From 9dc567c72a2ed12499f3d4118afa9c1704126c03 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Mon, 19 Oct 2026 15:34:45 -0700 Subject: [PATCH] =?UTF-8?q?TODO=20=C2=A765.4:=20a=20hierarchical=20path=20?= =?UTF-8?q?rooted=20at=20a=20top-level=20module=20resolves=20through=20the?= =?UTF-8?q?=20workspace=20(conservative)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `tb.dut.g_sw[0].buf_q` written in a file that does not declare `tb` now resolves like an instance path: the binder marks a dotted path's head (Target::PathHead), resolve/root.rs answers a plain lexical miss with a hierarchical external candidate, head_site roots the spine there, and fold_path walks it — every hop a module/interface surface. find_references, LSP references and rename see every segment; $root.tb works; a local `tb` shadows. FACTS_FORMAT 22. Rooted only when the root is provable (owner's ruling: conservative): not when the head has an import candidate (so `import uvm_pkg::*` with uvm_pkg outside the project stays warned — opentitan's DV force paths behave as before), not from inside a class, not beside a macro that stands where a declaration could (item, statement, port list), not when the root name is also a package or ambiguous. The LSP rename set adds the files of the path's root and middle hops (sources.rs, WorkspaceIndex::path_units_to). An unresolved path is warned once. QA (Opus) x2: F1-F4 and R1 silent-wrong-rename shapes fixed with tests; QA's attack cases 1-6 each warned or correctly renamed; lucisv check hw byte-identical to master. Completion after `tb.` deferred (TODO §65.8). tools/gates.sh: PASS, 15 steps, 5 180 tests, corpus 814/820. docs/features/top-rooted-paths. Co-Authored-By: Claude Opus 5.5 --- TODO.md | 17 +- crates/lucisv_server/src/server/tests/mod.rs | 2 + .../src/server/tests/references_top_rooted.rs | 106 +++ .../src/server/tests/rename_generate_label.rs | 4 +- .../server/tests/rename_top_rooted_scope.rs | 121 ++++ crates/lucisv_server/src/state/sources.rs | 12 + crates/vlog_refactor/src/rename/mod.rs | 31 +- crates/vlog_refactor/src/rename/paths.rs | 117 ++- crates/vlog_refactor/src/rename/warnings.rs | 32 +- .../tests/opentitan_top_rooted.rs | 155 ++++ .../vlog_refactor/tests/qa_generate_label.rs | 64 +- .../vlog_refactor/tests/qa_warning_scope.rs | 14 +- .../tests/rename_generate_label.rs | 5 +- .../vlog_refactor/tests/top_rooted_paths.rs | 343 +++++++++ crates/vlog_semantic/src/bind/expr.rs | 15 +- crates/vlog_semantic/src/bind/item.rs | 22 +- crates/vlog_semantic/src/bind/mod.rs | 26 +- crates/vlog_semantic/src/bind/stmt.rs | 4 +- crates/vlog_semantic/src/facts.rs | 10 +- crates/vlog_semantic/src/model.rs | 7 + crates/vlog_semantic/src/resolve.rs | 73 +- crates/vlog_semantic/src/resolve/root.rs | 85 +++ .../vlog_semantic/src/workspace/external.rs | 47 +- crates/vlog_semantic/src/workspace/mod.rs | 1 + .../vlog_semantic/src/workspace/path_units.rs | 72 ++ crates/vlog_semantic/tests/generate_blocks.rs | 16 +- crates/vlog_semantic/tests/member_access.rs | 12 +- .../vlog_semantic/tests/top_rooted_paths.rs | 338 +++++++++ docs/features/top-rooted-paths/README.md | 683 ++++++++++++++++++ 29 files changed, 2371 insertions(+), 63 deletions(-) create mode 100644 crates/lucisv_server/src/server/tests/references_top_rooted.rs create mode 100644 crates/lucisv_server/src/server/tests/rename_top_rooted_scope.rs create mode 100644 crates/vlog_refactor/tests/opentitan_top_rooted.rs create mode 100644 crates/vlog_refactor/tests/top_rooted_paths.rs create mode 100644 crates/vlog_semantic/src/resolve/root.rs create mode 100644 crates/vlog_semantic/src/workspace/path_units.rs create mode 100644 crates/vlog_semantic/tests/top_rooted_paths.rs create mode 100644 docs/features/top-rooted-paths/README.md diff --git a/TODO.md b/TODO.md index afe0f22..98bb2f6 100644 --- a/TODO.md +++ b/TODO.md @@ -7064,8 +7064,8 @@ tb.dut.gen_sw_assigns[i]…`) under `rename gen_sw_assigns`. Watch: a name that is both a local and a top module (the local wins), `$root.tb…`, and the index cost of the extra external candidates on every DV path. -- [ ] root lookup in `head_site`, the head recorded as a module use -- [ ] QA's repro renames the path instead of warning; the §65.1 warning +- [x] root lookup in `head_site`, the head recorded as a module use +- [x] QA's repro renames the path instead of warning; the §65.1 warning still fires for a root the workspace does not declare ### 65.6 Rename inside included fragments (lead to schedule; from §65.1 QA final H4) @@ -7115,4 +7115,15 @@ CLAUDE.md's pointer is the lead's at merge. **Then — §65.4 top-module-rooted paths** (serial, after lane A merges). -- [ ] §65.4's checklist above +- [x] §65.4's checklist above (conservative by the owner's ruling: a head with an import candidate, inside a class, or beside a macro that could declare it is not rooted) + + +### 65.8 Completion after a top-rooted path head (deferred from §65.4 H2, 2026-10-19) + +`tb.` offers nothing in completion: the completion walk keeps "an unknown +head answers nothing" (two `lucisv_server` completion tests pin it), while +resolution now roots an unknown head at a top module. Decide whether +completion should offer `tb.`'s hierarchical members, answering `None` when +the index has no unit of that name. `docs/features/top-rooted-paths`. + +- [ ] owner/lead decision; if yes, `completion/member.rs` + tests diff --git a/crates/lucisv_server/src/server/tests/mod.rs b/crates/lucisv_server/src/server/tests/mod.rs index 93653db..3974099 100644 --- a/crates/lucisv_server/src/server/tests/mod.rs +++ b/crates/lucisv_server/src/server/tests/mod.rs @@ -62,8 +62,10 @@ mod pull_diagnostics; mod qa_generate_label; mod qa_rename_implicit; mod references_scope; +mod references_top_rooted; mod rename_generate_label; mod rename_implicit; +mod rename_top_rooted_scope; mod requests; mod scan; mod scan_trace; diff --git a/crates/lucisv_server/src/server/tests/references_top_rooted.rs b/crates/lucisv_server/src/server/tests/references_top_rooted.rs new file mode 100644 index 0000000..cc26bdd --- /dev/null +++ b/crates/lucisv_server/src/server/tests/references_top_rooted.rs @@ -0,0 +1,106 @@ +//! A hierarchical path rooted at a top module another file declares, over +//! the wire (TODO §65.4): `references` at a member of the DUT lists every +//! segment of `tb.dut.g_sw[0].buf_q` in a DV file, whichever side is open, +//! and `rename` rewrites them. `docs/features/top-rooted-paths/README.md`. + +use super::*; + +const DUT: &str = "module dut_a;\n for (genvar i = 0; i < 2; i++) begin : g_sw\n logic buf_q;\n end\nendmodule\n"; +const TB: &str = "module tb;\n dut_a dut ();\nendmodule\n"; +const PROBE: &str = "module probe (output logic o);\n assign o = tb.dut.g_sw[0].buf_q;\n initial force tb.dut.g_sw[1].buf_q = 1'b0;\nendmodule\n"; + +/// The LSP position of the first `name` on 0-based `line` of `text`. +fn at(uri: &Uri, text: &str, line: usize, name: &str) -> Value { + let row = text.lines().nth(line).expect("the line"); + let character = row.find(name).expect("the name on that line"); + serde_json::json!({ + "textDocument": { "uri": uri }, + "position": { "line": line, "character": character }, + }) +} + +/// `(file name, 0-based line)` of every location in a `references` answer. +fn places(found: &Value) -> Vec<(String, u64)> { + let mut out: Vec<(String, u64)> = found + .as_array() + .expect("an array") + .iter() + .map(|l| { + let uri = l["uri"].as_str().unwrap_or("?"); + let name = uri.rsplit('/').next().unwrap_or("?").to_string(); + (name, l["range"]["start"]["line"].as_u64().unwrap_or(0)) + }) + .collect(); + out.sort(); + out +} + +/// The three-file tree with the named files open; the uris of `dut_a.sv` +/// and `probe.sv`. +fn session_with(tag: &str, open: &[&str]) -> (Tree, Session, Uri, Uri) { + let tree = Tree::new(tag); + let files = [("dut_a.sv", DUT), ("tb.sv", TB), ("probe.sv", PROBE)]; + for (name, text) in files { + tree.write(name, text); + } + let mut session = Session::wide(vec![tree.path.clone()], false); + for (name, text) in files.into_iter().filter(|(name, _)| open.contains(name)) { + session.open(&tree.path.join(name), text); + } + let uri = |name: &str| path_to_uri(&tree.path.join(name)).expect("a uri"); + let (dut, probe) = (uri("dut_a.sv"), uri("probe.sv")); + (tree, session, dut, probe) +} + +fn expected() -> Vec<(String, u64)> { + let place = |file: &str, line| (file.to_string(), line); + vec![place("dut_a.sv", 2), place("probe.sv", 1), place("probe.sv", 2)] +} + +fn references(session: &mut Session, mut params: Value) -> Vec<(String, u64)> { + params["context"] = serde_json::json!({ "includeDeclaration": true }); + places(&session.result(References::METHOD, params)) +} + +#[test] +fn references_at_the_member_list_the_path_in_the_closed_dv_file() { + let (_tree, mut session, dut, _) = session_with("toproot_refs_decl", &["dut_a.sv"]); + assert_eq!(references(&mut session, at(&dut, DUT, 2, "buf_q")), expected()); +} + +#[test] +fn references_at_the_paths_segment_reach_the_closed_declaration() { + let (_tree, mut session, _, probe) = session_with("toproot_refs_path", &["probe.sv"]); + assert_eq!(references(&mut session, at(&probe, PROBE, 2, "buf_q")), expected()); +} + +#[test] +fn references_with_both_files_open_are_the_same_set() { + let (_tree, mut session, _, probe) = + session_with("toproot_refs_both", &["dut_a.sv", "probe.sv"]); + assert_eq!(references(&mut session, at(&probe, PROBE, 1, "buf_q")), expected()); +} + +#[test] +fn references_at_the_root_list_every_path_it_heads() { + let (_tree, mut session, _, probe) = session_with("toproot_refs_root", &["probe.sv"]); + let found = references(&mut session, at(&probe, PROBE, 1, "tb")); + let tb = ("tb.sv".to_string(), 0); + assert_eq!(found, vec![("probe.sv".to_string(), 1), ("probe.sv".to_string(), 2), tb]); +} + +#[test] +fn rename_at_the_block_label_rewrites_the_paths_in_the_dv_file() { + let (tree, mut session, dut, _) = session_with("toproot_rename", &["dut_a.sv"]); + let mut params = at(&dut, DUT, 1, "g_sw"); + params["newName"] = serde_json::json!("g_hw"); + let answer = session.request(Rename::METHOD, params).response_result.expect("renames"); + let changes = answer["changes"].as_object().expect("changes"); + let count = |path: &str| { + let uri = path_to_uri(&tree.path.join(path)).expect("a uri"); + changes.get(uri.as_str()).and_then(Value::as_array).map_or(0, Vec::len) + }; + assert_eq!((count("dut_a.sv"), count("probe.sv"), count("tb.sv")), (1, 2, 0), "{answer:#}"); + let mut texts = changes.values().flat_map(|e| e.as_array().into_iter().flatten()); + assert!(texts.all(|e| e["newText"] == "g_hw"), "{answer:#}"); +} diff --git a/crates/lucisv_server/src/server/tests/rename_generate_label.rs b/crates/lucisv_server/src/server/tests/rename_generate_label.rs index f872179..076ee9d 100644 --- a/crates/lucisv_server/src/server/tests/rename_generate_label.rs +++ b/crates/lucisv_server/src/server/tests/rename_generate_label.rs @@ -128,7 +128,8 @@ fn references_at_a_nested_blocks_member_reach_the_path_from_another_file() { /// QA F1 over the wire: an open buffer is always in the rename's set, so its /// path through the label that resolves to nothing (`tb.u_x.…`, rooted at a -/// top module this server cannot resolve) is shown as a warning, unedited. +/// top module no file in the tree declares — TODO §65.4 resolves the root +/// when one does) is shown as a warning, unedited. #[test] fn an_unresolved_path_in_an_open_buffer_is_shown_as_a_rename_warning() { const PROBE: &str = @@ -147,4 +148,5 @@ fn an_unresolved_path_in_an_open_buffer_is_shown_as_a_rename_warning() { shown.iter().any(|(_, m)| m.contains("probe.sv:2:") && m.contains("`g_lane`")), "{shown:?}" ); + assert!(!shown.iter().any(|(_, m)| m.contains("more")), "said once: {shown:?}"); } diff --git a/crates/lucisv_server/src/server/tests/rename_top_rooted_scope.rs b/crates/lucisv_server/src/server/tests/rename_top_rooted_scope.rs new file mode 100644 index 0000000..90bdbfd --- /dev/null +++ b/crates/lucisv_server/src/server/tests/rename_top_rooted_scope.rs @@ -0,0 +1,121 @@ +//! A rename through a hierarchical path rooted at a top module, under the +//! shipped **folder** scope (top-rooted-paths QA F3): the rename's file set +//! holds the files declaring every unit the path walks through — the root +//! `tb` and each hop's type — so a three-hop `tb.dut.u_core.sig` is renamed +//! exactly as the whole-set engine renames it, from the declaration or from +//! the segment. A hop outside the scope leaves the path warned about, and a +//! rename from its segment is refused with the accurate reason. + +use super::*; + +const CORE: &str = "module core;\n logic sig;\nendmodule\n"; +const DUT: &str = "module dut_a;\n core u_core ();\n logic top_sig;\n for (genvar i = 0; i < 2; i++) begin : g_sw\n logic buf_q;\n end\nendmodule\n"; +const TB: &str = "module tb;\n dut_a dut ();\nendmodule\n"; +const PROBE: &str = "module probe;\n initial force tb.dut.u_core.sig = 1'b0;\n initial force tb.dut.top_sig = 1'b0;\n initial force tb.dut.g_sw[1].buf_q = 1'b0;\nendmodule\n"; + +/// The opentitan shape: `ip/blk/{rtl,dv}`, with `tb.sv` at `tb_at`. +fn fixture(tag: &str, tb_at: &str) -> Tree { + let tree = Tree::new(tag); + tree.write("ip/blk/rtl/core.sv", CORE); + tree.write("ip/blk/rtl/dut_a.sv", DUT); + tree.write(tb_at, TB); + tree.write("ip/blk/dv/probe.sv", PROBE); + tree +} + +/// The LSP position of the first `name` on 0-based `line` of `text`. +fn at(uri: &Uri, text: &str, line: usize, name: &str) -> Value { + let row = text.lines().nth(line).expect("the line"); + let character = row.find(name).expect("the name on that line"); + serde_json::json!({ + "textDocument": { "uri": uri }, + "position": { "line": line, "character": character }, + }) +} + +/// The number of edits a rename answer makes in each of `files`. +fn edits(tree: &Tree, answer: &Value, files: &[&str]) -> Vec { + let changes = answer["changes"].as_object().expect("changes"); + files + .iter() + .map(|rel| { + let uri = path_to_uri(&tree.path.join(rel)).expect("a uri"); + changes.get(uri.as_str()).and_then(Value::as_array).map_or(0, Vec::len) + }) + .collect() +} + +fn rename(session: &mut Session, mut params: Value, new: &str) -> Result { + params["newName"] = serde_json::json!(new); + session.request(Rename::METHOD, params).response_result.map_err(|e| format!("{e:?}")) +} + +const FILES: [&str; 2] = ["ip/blk/rtl/core.sv", "ip/blk/dv/probe.sv"]; + +#[test] +fn a_three_hop_path_is_renamed_from_the_declaration() { + let tree = fixture("toproot_scope_decl", "ip/blk/dv/tb.sv"); + let mut session = Session::new(vec![tree.path.clone()], false); + let core = session.open(&tree.path.join(FILES[0]), CORE); + let answer = rename(&mut session, at(&core, CORE, 1, "sig"), "sig2").expect("renames"); + assert_eq!(edits(&tree, &answer, &FILES), vec![1, 1], "{answer:#}"); + assert!(session.shown().is_empty(), "nothing to warn about: {:?}", session.shown()); +} + +#[test] +fn a_three_hop_path_is_renamed_from_its_segment() { + let tree = fixture("toproot_scope_seg", "ip/blk/dv/tb.sv"); + let mut session = Session::new(vec![tree.path.clone()], false); + let probe = session.open(&tree.path.join(FILES[1]), PROBE); + let answer = rename(&mut session, at(&probe, PROBE, 1, "sig"), "sig2").expect("renames"); + assert_eq!(edits(&tree, &answer, &FILES), vec![1, 1], "{answer:#}"); +} + +#[test] +fn a_member_of_a_generate_block_is_renamed_through_the_path() { + let tree = fixture("toproot_scope_block", "ip/blk/dv/tb.sv"); + let mut session = Session::new(vec![tree.path.clone()], false); + let dut = session.open(&tree.path.join("ip/blk/rtl/dut_a.sv"), DUT); + let answer = rename(&mut session, at(&dut, DUT, 4, "buf_q"), "buf_r").expect("renames"); + let files = ["ip/blk/rtl/dut_a.sv", "ip/blk/dv/probe.sv"]; + assert_eq!(edits(&tree, &answer, &files), vec![1, 1], "{answer:#}"); +} + +/// The LSP rename equals the engine's over the scope's files. +#[test] +fn the_lsp_rename_equals_the_engine_over_the_scope() { + let tree = fixture("toproot_scope_engine", "ip/blk/dv/tb.sv"); + let mut session = Session::new(vec![tree.path.clone()], false); + let core = session.open(&tree.path.join(FILES[0]), CORE); + let answer = rename(&mut session, at(&core, CORE, 1, "sig"), "sig2").expect("renames"); + let sources = session.server.workspace.sources(); + let path = tree.path.join(FILES[0]); + let offset = CORE.find("sig").expect("sig") as u32; + let engine = vlog_refactor::rename(&sources, &path, offset, "sig2").expect("engine renames"); + let lsp = edits(&tree, &answer, &FILES); + let whole: Vec = + FILES.iter().map(|rel| engine.edits_for(&tree.path.join(rel)).len()).collect(); + assert_eq!(lsp, whole); +} + +/// `tb.sv` outside the folder scope: the index cannot resolve the root, so +/// the open probe's path is left and warned about, and a rename asked from +/// its segment is refused for what it is — an unresolved path. +#[test] +fn a_root_outside_the_scope_is_warned_and_refused_accurately() { + let tree = fixture("toproot_scope_out", "top/dv/tb.sv"); + let mut session = Session::new(vec![tree.path.clone()], false); + let probe = session.open(&tree.path.join(FILES[1]), PROBE); + let core = session.open(&tree.path.join(FILES[0]), CORE); + let in_index = + session.server.workspace.index().files().contains(&tree.path.join("top/dv/tb.sv")); + assert!(!in_index, "premise: the root's file is outside the scope"); + let _ = session.drain(); + let answer = rename(&mut session, at(&core, CORE, 1, "sig"), "sig2").expect("renames"); + assert_eq!(edits(&tree, &answer, &FILES), vec![1, 0], "{answer:#}"); + let shown = session.shown(); + assert!(shown.iter().any(|(_, m)| m.contains("probe.sv:2:")), "{shown:?}"); + let why = rename(&mut session, at(&probe, PROBE, 1, "sig"), "sig3").expect_err("refused"); + assert!(why.contains("hierarchical path"), "{why}"); + assert!(!why.contains("declared outside"), "{why}"); +} diff --git a/crates/lucisv_server/src/state/sources.rs b/crates/lucisv_server/src/state/sources.rs index f1a8e18..8c40915 100644 --- a/crates/lucisv_server/src/state/sources.rs +++ b/crates/lucisv_server/src/state/sources.rs @@ -281,6 +281,18 @@ impl Workspace { for site in self.index.references_to(def) { wanted.extend(self.index.path(site.file).map(Path::to_path_buf)); } + // A use written as a hierarchical path (`tb.dut.u_core.sig`) resolves + // inside the engine's set only if the set declares every unit the + // path walks through — the top module it is rooted at and each hop's + // type — so their declaring files come too (top-rooted-paths QA F3). + // Only files the index has: a unit outside the scope is not in it, + // and the path stays unresolved and warned about. + wanted.on(Rung::Declaration); + for unit in self.index.path_units_to(def) { + for unit_def in self.index.units(&unit) { + wanted.extend(self.index.path(unit_def.file).map(Path::to_path_buf)); + } + } } /// Every file that instantiates a name — the census the reference postings diff --git a/crates/vlog_refactor/src/rename/mod.rs b/crates/vlog_refactor/src/rename/mod.rs index 5db9b53..29d366d 100644 --- a/crates/vlog_refactor/src/rename/mod.rs +++ b/crates/vlog_refactor/src/rename/mod.rs @@ -49,8 +49,8 @@ use vlog_parser::span::TextRange; use vlog_parser::token::{is_keyword, TokenKind}; use vlog_parser::tokenize; use vlog_semantic::{ - Def, ExternalResolutions, ExternalTarget, ReferenceId, Resolution, Semantics, Symbol, SymbolId, - WorkspaceIndex, + Def, ExternalResolutions, ExternalTarget, ReferenceId, Resolution, Semantics, Surface, Symbol, + SymbolId, WorkspaceIndex, }; use crate::trace::RenameTrace; @@ -130,6 +130,7 @@ pub fn prepare_rename_here( Ok(RenameTarget { range: cursor, name: reference.name.clone() }) } Some(ExternalTarget::Ambiguous(_)) => Err(ambiguous(&reference.name)), + _ if hierarchical(&reference.resolution) => Err(unresolved_path(&reference.name)), _ => Err(declared_outside(&reference.name)), }, } @@ -366,7 +367,15 @@ impl<'a> Scope<'a> { return Err(from_base(&name, base)) } Resolution::ExternalCandidate { .. } => { - Found::Elsewhere(name, cursor, analysis.external.get(id).cloned()) + let answer = analysis.external.get(id).cloned(); + let answered = matches!( + answer, + Some(ExternalTarget::Resolved(_) | ExternalTarget::Ambiguous(_)) + ); + if !answered && hierarchical(&reference.resolution) { + return Err(unresolved_path(&name)); + } + Found::Elsewhere(name, cursor, answer) } } } @@ -594,6 +603,22 @@ fn from_base(name: &str, base: &str) -> String { ) } +/// Whether a use is a segment of a hierarchical path (its candidate reads a +/// module's hierarchical surface) — the one external candidate whose miss is +/// not "declared outside the indexed files" but "the path did not resolve". +fn hierarchical(resolution: &Resolution) -> bool { + matches!(resolution, Resolution::ExternalCandidate { surface: Surface::Hierarchical, .. }) +} + +/// The refusal for a path segment the workspace could not walk to a +/// declaration (top-rooted-paths QA F3): a unit the path passes through is +/// not in the files lucisv reads, or several files declare it. +fn unresolved_path(name: &str) -> String { + format!( + "`{name}` is a segment of a hierarchical path lucisv could not resolve to one declaration (a unit the path passes through is not among the files lucisv indexes, or is declared more than once); rename the declaration itself." + ) +} + fn declared_outside(name: &str) -> String { format!( "`{name}` is declared outside the files lucisv indexes, so a rename here would only be half a rename." diff --git a/crates/vlog_refactor/src/rename/paths.rs b/crates/vlog_refactor/src/rename/paths.rs index 78c4c1c..ab98175 100644 --- a/crates/vlog_refactor/src/rename/paths.rs +++ b/crates/vlog_refactor/src/rename/paths.rs @@ -2,12 +2,20 @@ //! loud (generate-label-rename QA F1). //! //! [`Scope::unresolved_path_warnings`]: a segment spelling the renamed name, -//! in *any* file of the set, that resolved to no declaration at all -//! (`tb.dut.g_sw[0].q`, where `tb` is a top module another file declares and -//! nothing resolves the root — TODO §65.4). The rename cannot know whether -//! that path reaches the renamed declaration, so it is left unchanged and -//! named. A segment that resolved to a *different* declaration is not news -//! and is not reported. (The same-label arms are `arms.rs`.) +//! in *any* file of the set, that resolved to no declaration at all — no +//! reference, or `NotFound` (`tb.dut.g_sw[0].q` where a local `logic tb` +//! shadows the top module, so the spine stops at a net). The rename cannot +//! know whether that path reaches the renamed declaration, so it is left +//! unchanged and named. A segment that resolved to a *different* declaration +//! is not news and is not reported. (The same-label arms are `arms.rs`.) +//! +//! Since TODO §65.4 a path rooted at a top module another file declares +//! (`tb.dut.g_sw[0].q`, `$root.tb.…`) resolves when the workspace can walk +//! it, and every segment of it is renamed with its declaration. When the +//! workspace cannot — the root is declared nowhere, or by several files +//! (`tb` in seventy opentitan testbenches) — the segment is an external +//! candidate the index left unanswered, and it is named here too: such a +//! path is exactly what this scan was written for. //! //! Narrowed by the index's word census and then by a text test for a `.` or //! `[` beside the name, so a file is analysed only when it could hold such a @@ -16,9 +24,9 @@ use vlog_parser::token::{Token, TokenKind}; use vlog_parser::tokenize; -use vlog_semantic::{Resolution, Semantics}; +use vlog_semantic::{ExternalResolutions, ExternalTarget, Resolution, Semantics, Surface}; -use crate::scope::Scope; +use crate::scope::{Analysis, Scope}; impl<'a> Scope<'a> { /// One warning per file listing the lines where a path segment spelling @@ -42,8 +50,7 @@ impl<'a> Scope<'a> { let Some(path) = self.path(i) else { continue }; let Ok(tokens) = tokenize(text) else { continue }; let Some(analysis) = self.analysis(i) else { continue }; - let lines = - unresolved_segments(&analysis.semantics, &tokens, name, edited.contains(&i)); + let lines = unresolved_segments(analysis, &tokens, name, edited.contains(&i)); if lines.is_empty() { continue; } @@ -58,9 +65,16 @@ impl<'a> Scope<'a> { } /// The 1-based lines of `name` tokens that are a path segment and resolved to -/// nothing: no reference at all (unless `edited`, see the caller), or a -/// reference whose resolution is `NotFound`. -fn unresolved_segments(sem: &Semantics, tokens: &[Token], name: &str, edited: bool) -> Vec { +/// nothing: no reference at all (unless `edited`, see the caller), a +/// reference whose resolution is `NotFound`, or a segment of a top-rooted +/// path the workspace left unanswered ([`top_rooted_miss`]). +fn unresolved_segments( + analysis: &Analysis, + tokens: &[Token], + name: &str, + edited: bool, +) -> Vec { + let sem = &analysis.semantics; let mut lines: Vec = Vec::new(); for (i, token) in tokens.iter().enumerate() { if token.kind != TokenKind::Ident || token.text != name || !is_segment(tokens, i) { @@ -70,7 +84,13 @@ fn unresolved_segments(sem: &Semantics, tokens: &[Token], name: &str, edited: bo continue; } let unresolved = match sem.reference_at(token.span.start) { - Some(r) if r.name_span == token.span => matches!(r.resolution, Resolution::NotFound), + Some(r) if r.name_span == token.span => match r.resolution { + Resolution::NotFound => true, + Resolution::ExternalCandidate { surface: Surface::Hierarchical, .. } => { + top_rooted_miss(sem, &analysis.external, tokens, i) + } + _ => false, + }, _ => !edited, }; if unresolved && lines.last() != Some(&token.line) { @@ -80,6 +100,75 @@ fn unresolved_segments(sem: &Semantics, tokens: &[Token], name: &str, edited: bo lines } +/// Whether this scan names the use whose name starts at `offset`: a path +/// segment of a top-rooted path the workspace left unanswered. Asked by +/// `warnings.rs`'s unresolved-candidate scan, which skips such a use so each +/// line is said once, in this scan's words (Handshake H1, lead-granted). +pub(super) fn names_top_rooted_miss(analysis: &Analysis, tokens: &[Token], offset: u32) -> bool { + let Ok(i) = tokens.binary_search_by_key(&offset, |t| t.span.start) else { return false }; + is_segment(tokens, i) && top_rooted_miss(&analysis.semantics, &analysis.external, tokens, i) +} + +/// Whether the segment at `i` is part of a path rooted at a top-level module +/// — its head is `$root`, or a name this file does not declare, which the +/// semantic layer records as a candidate for the unit table on the +/// hierarchical surface — **and** the workspace answered the segment with +/// nothing. An ambiguous answer is not this scan's: when it can name the +/// renamed declaration the rename is refused outright, and when it cannot, +/// the path is another declaration's. +fn top_rooted_miss( + sem: &Semantics, + external: &ExternalResolutions, + tokens: &[Token], + i: usize, +) -> bool { + let answered = sem.reference_id_at(tokens[i].span.start).and_then(|id| external.get(id)); + if !matches!(answered, Some(ExternalTarget::StillUnresolved)) { + return false; + } + let Some(head) = path_head(tokens, i) else { return false }; + if head.text == "$root" { + return true; + } + match sem.reference_at(head.span.start) { + Some(r) if r.name_span == head.span => matches!( + &r.resolution, + Resolution::ExternalCandidate { surface: Surface::Hierarchical, paths } + if paths.last().is_some_and(|last| *last == head.text) + ), + _ => false, + } +} + +/// The first token of the dotted path the identifier at `i` is a segment of: +/// back over each `.` and the element selects before it (`g[0][k].x`). +fn path_head(tokens: &[Token], mut i: usize) -> Option<&Token> { + while i >= 2 && tokens[i - 1].is_sym(".") { + let mut j = i - 2; + while tokens[j].is_sym("]") { + j = matching_open(tokens, j)?.checked_sub(1)?; + } + i = j; + } + tokens.get(i) +} + +/// The `[` that opens the `]` at `close`. +fn matching_open(tokens: &[Token], close: usize) -> Option { + let mut depth = 0usize; + for j in (0..=close).rev() { + if tokens[j].is_sym("]") { + depth += 1; + } else if tokens[j].is_sym("[") { + depth -= 1; + if depth == 0 { + return Some(j); + } + } + } + None +} + /// Whether the identifier at `i` is one segment of a dotted path: a `.` /// before it, or a `.` after it past any element selects (`g[0][1].x`). fn is_segment(tokens: &[Token], i: usize) -> bool { diff --git a/crates/vlog_refactor/src/rename/warnings.rs b/crates/vlog_refactor/src/rename/warnings.rs index 8394519..00ecdf3 100644 --- a/crates/vlog_refactor/src/rename/warnings.rs +++ b/crates/vlog_refactor/src/rename/warnings.rs @@ -21,11 +21,12 @@ use vlog_parser::defines::DefineKind; use vlog_parser::span::TextRange; use vlog_parser::token::{Token, TokenKind}; use vlog_parser::{tokenize, LineIndex}; -use vlog_semantic::{ExternalTarget, ReferenceId, Resolution}; +use vlog_semantic::{ExternalTarget, ReferenceId, Resolution, Surface}; use crate::TextEdit; use super::carry::argument_position; +use super::paths; use super::scoped::{binds_into, spellings, Scoping}; use super::Target; use crate::scope::Scope; @@ -524,10 +525,9 @@ impl<'a> Scope<'a> { return Vec::new(); } let where_ = self.name_of(path); - let lines = scan.lines(text); let Some(analysis) = self.analysis(file) else { return Vec::new() }; - // Unit that could not be found → the lines it was named on. - let mut groups: Vec<(String, Vec)> = Vec::new(); + // The unanswered candidates: (unit, offset, on the hierarchical surface). + let mut hits: Vec<(String, u32, bool)> = Vec::new(); for (i, reference) in analysis.semantics.references().iter().enumerate() { if reference.name != name { continue; @@ -542,7 +542,29 @@ impl<'a> Scope<'a> { ) { continue; } - let line = lines.line_col(reference.name_span.start).0; + let hierarchical = matches!( + reference.resolution, + Resolution::ExternalCandidate { surface: Surface::Hierarchical, .. } + ); + hits.push((unit, reference.name_span.start, hierarchical)); + } + // A segment of a top-rooted path is the §65.1 path scan's to name + // (`paths.rs`); naming it here too would say the line twice. Lexed + // only when a hierarchical candidate could be one. + let (tokens, lines) = if hits.iter().any(|(_, _, h)| *h) { + scan.tokens_and_lines(text) + } else { + (None, scan.lines(text)) + }; + // Unit that could not be found → the lines it was named on. + let mut groups: Vec<(String, Vec)> = Vec::new(); + for (unit, offset, hierarchical) in hits { + let path_line = hierarchical + && tokens.is_some_and(|t| paths::names_top_rooted_miss(analysis, t, offset)); + if path_line { + continue; + } + let line = lines.line_col(offset).0; match groups.iter_mut().find(|(u, _)| *u == unit) { Some((_, at)) => at.push(line), None => groups.push((unit, vec![line])), diff --git a/crates/vlog_refactor/tests/opentitan_top_rooted.rs b/crates/vlog_refactor/tests/opentitan_top_rooted.rs new file mode 100644 index 0000000..b47335d --- /dev/null +++ b/crates/vlog_refactor/tests/opentitan_top_rooted.rs @@ -0,0 +1,155 @@ +//! TODO §65.4 on a real checkout: `rename keymgr_dpe.gen_sw_assigns`, whose +//! DV interface writes `force tb.dut.gen_sw_assigns[i]…` (a path rooted at a +//! top module another file declares, IEEE 1800 §23.6). +//! +//! Two file sets, because the answer depends on how many `module tb` the set +//! holds (`docs/features/top-rooted-paths/README.md`): +//! +//! * **the IP folder** `hw/ip/keymgr_dpe` — what the language server indexes +//! under its shipped folder scope for a file there. One `tb`; but the +//! interface imports `uvm_pkg::*` and `keymgr_dpe_env_pkg::*`, either of +//! which could supply `tb` by the LRM (and `uvm_pkg` is not in the tree), +//! so the head is not provably the top module and the path is left and +//! named (the rework after QA, F2). +//! * **the whole `hw` tree** — what `lucisv-mcp` hands the engine. Seventy +//! files declare `module tb`, so `tb.dut` names seventy instances and the +//! path resolves to nothing; the rename leaves it and says so. +//! +//! `#[ignore]`: it needs the checkout, which it only reads — the edit is +//! computed, never applied. Run with `LUCISV_OPENTITAN=/path/to/opentitan +//! tools/guard.sh -- cargo test -p vlog_refactor --test opentitan_top_rooted +//! -- --ignored --nocapture`; without the variable it looks in +//! `~/.cache/lucisv-eval/ot`, and it skips (passing, with a line on stderr) +//! when neither holds the IP. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::time::Instant; + +use vlog_refactor::rename; + +const RTL: &str = "hw/ip/keymgr_dpe/rtl/keymgr_dpe.sv"; +const IF: &str = "hw/ip/keymgr_dpe/dv/env/keymgr_dpe_if.sv"; + +fn checkout() -> Option { + let root = std::env::var_os("LUCISV_OPENTITAN").map(PathBuf::from).or_else(|| { + std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".cache/lucisv-eval/ot")) + })?; + root.join(RTL).is_file().then_some(root) +} + +/// Every `.sv`/`.svh`/`.v` file under `dir`, with its text, path-sorted. +fn sources(dir: &Path) -> Vec<(PathBuf, String)> { + let mut out = Vec::new(); + let mut stack = vec![dir.to_path_buf()]; + while let Some(d) = stack.pop() { + let Ok(entries) = fs::read_dir(&d) else { continue }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + stack.push(path); + } else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "svh" | "v")) + { + if let Ok(text) = fs::read_to_string(&path) { + out.push((path, text)); + } + } + } + } + out.sort(); + out +} + +/// The rename over one set: the 1-based lines it edits in the interface file, +/// how many sites in how many files, and the warnings naming the interface. +fn probe(root: &Path, set: &str) -> (Vec, usize, usize, Vec) { + let files = sources(&root.join(set)); + let rtl = root.join(RTL); + let text = &files.iter().find(|(p, _)| *p == rtl).expect("the rtl is in the set").1; + let offset = text.find("begin : gen_sw_assigns").expect("the label") + "begin : ".len(); + let started = Instant::now(); + let edit = rename(&files, &rtl, offset as u32, "gen_sw_asg").expect("renames"); + let took = started.elapsed(); + let iface = root.join(IF); + let if_text = &files.iter().find(|(p, _)| *p == iface).expect("the interface").1; + let lines: Vec = edit + .edits_for(&iface) + .iter() + .map(|e| if_text[..e.range.start as usize].matches('\n').count() + 1) + .collect(); + let touched: Vec<&PathBuf> = + files.iter().map(|(p, _)| p).filter(|p| !edit.edits_for(p).is_empty()).collect(); + let sites: usize = touched.iter().map(|p| edit.edits_for(p).len()).sum(); + let warned: Vec = + edit.warnings.iter().filter(|w| w.contains("keymgr_dpe_if.sv")).cloned().collect(); + eprintln!( + "{set}: {} files, {sites} sites in {} files, {} warnings ({} naming the interface), {took:.2?}", + files.len(), + touched.len(), + edit.warnings.len(), + warned.len() + ); + for w in &edit.warnings { + eprintln!(" warning: {w}"); + } + (lines, sites, touched.len(), warned) +} + +#[test] +#[ignore = "needs an opentitan checkout"] +fn the_ip_folder_leaves_the_imported_head_and_says_so() { + let Some(root) = checkout() else { + eprintln!("skipped: no opentitan checkout"); + return; + }; + let (lines, _, _, warned) = probe(&root, "hw/ip/keymgr_dpe"); + assert!(lines.is_empty(), "an import could supply `tb`: {lines:?}"); + let said: Vec<&String> = warned.iter().filter(|w| w.contains("514")).collect(); + assert_eq!(said.len(), 1, "the force lines are said once: {warned:?}"); +} + +#[test] +#[ignore = "needs an opentitan checkout"] +fn the_whole_tree_leaves_the_ambiguous_root_and_says_so() { + let Some(root) = checkout() else { + eprintln!("skipped: no opentitan checkout"); + return; + }; + let (lines, _, _, warned) = probe(&root, "hw"); + assert!(lines.is_empty(), "seventy `tb`s: the path names nothing: {lines:?}"); + let said: Vec<&String> = warned.iter().filter(|w| w.contains("514")).collect(); + assert_eq!(said.len(), 1, "the force lines are said once: {warned:?}"); +} + +/// The index cost of the extra external references: the facts every file +/// records (encoded bytes — the persistent store's size), the reference +/// postings the merge resolves them into, and the wall time of the build, +/// best of three. Prints only; the before/after is the feature README's. +#[test] +#[ignore = "needs an opentitan checkout"] +fn index_cost_over_the_whole_tree() { + let Some(root) = checkout() else { + eprintln!("skipped: no opentitan checkout"); + return; + }; + let files = sources(&root.join("hw")); + let bytes: usize = files + .iter() + .map(|(p, t)| vlog_semantic::FileFacts::of(p.clone(), t).encode().map_or(0, |s| s.len())) + .sum(); + let mut best: Option = None; + let mut sizes = None; + for _ in 0..3 { + let started = Instant::now(); + let index = vlog_semantic::WorkspaceIndex::build( + files.iter().map(|(p, t)| (p.clone(), t.as_str())), + ); + let took = started.elapsed(); + best = Some(best.map_or(took, |b| b.min(took))); + sizes = Some(index.table_sizes()); + } + eprintln!( + "index over {} files: facts {bytes} bytes, {sizes:?}, build best of 3 {best:.2?}", + files.len() + ); +} diff --git a/crates/vlog_refactor/tests/qa_generate_label.rs b/crates/vlog_refactor/tests/qa_generate_label.rs index 881aebf..2ada1da 100644 --- a/crates/vlog_refactor/tests/qa_generate_label.rs +++ b/crates/vlog_refactor/tests/qa_generate_label.rs @@ -529,15 +529,15 @@ endmodule let files = [("dut_a.sv", dut), ("tb.sv", tb), ("probe.sv", probe)]; complete_or_loud(&renamed(&files, "dut_a.sv", "begin : ", "g_sw", "g_hw"), "g_sw"); complete_or_loud(&renamed(&files, "dut_a.sv", "logic ", "buf_q", "buf_r"), "buf_q"); - // Lead's ruling on F1: the path rooted at another file's top module does - // not resolve, so it is left unchanged — and said so, with its line. + // TODO §65.4 (superseding the lead's F1 ruling, which warned): the root + // `tb` is the top module `tb.sv` declares (IEEE 1800 §23.6), so the path + // resolves and is renamed with the declaration — and nothing is warned. for (prefix, old, new) in [("begin : ", "g_sw", "g_hw"), ("logic ", "buf_q", "buf_r")] { let (texts, warnings) = renamed(&files, "dut_a.sv", prefix, old, new).expect("renames"); assert_eq!(texts[0], dut.replace(old, new), "the declaration moves"); - assert_eq!((texts[1].as_str(), texts[2].as_str()), (tb, probe), "nothing else is edited"); - let said: Vec<&String> = warnings.iter().filter(|w| w.contains("probe.sv:2:")).collect(); - assert_eq!(said.len(), 1, "one warning for the unresolved path: {warnings:?}"); - assert!(said[0].contains(&format!("`{old}`")), "{said:?}"); + assert_eq!(texts[1], tb, "the testbench does not spell the name"); + assert_eq!(texts[2], probe.replace(old, new), "the path moves with it"); + assert!(warnings.is_empty(), "{warnings:?}"); } } @@ -619,16 +619,48 @@ fn rc_files() -> Vec<(&'static str, &'static str)> { vec![("dut_a.sv", RC_DUT), ("dut_b.sv", RC_OTHER), ("tb.sv", RC_TB), ("probe.sv", RC_PROBE)] } +/// The set without `tb.sv`: nothing declares the root `tb`, so no path +/// rooted at it can resolve (TODO §65.4 — with `tb.sv` in the set they do). +fn rc_files_without_the_root() -> Vec<(&'static str, &'static str)> { + rc_files().into_iter().filter(|(name, _)| *name != "tb.sv").collect() +} + #[test] fn recheck_every_unresolved_path_shape_is_named_once_with_its_lines() { let (texts, warnings) = - renamed(&rc_files(), "dut_a.sv", "begin : ", "g_sw", "g_hw").expect("renames"); - assert_eq!(texts[3], RC_PROBE, "the probe is never edited"); + renamed(&rc_files_without_the_root(), "dut_a.sv", "begin : ", "g_sw", "g_hw") + .expect("renames"); + assert_eq!(texts[2], RC_PROBE, "the probe is never edited"); let said: Vec<&String> = warnings.iter().filter(|w| w.contains("probe.sv")).collect(); assert_eq!(said.len(), 1, "one line for the file: {warnings:?}"); assert!(said[0].starts_with("probe.sv:2,3,4,6:"), "{said:?}"); } +/// TODO §65.4: with the root declared, every path shape is renamed and the +/// comment, the string and the connection to an unknown module are not. +#[test] +fn every_path_shape_rooted_at_a_declared_top_module_is_renamed() { + let (texts, warnings) = + renamed(&rc_files(), "dut_a.sv", "begin : ", "g_sw", "g_hw").expect("renames"); + let code: Vec<&str> = RC_PROBE.lines().collect(); + let want: Vec = code + .iter() + .enumerate() + .map( + |(i, l)| { + if [1, 2, 3, 5].contains(&i) { + l.replace("g_sw", "g_hw") + } else { + l.to_string() + } + }, + ) + .collect(); + assert_eq!(texts[3], want.join("\n") + "\n"); + assert_eq!(texts[1], RC_OTHER, "`dut_b`'s block is another declaration"); + assert!(warnings.is_empty(), "{warnings:?}"); +} + #[test] fn recheck_a_path_that_resolves_to_another_declaration_is_not_warned_about() { let user = "module user (output logic o); @@ -646,11 +678,17 @@ endmodule fn recheck_an_included_fragment_is_scanned_like_any_file() { let frag = " initial force tb.dut.g_sw[0].buf_q = 1'b1;\n"; let host = "module host;\n`include \"frag.svh\"\nendmodule\n"; - let mut files = rc_files(); + let mut files = rc_files_without_the_root(); files.push(("frag.svh", frag)); files.push(("host.sv", host)); let (_, warnings) = renamed(&files, "dut_a.sv", "begin : ", "g_sw", "g_hw").expect("renames"); assert!(warnings.iter().any(|w| w.starts_with("frag.svh:1:")), "{warnings:?}"); + // TODO §65.4: with the root declared, the fragment's path is renamed. + let mut files = rc_files(); + files.push(("frag.svh", frag)); + files.push(("host.sv", host)); + let (texts, _) = renamed(&files, "dut_a.sv", "begin : ", "g_sw", "g_hw").expect("renames"); + assert_eq!(texts[4], frag.replace("g_sw", "g_hw")); } /// The word census holds no escaped identifier (`words.rs`: "an escaped @@ -660,11 +698,17 @@ fn recheck_an_escaped_label_behind_an_unresolved_root_is_named() { let dut = "module dut_e;\n if (1) begin : \\g$sw \n logic q;\n end\nendmodule\n"; let tb = "module tbe;\n dut_e dut ();\nendmodule\n"; let probe = "module pe (output logic o);\n assign o = tbe.dut.\\g$sw .q;\nendmodule\n"; - let files = [("dut_e.sv", dut), ("tbe.sv", tb), ("pe.sv", probe)]; + // Without `tbe.sv` nothing declares the root, and the path is named. + let files = [("dut_e.sv", dut), ("pe.sv", probe)]; let result = renamed(&files, "dut_e.sv", "begin : ", "\\g$sw", "g_hw"); complete_or_loud(&result, "\\g$sw"); let (_, warnings) = result.expect("renames"); assert!(warnings.iter().any(|w| w.starts_with("pe.sv:2:")), "{warnings:?}"); + // TODO §65.4: with it, the escaped segment is renamed. + let files = [("dut_e.sv", dut), ("tbe.sv", tb), ("pe.sv", probe)]; + let (texts, warnings) = + renamed(&files, "dut_e.sv", "begin : ", "\\g$sw", "g_hw").expect("renames"); + assert_eq!(texts[2], probe.replace("\\g$sw", "g_hw"), "{warnings:?}"); } #[test] diff --git a/crates/vlog_refactor/tests/qa_warning_scope.rs b/crates/vlog_refactor/tests/qa_warning_scope.rs index 8d79bf3..d484cad 100644 --- a/crates/vlog_refactor/tests/qa_warning_scope.rs +++ b/crates/vlog_refactor/tests/qa_warning_scope.rs @@ -175,17 +175,16 @@ endmodule } /// Rework 2, R1: three files named `probe.sv` at different depths, each with -/// an unresolved path — each warning must name a findable file. +/// an unresolved path — each warning must name a findable file. (Since TODO +/// §65.4 a root some file declares resolves, so the set declares no `tb`.) #[test] fn recheck_three_same_named_files_are_each_named_by_their_path() { let dut = "module dut_a;\n for (genvar i = 0; i < 2; i++) begin : g_sw\n logic q;\n end\nendmodule\n"; - let tb = "module tb;\n dut_a dut ();\nendmodule\n"; let probe = "module PROBE (output logic o);\n assign o = tb.dut.g_sw[0].q;\nendmodule\n"; let (p1, p2, p3) = (probe.replace("PROBE", "p1"), probe.replace("PROBE", "p2"), probe.replace("PROBE", "p3")); let files = [ ("dut_a.sv", dut), - ("tb.sv", tb), ("probe.sv", p1.as_str()), ("x/probe.sv", p2.as_str()), ("x/y/z/probe.sv", p3.as_str()), @@ -250,17 +249,22 @@ endmodule } } -/// Rework 2, R2: an escaped net and an escaped label behind an unresolved root. +/// Rework 2, R2: an escaped net and an escaped label behind an unresolved root +/// — no file declares `tbe` — and, since TODO §65.4, renamed behind one that +/// is declared. #[test] fn recheck_escaped_net_and_label_paths_are_named() { let dut = "module dut_e;\n logic \\n$q ;\n if (1) begin : \\g$sw \n logic q;\n end\nendmodule\n"; let tb = "module tbe;\n dut_e dut ();\nendmodule\n"; let probe = "module pe (output logic o, output logic p);\n assign o = tbe.dut.\\g$sw .q;\n assign p = tbe.dut.\\n$q ;\nendmodule\n"; - let files = [("dut_e.sv", dut), ("tbe.sv", tb), ("pe.sv", probe)]; + let files = [("dut_e.sv", dut), ("pe.sv", probe)]; let (_, warnings) = run(&files, "dut_e.sv", "begin : ", "\\g$sw", "g_hw").expect("label"); assert!(warnings.iter().any(|w| w.starts_with("pe.sv:2:")), "{warnings:#?}"); let (_, warnings) = run(&files, "dut_e.sv", "logic ", "\\n$q", "n_q").expect("net"); assert!(warnings.iter().any(|w| w.starts_with("pe.sv:3:")), "{warnings:#?}"); + let files = [("dut_e.sv", dut), ("tbe.sv", tb), ("pe.sv", probe)]; + let (texts, warnings) = run(&files, "dut_e.sv", "logic ", "\\n$q", "n_q").expect("net"); + assert_eq!(texts[2], probe.replace("\\n$q", "n_q"), "{warnings:#?}"); } // --------------------------------------------------------------------------- diff --git a/crates/vlog_refactor/tests/rename_generate_label.rs b/crates/vlog_refactor/tests/rename_generate_label.rs index 3a0dc4c..530cfa6 100644 --- a/crates/vlog_refactor/tests/rename_generate_label.rs +++ b/crates/vlog_refactor/tests/rename_generate_label.rs @@ -258,7 +258,9 @@ endmodule let files = workspace(&[("m.sv", text)]); let why = rename(&files, &path("m.sv"), at(text, "o = ", "genblk1"), "g_x").expect_err("refused"); - assert!(why.contains("not resolved"), "{why}"); + // Since TODO §65.4 `genblk1.` heads a path rooted at a top module no + // file declares — refused all the same, never this file's unnamed block. + assert!(why.contains("not resolved") || why.contains("hierarchical path"), "{why}"); assert!(prepare_rename(&files, &path("m.sv"), at(text, "o = ", "genblk1")).is_err()); } @@ -351,6 +353,7 @@ fn an_unresolved_path_through_the_name_warns_and_a_path_to_another_declaration_d renamed(&files, "sub.sv", "logic ", "state_q", "state_r").expect("renames"); assert_eq!(texts[2], top.replace("u_x.state_q", "u_x.state_r")); assert_eq!((texts[1].as_str(), texts[3].as_str()), (other, probe)); + // `tb` is declared nowhere (TODO §65.4 resolves it when it is). assert_eq!(warnings.len(), 1, "{warnings:?}"); assert!(warnings[0].starts_with("probe.sv:2,3,4: "), "{warnings:?}"); } diff --git a/crates/vlog_refactor/tests/top_rooted_paths.rs b/crates/vlog_refactor/tests/top_rooted_paths.rs new file mode 100644 index 0000000..d27c737 --- /dev/null +++ b/crates/vlog_refactor/tests/top_rooted_paths.rs @@ -0,0 +1,343 @@ +//! TODO §65.4: `find_references` and `rename` through a hierarchical path +//! rooted at a top-level module another file declares (`tb.dut.g_sw[0].q`, +//! the opentitan DV `force` shape; IEEE 1800 §23.6), and `$root.tb.…`. +//! `docs/features/top-rooted-paths/README.md`. + +use std::path::{Path, PathBuf}; + +use vlog_refactor::{find_references, rename, RefactorEdit}; + +const DUT: &str = "module dut_a; + for (genvar i = 0; i < 2; i++) begin : g_sw + logic buf_q; + end +endmodule +"; +const TB: &str = "module tb; + dut_a dut (); +endmodule +"; +const PROBE: &str = "module probe (output logic o); + assign o = tb.dut.g_sw[0].buf_q; + initial force tb.dut.g_sw[1].buf_q = 1'b0; + initial release $root.tb.dut.g_sw[1].buf_q; +endmodule +"; + +fn path(name: &str) -> PathBuf { + PathBuf::from("/rtl").join(name) +} + +fn workspace(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> { + files.iter().map(|(name, text)| (path(name), text.to_string())).collect() +} + +/// The offset of the first `name` after `prefix`. +fn at(text: &str, prefix: &str, name: &str) -> u32 { + let from = text.find(prefix).unwrap_or_else(|| panic!("`{prefix}` is not in the text")); + let from = from + prefix.len(); + (from + text[from..].find(name).expect("the name after the prefix")) as u32 +} + +fn apply(text: &str, edit: &RefactorEdit, file: &Path) -> String { + let mut out = String::new(); + let mut cursor = 0usize; + for e in edit.edits_for(file) { + out.push_str(&text[cursor..e.range.start as usize]); + out.push_str(&e.new_text); + cursor = e.range.end as usize; + } + out.push_str(&text[cursor..]); + out +} + +/// Every file's text after renaming the `name` after `prefix` in `file`, and +/// the warnings. +fn renamed( + files: &[(&str, &str)], + file: &str, + prefix: &str, + name: &str, + new: &str, +) -> (Vec, Vec) { + let text = files.iter().find(|(n, _)| *n == file).map(|(_, t)| *t).expect("the file"); + let edit = rename(&workspace(files), &path(file), at(text, prefix, name), new) + .unwrap_or_else(|why| panic!("rename refused: {why}")); + let texts = files.iter().map(|(n, t)| apply(t, &edit, &path(n))).collect(); + (texts, edit.warnings) +} + +/// `file:line` of every reference to the `name` after `prefix`, sorted. +fn references(files: &[(&str, &str)], file: &str, prefix: &str, name: &str) -> Vec { + let text = files.iter().find(|(n, _)| *n == file).map(|(_, t)| *t).expect("the file"); + let found = find_references(&workspace(files), &path(file), at(text, prefix, name), true) + .unwrap_or_else(|why| panic!("find_references refused: {why}")); + let mut out: Vec = found + .iter() + .map(|(p, span)| { + let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("?"); + let text = files.iter().find(|(n, _)| *n == name).map(|(_, t)| *t).expect("file"); + assert_eq!(&text[span.as_range()], ident_at(text, span.start)); + format!("{name}:{}", text[..span.start as usize].matches('\n').count() + 1) + }) + .collect(); + out.sort(); + out +} + +/// The identifier starting at `start` — what a reference span must slice. +fn ident_at(text: &str, start: u32) -> &str { + let rest = &text[start as usize..]; + let end = rest.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).unwrap_or(rest.len()); + &rest[..end] +} + +fn files() -> Vec<(&'static str, &'static str)> { + vec![("dut_a.sv", DUT), ("tb.sv", TB), ("probe.sv", PROBE)] +} + +#[test] +fn find_references_lists_every_segment_of_a_top_rooted_path() { + let files = files(); + let want = ["dut_a.sv:2", "probe.sv:2", "probe.sv:3", "probe.sv:4"]; + assert_eq!(references(&files, "dut_a.sv", "begin : ", "g_sw"), want); + let want = ["dut_a.sv:3", "probe.sv:2", "probe.sv:3", "probe.sv:4"]; + assert_eq!(references(&files, "dut_a.sv", "logic ", "buf_q"), want); + let want = ["probe.sv:2", "probe.sv:3", "probe.sv:4", "tb.sv:2"]; + assert_eq!(references(&files, "tb.sv", "dut_a ", "dut"), want); + let want = ["probe.sv:2", "probe.sv:3", "probe.sv:4", "tb.sv:1"]; + assert_eq!(references(&files, "tb.sv", "module ", "tb"), want, "the root itself"); +} + +#[test] +fn renaming_a_member_rewrites_the_path_and_warns_about_nothing() { + let files = files(); + for (prefix, old, new) in [("begin : ", "g_sw", "g_hw"), ("logic ", "buf_q", "buf_r")] { + let (texts, warnings) = renamed(&files, "dut_a.sv", prefix, old, new); + assert_eq!(texts[0], DUT.replace(old, new)); + assert_eq!(texts[1], TB); + assert_eq!(texts[2], PROBE.replace(old, new)); + assert!(warnings.is_empty(), "{warnings:?}"); + } +} + +#[test] +fn renaming_the_instance_or_the_top_module_rewrites_its_segment() { + let files = files(); + let (texts, warnings) = renamed(&files, "tb.sv", "dut_a ", "dut", "u_dut"); + assert_eq!(texts[1], TB.replace(" dut ", " u_dut ")); + assert_eq!(texts[2], PROBE.replace("tb.dut.", "tb.u_dut.")); + assert!(warnings.is_empty(), "{warnings:?}"); + let (texts, warnings) = renamed(&files, "tb.sv", "module ", "tb", "top_tb"); + assert_eq!(texts[1], TB.replace("module tb", "module top_tb")); + assert_eq!(texts[2], PROBE.replace("tb.dut.", "top_tb.dut.")); + assert!(warnings.is_empty(), "{warnings:?}"); +} + +/// The rename can be asked from the path itself, at any segment. +#[test] +fn a_rename_requested_on_a_segment_of_the_path_renames_the_declaration() { + let files = files(); + let (texts, warnings) = renamed(&files, "probe.sv", "force tb.dut.", "g_sw", "g_hw"); + assert_eq!(texts[0], DUT.replace("g_sw", "g_hw")); + assert_eq!(texts[2], PROBE.replace("g_sw", "g_hw")); + assert!(warnings.is_empty(), "{warnings:?}"); +} + +/// A local of the head's name wins (IEEE 1800 §23.8's upward search finds it +/// first): the path is that net's, nothing is rewritten, and the segment no +/// declaration answers is named — the §65.1 path warning, as before. +#[test] +fn a_local_that_shadows_the_top_module_is_not_renamed_through() { + let shadow = "module probe2 (output logic o); + logic tb; + assign o = tb.dut.g_sw[0].buf_q; +endmodule +"; + let mut files = files(); + files.push(("probe2.sv", shadow)); + let (texts, warnings) = renamed(&files, "dut_a.sv", "begin : ", "g_sw", "g_hw"); + assert_eq!(texts[2], PROBE.replace("g_sw", "g_hw"), "the unshadowed paths move"); + assert_eq!(texts[3], shadow, "the shadowed path does not"); + let said: Vec<&String> = warnings.iter().filter(|w| w.contains("probe2.sv")).collect(); + assert_eq!(said.len(), 1, "{warnings:?}"); + assert!(said[0].starts_with("probe2.sv:3:"), "{said:?}"); +} + +/// A root no file declares: the path is left and named, with its lines. +#[test] +fn a_root_the_workspace_does_not_declare_is_left_and_warned_about() { + let files = [("dut_a.sv", DUT), ("probe.sv", PROBE)]; + let (texts, warnings) = renamed(&files, "dut_a.sv", "begin : ", "g_sw", "g_hw"); + assert_eq!(texts[1], PROBE, "nothing reaches `dut_a` from an unknown root"); + // Exactly one warning names these sites — the §65.1 path line; the + // unresolved-candidate scan leaves them to it (Handshake H1). + let said: Vec<&String> = warnings.iter().filter(|w| w.contains("probe.sv")).collect(); + assert_eq!(said.len(), 1, "one line for the file: {warnings:?}"); + assert!(said[0].starts_with("probe.sv:2,3,4:") && said[0].contains("`g_sw`"), "{said:?}"); +} + +/// Two `module tb`: `tb.dut` names two instances, so nothing after it is +/// renamed, and it is said. +#[test] +fn an_ambiguous_root_is_left_and_warned_about() { + let dut_b = "module dut_b;\n logic x;\nendmodule\n"; + let tb2 = "module tb;\n dut_b dut ();\nendmodule\n"; + let mut files = files(); + files.push(("dut_b.sv", dut_b)); + files.push(("tb2.sv", tb2)); + let (texts, warnings) = renamed(&files, "dut_a.sv", "begin : ", "g_sw", "g_hw"); + assert_eq!(texts[2], PROBE); + let said: Vec<&String> = warnings.iter().filter(|w| w.contains("probe.sv")).collect(); + assert_eq!(said.len(), 1, "one line for the file: {warnings:?}"); + assert!(said[0].starts_with("probe.sv:2,3,4:"), "{warnings:?}"); +} + +/// With two `module tb`, each `tb.` head could name either, so renaming one +/// of them is refused rather than rewriting heads that may be the other's. +#[test] +fn renaming_one_of_two_same_named_tops_is_refused() { + let tb2 = "module tb;\n dut_a dut ();\nendmodule\n"; + let mut files = files(); + files.push(("tb2.sv", tb2)); + let text = TB; + let why = rename(&workspace(&files), &path("tb.sv"), at(text, "module ", "tb"), "top_tb") + .expect_err("refused"); + assert!(why.contains("tb"), "{why}"); +} + +/// Handshake H1: QA's repro (`probe.sv: assign o = tb.dut.g_sw[0].buf_q;`) +/// with the root undeclared, and with three `module tb` (the opentitan +/// shape): exactly one warning names the probe's line, the §65.1 path line, +/// and the unresolved-candidate scan does not repeat it. +#[test] +fn an_unresolved_top_rooted_path_is_named_by_exactly_one_warning() { + let probe = "module probe (output logic o);\n assign o = tb.dut.g_sw[0].buf_q;\nendmodule\n"; + let tb_b = "module tb;\n dut_b dut ();\nendmodule\n"; + let tb_c = "module tb;\n dut_c dut ();\nendmodule\n"; + let undeclared = vec![("dut_a.sv", DUT), ("probe.sv", probe)]; + let mut three = vec![("dut_a.sv", DUT), ("tb.sv", TB), ("probe.sv", probe)]; + three.extend([("tb_b.sv", tb_b), ("tb_c.sv", tb_c)]); + for files in [undeclared, three] { + for (prefix, old) in [("begin : ", "g_sw"), ("logic ", "buf_q")] { + let (texts, warnings) = renamed(&files, "dut_a.sv", prefix, old, "renamed_x"); + let at_probe = files.iter().position(|(n, _)| *n == "probe.sv").expect("probe"); + assert_eq!(texts[at_probe], probe, "left unchanged"); + let said: Vec<&String> = warnings.iter().filter(|w| w.contains("probe.sv")).collect(); + assert_eq!(said.len(), 1, "{old}: {warnings:?}"); + assert!(said[0].starts_with("probe.sv:2:"), "{old}: {said:?}"); + } + } +} + +// --------------------------------------------------------------------------- +// Rework after QA (2026-10-19): rooting only when the head is provably a top +// module or interface. Each case is QA's repro (`scratchpad/qa654/attack`); +// each asserts the path is left unchanged and named, never silently renamed. +// --------------------------------------------------------------------------- + +/// Rename the `name` after `prefix` in `file`; assert `left` is unchanged and +/// a warning names `left`'s `line`. +fn left_and_named(files: &[(&str, &str)], at_: (&str, &str, &str), left: &str, line: u32) { + let (file, prefix, name) = at_; + let (texts, warnings) = renamed(files, file, prefix, name, "renamed_x"); + let i = files.iter().position(|(n, _)| *n == left).expect("the left file"); + assert_eq!(texts[i], files[i].1, "{name}: `{left}` is not edited"); + let named = format!("{left}:{line}:"); + assert!(warnings.iter().any(|w| w.starts_with(&named)), "{name}: {warnings:?}"); +} + +/// QA F1 (B12): a package `tb` beside the module `tb`. Renaming the package's +/// `dut` used to rewrite `tb.dut.x`; renaming the module's instance used to +/// miss it. Neither touches it now, and both name it. +#[test] +fn qa_f1_a_package_sharing_the_roots_name_lends_the_path_nothing() { + let dut = "module dut_a;\n logic x;\nendmodule\n"; + let pkg = "package tb;\n logic dut;\nendpackage\n"; + let other = "module other;\n initial force tb.dut.x = 0;\nendmodule\n"; + let files = [("dut_a.sv", dut), ("tb.sv", TB), ("tb_pkg.sv", pkg), ("other.sv", other)]; + left_and_named(&files, ("tb_pkg.sv", "logic ", "dut"), "other.sv", 2); + left_and_named(&files, ("tb.sv", "dut_a ", "dut"), "other.sv", 2); + left_and_named(&files, ("dut_a.sv", "logic ", "x"), "other.sv", 2); +} + +/// QA A3/A4: `pk.x` (illegal) with a package `pk`, with and without a module +/// `pk`: renaming the package's `x` leaves it. +#[test] +fn qa_f1_a_package_is_never_a_root() { + let pkg = "package pk;\n logic x;\nendpackage\n"; + let module = "module pk;\n logic x;\nendmodule\n"; + let user = "module user (output logic o);\n assign o = pk.x;\nendmodule\n"; + let alone = [("p.sv", pkg), ("user.sv", user)]; + let (texts, _) = renamed(&alone, "p.sv", "logic ", "x", "y"); + assert_eq!(texts[1], user); + let both = [("p.sv", pkg), ("m.sv", module), ("user.sv", user)]; + left_and_named(&both, ("p.sv", "logic ", "x"), "user.sv", 2); + left_and_named(&both, ("m.sv", "logic ", "x"), "user.sv", 2); +} + +/// QA F2 (A1): `import p::*` supplies `cfg`, a package variable, and a module +/// `cfg` exists too. The imported name is the head; renaming the module's +/// `field` used to rewrite `cfg.field`. +#[test] +fn qa_f2_an_imported_head_is_never_rooted_at_a_same_named_module() { + let pkg = "package p;\n typedef struct packed { logic field; } s_t;\n s_t cfg;\nendpackage\n"; + let module = "module cfg;\n logic field;\nendmodule\n"; + let user = + "module user (output logic o);\n import p::*;\n assign o = cfg.field;\nendmodule\n"; + let files = [("p.sv", pkg), ("cfgm.sv", module), ("user.sv", user)]; + left_and_named(&files, ("cfgm.sv", "logic ", "field"), "user.sv", 3); +} + +/// QA F4: three heads the binder cannot see — a macro-declared member in a +/// class (A11), a macro-declared struct in a module (A12) and a class in a +/// package writing `tb.dut.x` (D2) — each used to be renamed through a +/// same-named module. +#[test] +fn qa_f4_a_head_this_crate_cannot_see_is_never_rooted() { + let cfg = "module cfg;\n logic en;\nendmodule\n"; + let class = "class env;\n `DECLARE_CFG\n task run(); if (cfg.en) $display(\"x\"); endtask\nendclass\n"; + left_and_named(&[("cm.sv", cfg), ("cls.sv", class)], ("cm.sv", "logic ", "en"), "cls.sv", 3); + let st = "module st;\n logic a;\nendmodule\n"; + let user = "module user (output logic o);\n `DECL_STRUCT(st)\n assign o = st.a;\nendmodule\n"; + left_and_named(&[("cm.sv", st), ("user.sv", user)], ("cm.sv", "logic ", "a"), "user.sv", 3); + let dut = "module dut_a;\n logic x;\nendmodule\n"; + let pkg = "package env_pkg;\n class seq;\n task body(); tb.dut.x = 1; endtask\n endclass\nendpackage\n"; + let files = [("dut_a.sv", dut), ("tb.sv", TB), ("pkg.sv", pkg)]; + left_and_named(&files, ("dut_a.sv", "logic ", "x"), "pkg.sv", 3); +} + +/// QA R1 (E1, E2, E6, E3): a macro statement in a `begin` block, a task or a +/// function body, or a macro in the ANSI port list, may declare `st`/`bus`; +/// renaming the same-named module's member leaves the path and names it. +#[test] +fn qa_r1_a_macro_where_a_declaration_could_stand_blocks_rooting() { + let st = "module st;\n logic a;\nendmodule\n"; + for (user, line) in [ + ("module user;\n initial begin\n `DECL_LOCAL(st)\n st.a = 1;\n end\nendmodule\n", 4), + ("module user;\n task automatic t();\n `DECL_LOCAL(st)\n st.a = 1;\n endtask\nendmodule\n", 4), + ("module user;\n function automatic void f();\n `DECL_LOCAL(st)\n begin st.a = 1; end\n endfunction\nendmodule\n", 4), + ] { + left_and_named(&[("st.sv", st), ("user.sv", user)], ("st.sv", "logic ", "a"), "user.sv", line); + } + let bus = "module bus;\n logic data;\nendmodule\n"; + let user = "module user (`MY_PORTS, output logic o);\n assign o = bus.data;\nendmodule\n"; + let files = [("bus.sv", bus), ("user.sv", user)]; + let (texts, _) = renamed(&files, "bus.sv", "logic ", "data", "d2"); + assert_eq!(texts[1], user, "the macro port may declare `bus`"); +} + +/// The held shapes (E7, E8): a macro in a sibling generate block, or used as +/// a data type, declares no head on the path's scope chain — renamed. +#[test] +fn qa_r1_a_macro_off_the_scope_chain_or_as_a_type_still_renames() { + let st = "module st;\n logic a;\nendmodule\n"; + for user in [ + "module user;\n if (1) begin : g1\n `DECL_LOCAL(st)\n end\n if (1) begin : g2\n initial st.a = 1;\n end\nendmodule\n", + "module user;\n `MY_STRUCT_T other;\n initial st.a = 1;\nendmodule\n", + ] { + let files = [("st.sv", st), ("user.sv", user)]; + let (texts, warnings) = renamed(&files, "st.sv", "logic ", "a", "b"); + assert_eq!(texts[1], user.replace("st.a", "st.b"), "{warnings:?}"); + } +} diff --git a/crates/vlog_semantic/src/bind/expr.rs b/crates/vlog_semantic/src/bind/expr.rs index 5cb967e..174ba9d 100644 --- a/crates/vlog_semantic/src/bind/expr.rs +++ b/crates/vlog_semantic/src/bind/expr.rs @@ -74,8 +74,9 @@ impl<'a> Binder<'a> { self.bind_expr(lsb, scope); } // `a.b`, `a.b.c`, `tb.dut.u_core.sig`: every link is bound — - // the head as an ordinary use, each `.name` as a tail against the - // type of what precedes it (`Target::MemberOf`) — because the + // the head as a path root (`Target::PathHead`), each `.name` as a + // tail against the type of what precedes it (`Target::MemberOf`) — + // because the // recursion below meets each `Member` node in turn. `this.b` and // `super.b` go to the enclosing class instead, and a spine that // starts at one of them stops there: `this.a.b` records `a` and @@ -92,7 +93,15 @@ impl<'a> Binder<'a> { self.use_member(scope, name, member_tail(e.span, name), Target::SuperMember) } _ => { - self.bind_expr(base, scope); + // A bare head is a path's root: a miss there names a + // top-level module (`Target::PathHead`), where any other + // bare identifier's miss names nothing. + match &base.kind { + ExprKind::Ident(head) => { + self.use_name(scope, head, base.span, Target::PathHead) + } + _ => self.bind_expr(base, scope), + } if let Some((head, mids)) = spine(base) { // The tail's range is derived from the whole // expression's, so it is verified before use: a diff --git a/crates/vlog_semantic/src/bind/item.rs b/crates/vlog_semantic/src/bind/item.rs index ee026d6..c126647 100644 --- a/crates/vlog_semantic/src/bind/item.rs +++ b/crates/vlog_semantic/src/bind/item.rs @@ -183,9 +183,11 @@ impl<'a> Binder<'a> { // `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. + // A macro invocation standing as an item may declare names this + // crate never sees (`Binder::mark_macro_declarations`). + ItemKind::MacroItem(_) => self.mark_macro_declarations(scope), ItemKind::Export(ExportDecl::Dpi(_)) | ItemKind::Directive(_) - | ItemKind::MacroItem(_) | ItemKind::Timeunit(_) | ItemKind::Error(_) // A null item (`;`) declares nothing and references nothing. @@ -212,6 +214,9 @@ impl<'a> Binder<'a> { } } self.bind_param_ports(m.param_ports.iter().flatten(), inner); + if port_list_may_hide_declarations(&m.ports) { + self.mark_macro_declarations(inner); + } match &m.ports { // An error element — a port a tolerant parse could not read — // declares nothing, exactly as an `ItemKind::Error` does. @@ -568,3 +573,18 @@ fn bind_target_path(b: &BindDirective) -> Option { } (!out.is_empty()).then_some(out) } + +/// Whether a header's port list holds an entry this crate cannot read as a +/// port: a macro invocation standing as one (`` module m (`MY_PORTS, …) ``, +/// which the parser keeps as a port spelled `` `MY_PORTS ``) or an element a +/// tolerant parse gave up on. Either may declare names this crate never sees. +fn port_list_may_hide_declarations(ports: &PortList) -> bool { + let macro_name = |name: &str| name.starts_with('`'); + match ports { + PortList::Ansi(ports) => ports.iter().any(|p| p.ok().is_none_or(|p| macro_name(&p.name))), + PortList::NonAnsi(ports) => { + ports.iter().any(|p| p.ok().is_none_or(|p| macro_name(&p.name))) + } + PortList::None | PortList::Empty => false, + } +} diff --git a/crates/vlog_semantic/src/bind/mod.rs b/crates/vlog_semantic/src/bind/mod.rs index bfd9c5e..4d1e959 100644 --- a/crates/vlog_semantic/src/bind/mod.rs +++ b/crates/vlog_semantic/src/bind/mod.rs @@ -113,6 +113,13 @@ pub(crate) enum Target { /// of `mids` walks one link further — the [`Target::MemberOf`] walk, with /// its start moved from the writing scope to the target's. BindMember { target: String, head: String, mids: Vec }, + /// The **head** of a dotted path — the `tb` of `tb.dut.sig`: looked up + /// exactly like [`Target::Lexical`], but a miss is a top-level module's + /// name (IEEE 1800 §23.6: a top-level module name is the root of a + /// hierarchical name), so it is handed to the workspace's unit table as + /// [`Target::Module`] hands an instantiation's type. A local of the name + /// still wins. `docs/features/top-rooted-paths/README.md`. + PathHead, /// The `x` of `this.x`: the enclosing class's scope only. ThisMember, /// The `x` of `super.x`: always the base class's business. @@ -166,6 +173,7 @@ impl<'a> Binder<'a> { imports: Vec::new(), extends: None, names: HashMap::new(), + macro_items: false, }; Binder { src, @@ -183,6 +191,17 @@ impl<'a> Binder<'a> { ScopeId(0) } + /// Record that an unexpanded macro invocation stands in `scope` where a + /// declaration could stand — an item, a statement or block item, a port — + /// so it may declare names this crate never sees. A path head missing + /// from `scope`, or from a scope inside it, is then not proven a top + /// module (`resolve/root.rs`, top-rooted-paths QA F4 and R1). + pub(super) fn mark_macro_declarations(&mut self, scope: ScopeId) { + if let Some(s) = self.scopes.get_mut(scope.0 as usize) { + s.macro_items = true; + } + } + fn new_scope(&mut self, kind: ScopeKind, parent: ScopeId, span: TextRange) -> ScopeId { let id = ScopeId(self.scopes.len() as u32); self.scopes.push(Scope { @@ -195,6 +214,7 @@ impl<'a> Binder<'a> { imports: Vec::new(), extends: None, names: HashMap::new(), + macro_items: false, }); self.scopes[parent.0 as usize].children.push(id); id @@ -322,14 +342,16 @@ impl<'a> Binder<'a> { // with a head of its own already carries the right target and is left // alone. let target = match (&self.with_head, &self.bind_target, &target) { - (Some((head, mids)), _, Target::Lexical) => { + (Some((head, mids)), _, Target::Lexical | Target::PathHead) => { Target::InlineConstraint { head: head.clone(), mids: mids.clone() } } // Same funnel, same rule, for a `bind`'s connection expressions: // a bare name there is the target scope's before it is anything // else. A name written with a head of its own already carries the // right target and is left alone. - (None, Some(scope), Target::Lexical) => Target::BindScope { target: scope.clone() }, + (None, Some(scope), Target::Lexical | Target::PathHead) => { + Target::BindScope { target: scope.clone() } + } // And the same rule for a hierarchical path in one: its head is a // name in the target's scope, so the whole spine is rooted there // rather than in the scope the directive is written in. diff --git a/crates/vlog_semantic/src/bind/stmt.rs b/crates/vlog_semantic/src/bind/stmt.rs index 8635c2d..97aadd0 100644 --- a/crates/vlog_semantic/src/bind/stmt.rs +++ b/crates/vlog_semantic/src/bind/stmt.rs @@ -277,13 +277,15 @@ impl<'a> Binder<'a> { | StmtKind::Continue | StmtKind::WaitFork | StmtKind::Directive(_) - | StmtKind::MacroStmt(_) | StmtKind::Null // Verbatim source: opaque to name resolution, exactly as the // item-level `ItemKind::Verbatim` is. | StmtKind::Verbatim(_) | StmtKind::Error(_) => {} StmtKind::Assertion(a) => self.bind_assertion(a, scope), + // A macro standing as a statement may be a block-item declaration + // (`Binder::mark_macro_declarations`, top-rooted-paths QA R1). + StmtKind::MacroStmt(_) => self.mark_macro_declarations(scope), } } diff --git a/crates/vlog_semantic/src/facts.rs b/crates/vlog_semantic/src/facts.rs index 58b71ea..a979baf 100644 --- a/crates/vlog_semantic/src/facts.rs +++ b/crates/vlog_semantic/src/facts.rs @@ -164,7 +164,15 @@ use crate::workspace::{ /// nothing. A 0.59.0 store would answer find-references and the rename of a /// block label as though no other file named it. See /// `docs/features/generate-label-rename/README.md`. -pub const FACTS_FORMAT: u32 = 21; +/// 21 → 22 (2026-10-19, top-rooted-paths): no new field, but new records — a +/// dotted path whose head this file does not declare (`tb.dut.sig`, rooted at +/// a top module another file declares) records its head as a candidate for +/// the unit table and every segment after it as an external reference on the +/// hierarchical surface, where it recorded nothing. A 0.61.0 store would +/// answer find-references and the rename of `dut`'s members as though no DV +/// file's `force tb.dut.…` named them. See +/// `docs/features/top-rooted-paths/README.md`. +pub const FACTS_FORMAT: u32 = 22; impl FileFacts { /// These facts as one line's worth of fields, tab-separated. diff --git a/crates/vlog_semantic/src/model.rs b/crates/vlog_semantic/src/model.rs index 3df2635..2009b14 100644 --- a/crates/vlog_semantic/src/model.rs +++ b/crates/vlog_semantic/src/model.rs @@ -239,6 +239,10 @@ pub enum Resolution { /// which is a hierarchical path and reads the module's hierarchical /// surface. Carried here rather than worked out again at lookup time /// because only the file that wrote the path knows what its head was. + /// A path rooted at a **top module** another file declares (`tb` of + /// `tb.dut.sig`, TODO §65.4) reads the hierarchical surface too — its + /// head as well, whose bare path the index then accepts only as a module + /// or an interface. ExternalCandidate { paths: Vec, surface: Surface }, /// A use inside a class that nothing lexical binds, where the class's /// `extends` could: `base` is the base-class path as written @@ -420,6 +424,9 @@ pub struct Scope { /// rules). Kept separate from `symbols` so a redeclaration is still /// visible in the outline. pub(crate) names: HashMap, + /// Whether an unexpanded macro invocation stands as an item here — text + /// that may declare names this crate cannot see. + pub(crate) macro_items: bool, } impl Scope { diff --git a/crates/vlog_semantic/src/resolve.rs b/crates/vlog_semantic/src/resolve.rs index fe9fa90..bf1f435 100644 --- a/crates/vlog_semantic/src/resolve.rs +++ b/crates/vlog_semantic/src/resolve.rs @@ -7,6 +7,8 @@ use crate::bind::{Pending, Target}; use crate::model::{MemberSite, Resolution, Scope, ScopeId, Surface, Symbol, SymbolId, SymbolKind}; +mod root; + /// Resolve one pending use against the finished scope tree. /// /// `None` means **record no reference at all**: the targets that can arrive @@ -21,6 +23,7 @@ pub(crate) fn resolve(scopes: &[Scope], symbols: &[Symbol], p: &Pending) -> Opti // which symbol that is, so there is nothing to look up. Target::Declaration(id) => Resolution::Resolved(*id), Target::Lexical => lexical(scopes, p.scope, &p.name, false), + Target::PathHead => root::path_head(scopes, p.scope, &p.name), Target::Type => lexical(scopes, p.scope, &p.name, true), Target::Package => named_at_file_scope(scopes, symbols, &p.name, is_package), // An interface is instantiated, connected and hierarchically named @@ -222,7 +225,11 @@ fn member_of( mids: &[String], name: &str, ) -> Option { - let site = member_site(scopes, symbols, from, head, mids)?; + if head == root::ROOT && mids.is_empty() { + // `$root.tb`: the tail is the top module itself. + return Some(root::top_module(scopes, symbols, name)); + } + let site = spine_site(scopes, symbols, from, head, mids, HeadMiss::TopModule)?; member_at(scopes, symbols, site, name, mids.is_empty()) } @@ -288,6 +295,17 @@ fn member_at( /// keeps the two from drifting. `super` names the first hop of the `extends` /// chain — the base's scope when this file declares it, the base's *name* /// when it does not, which is the unit the overlay's own chase starts at. +/// +/// **One difference from the resolution walk**, and only one: a head this +/// file does not declare is *not* rooted at a top-level module here +/// ([`HeadMiss::Nothing`]), where [`member_of`] roots it at one +/// ([`HeadMiss::TopModule`], TODO §65.4). A popup after `no_such_handle.` has +/// always answered nothing so the ordinary completion tiers run, and a +/// workspace unit list after every unknown head would replace them with an +/// empty one; offering a top module's members after `tb.` is a completion +/// change the language server's member list must make knowingly +/// (`docs/features/top-rooted-paths/README.md`, Handshakes). `$root.tb.` is +/// rooted in both: it says what it is. pub(crate) fn member_site( scopes: &[Scope], symbols: &[Symbol], @@ -295,7 +313,31 @@ pub(crate) fn member_site( head: &str, mids: &[String], ) -> Option { - let mut here = head_site(scopes, symbols, from, head)?; + spine_site(scopes, symbols, from, head, mids, HeadMiss::Nothing) +} + +/// What a spine's head that this file does not declare roots the spine at. +#[derive(Clone, Copy)] +enum HeadMiss { + /// Nothing: the spine stops (the completion walk). + Nothing, + /// The top-level module of that name (the resolution walk). + TopModule, +} + +/// [`member_site`]'s walk, with what a head miss means said by the caller. +fn spine_site( + scopes: &[Scope], + symbols: &[Symbol], + from: ScopeId, + head: &str, + mids: &[String], + miss: HeadMiss, +) -> Option { + let (mut here, mids) = match (head, mids.split_first()) { + (root::ROOT, Some((top, rest))) => (root::top_site(scopes, symbols, top), rest), + _ => (head_site(scopes, symbols, from, head, miss)?, mids), + }; for mid in mids { here = descend(scopes, symbols, here, mid)?; } @@ -338,6 +380,7 @@ fn head_site( symbols: &[Symbol], from: ScopeId, head: &str, + miss: HeadMiss, ) -> Option { match head { // Neither is a name this crate binds, so neither goes through @@ -354,12 +397,22 @@ fn head_site( }), } } - _ => { - let Resolution::Resolved(id) = lexical(scopes, from, head, false) else { - return None; - }; - link_type(scopes, symbols, id) - } + // `$root` alone, a system name, a macro: no unit to root a path at. + _ if head.starts_with(['$', '`']) => None, + _ => match lexical(scopes, from, head, false) { + Resolution::Resolved(id) => link_type(scopes, symbols, id), + // A plain miss where nothing unseen could declare the name is a + // top-level module's name — the very rule `Target::PathHead` + // applies to the head's own reference (`root::roots_at_top`), so + // the head and the segments after it agree. Anything else is + // doubt, and doubt roots nothing. + Resolution::NotFound + if matches!(miss, HeadMiss::TopModule) && root::roots_at_top(scopes, from) => + { + Some(root::unit_root(head)) + } + _ => None, + }, } } @@ -684,7 +737,9 @@ fn last_segment(path: &str) -> &str { /// in a *value* position: a name a `` `define`` would have produced, a typo, a /// signal declared somewhere this crate does not model. Nothing about it says /// "file-scope declaration", so it is not swept through the unit table, where a -/// mere name collision would make `rename` rewrite an unrelated file. +/// mere name collision would make `rename` rewrite an unrelated file. The one +/// value position that does say it is the head of a dotted path, which is +/// [`Target::PathHead`]'s and `root::path_head`'s, not this function's. fn lexical(scopes: &[Scope], from: ScopeId, name: &str, promote: bool) -> Resolution { let mut external = Vec::new(); let mut current = Some(from); diff --git a/crates/vlog_semantic/src/resolve/root.rs b/crates/vlog_semantic/src/resolve/root.rs new file mode 100644 index 0000000..224c361 --- /dev/null +++ b/crates/vlog_semantic/src/resolve/root.rs @@ -0,0 +1,85 @@ +//! A hierarchical path rooted at a **top-level module** (IEEE 1800 §23.6: a +//! top-level module name is the root of a hierarchical name) — `tb.dut.sig` +//! written in a file that does not declare `tb`, and `$root.tb.dut.sig`. +//! +//! The head's own reference ([`path_head`]) and the walk the segments after it +//! take ([`unit_root`], via `head_site`) fall back to the same unit, so `tb` +//! and `tb.dut` cannot name different modules. +//! +//! **A path is rooted only when this file shows the head can be nothing but a +//! top-level module** ([`roots_at_top`]); in doubt it is not, and the path +//! stays unresolved and warned about, as before §65.4. A local of the name +//! wins (the LRM's upward search finds it first); so does a name an import +//! could supply, whether or not the workspace can say it does; and a head +//! written inside a class, or where an unexpanded macro stands as an item, +//! may be a name this crate never sees. `docs/features/top-rooted-paths/README.md`. + +use crate::model::{MemberSite, Resolution, Scope, ScopeId, ScopeKind, Surface, Symbol}; + +use super::{file_symbol, is_instantiable, lexical, owning_scope}; + +/// The system name that spells the root of the design hierarchy. +pub(super) const ROOT: &str = "$root"; + +/// The head of a dotted path: the lexical answer, and on a plain miss that +/// [`roots_at_top`] allows, the top-level module of that name. An import +/// candidate stays exactly what `lexical` said (the imported name is the +/// head, by the LRM), and so does every other answer. +pub(super) fn path_head(scopes: &[Scope], from: ScopeId, name: &str) -> Resolution { + match lexical(scopes, from, name, false) { + Resolution::NotFound if roots_at_top(scopes, from) => top_candidate(name), + found => found, + } +} + +/// Whether a head missing from the lexical chain of `from` may be taken for a +/// top-level module: no scope on the chain, up to the file, is a class (a +/// class member, inherited or macro-declared, is never a path into the design +/// hierarchy lucisv could prove) or holds an unexpanded macro invocation as +/// an item (it may declare the very name). +pub(super) fn roots_at_top(scopes: &[Scope], from: ScopeId) -> bool { + let mut current = Some(from); + while let Some(id) = current { + let Some(scope) = scopes.get(id.0 as usize) else { return false }; + if scope.kind == ScopeKind::Class || scope.macro_items { + return false; + } + current = scope.parent; + } + true +} + +/// Where a path whose head this file does not declare is rooted: the +/// workspace unit of that name, read on its hierarchical surface — the +/// surface an instance path reads, because the segments after a root are the +/// same kind of names (`tb.dut` is an instance of `tb`). +pub(super) fn unit_root(head: &str) -> MemberSite { + MemberSite::Unit { path: head.to_string(), surface: Surface::Hierarchical } +} + +/// The `tb` of `$root.tb.…` as a site: the module this file declares at file +/// scope, else the workspace unit. `$root` skips the lexical walk entirely — +/// that is what it is for. +pub(super) fn top_site(scopes: &[Scope], symbols: &[Symbol], top: &str) -> MemberSite { + match owning_scope(scopes, symbols, top, is_instantiable) { + Some(scope) => MemberSite::Scope(scope), + None => unit_root(top), + } +} + +/// The `tb` of `$root.tb` as a reference: the file-scope module this file +/// declares, else a candidate for the workspace's unit table. +pub(super) fn top_module(scopes: &[Scope], symbols: &[Symbol], top: &str) -> Resolution { + match file_symbol(scopes, symbols, top, is_instantiable) { + Some(id) => Resolution::Resolved(id), + None => top_candidate(top), + } +} + +/// The bare name on the hierarchical surface — which is also what tells the +/// workspace layer to accept only a module or an interface for it +/// (`external::follow_one`): a package or class sharing a top module's name +/// is not a root a `.` can follow. +fn top_candidate(name: &str) -> Resolution { + Resolution::ExternalCandidate { paths: vec![name.to_string()], surface: Surface::Hierarchical } +} diff --git a/crates/vlog_semantic/src/workspace/external.rs b/crates/vlog_semantic/src/workspace/external.rs index a4d23d3..942c2e1 100644 --- a/crates/vlog_semantic/src/workspace/external.rs +++ b/crates/vlog_semantic/src/workspace/external.rs @@ -246,15 +246,46 @@ pub(super) fn base_chain<'i>(index: &'i WorkspaceIndex, unit: &str) -> Vec<&'i s /// /// The same fold [`follow_one`] runs before its own lookup — shared, so a /// list and a lookup of the same path cannot land in different units. +/// +/// On the **hierarchical** surface every unit the fold stands in is checked +/// ([`design_unit`]): a path through the design hierarchy starts at a module +/// or an interface and never passes through a package, so a package sharing a +/// module's name cannot lend the path its members (top-rooted-paths QA F1). pub(super) fn fold_path(index: &WorkspaceIndex, path: &str, surface: Surface) -> Option { let mut segments = path.split("::"); let mut unit = segments.next()?.to_string(); + let hierarchical = surface == Surface::Hierarchical; + if hierarchical && !design_unit(index, &unit, true) { + return None; + } for segment in segments { unit = index.member_unit_in(&unit, segment, surface)?; + if hierarchical && !design_unit(index, &unit, false) { + return None; + } } Some(unit) } +/// Whether a hierarchical path may stand in `unit`. Its **first** unit must be +/// declared, and only as modules or interfaces — the type of an instance, the +/// target of a `bind`, or the top module a path is rooted at. A **later** unit +/// (an instance's type, a block's synthesized key, a struct or class type a +/// variable is declared with) may be any kind, but not a module and something +/// else at once: the member table is keyed by name, so such a name's members +/// are the two declarations' merged — which is how a package sharing a +/// module's name would reach a later hop. A later unit that is *only* a +/// package would need a declaration typed with a package's name, which is +/// not code; no separate rule is kept for it (QA M7). +fn design_unit(index: &WorkspaceIndex, unit: &str, first: bool) -> bool { + let defs = index.units(unit); + let modules = defs.iter().filter(|def| def.kind.is_instantiable()).count(); + if first { + return !defs.is_empty() && modules == defs.len(); + } + modules == 0 || modules == defs.len() +} + /// The type a file-scope `typedef` names, when the workspace declares the name /// exactly once and as a typedef. Two declarations of the name are two /// answers, and this layer picks between candidates nowhere else either. @@ -327,7 +358,7 @@ fn follow_one<'i>( } if segments.len() < 2 { return if path == name { - index.units(name) + root_units(index.units(name), surface) } else { member_chain(index, path, name, surface) }; @@ -342,6 +373,20 @@ fn follow_one<'i>( member_chain(index, &unit, name, surface) } +/// The units a bare name answers with. On the connection surface — an +/// instantiation's type, an imported package, a type name — every unit of the +/// name, as always. On the **hierarchical** surface the name is the root of a +/// path (`tb` of `tb.dut.sig`, TODO §65.4), which only a module or an +/// interface can be: units of any other kind answer nothing, and so does a +/// name some file declares as a module and another as something else, rather +/// than an answer with the stranger left in or quietly dropped. +fn root_units(units: &[Def], surface: Surface) -> &[Def] { + match surface { + Surface::Hierarchical if !units.iter().all(|def| def.kind.is_instantiable()) => &[], + _ => units, + } +} + impl ExternalResolutions { /// The answer for one reference, or `None` if it was not an external /// candidate. diff --git a/crates/vlog_semantic/src/workspace/mod.rs b/crates/vlog_semantic/src/workspace/mod.rs index c4134e5..db6e7ec 100644 --- a/crates/vlog_semantic/src/workspace/mod.rs +++ b/crates/vlog_semantic/src/workspace/mod.rs @@ -27,6 +27,7 @@ mod external; mod hierarchy; mod index; +mod path_units; mod record; mod reexport; mod update; diff --git a/crates/vlog_semantic/src/workspace/path_units.rs b/crates/vlog_semantic/src/workspace/path_units.rs new file mode 100644 index 0000000..8bed458 --- /dev/null +++ b/crates/vlog_semantic/src/workspace/path_units.rs @@ -0,0 +1,72 @@ +//! The design units a hierarchical path to a declaration walks through — +//! what a caller handing the refactoring engine a *subset* of the workspace +//! must include for that path to resolve inside the subset as it does in the +//! whole (top-rooted-paths QA F3). +//! +//! `tb.dut.u_core.sig` in a DV file names `sig` through `tb` (the top module +//! it is rooted at), `dut_a` (the type of `tb.dut`) and `core` (the type of +//! `u_core`). The index resolved it, so the use is in `sig`'s postings; but a +//! rename handed only `sig`'s declaring file and that DV file cannot resolve +//! the root, and would leave the path behind. The answer is read off the +//! records the index already holds: no file is read. + +use std::collections::{BTreeSet, HashMap, HashSet}; + +use crate::model::Surface; + +use super::record::ReferenceFact; +use super::{Def, FileId, WorkspaceIndex}; + +impl WorkspaceIndex { + /// Every unit an indexed use of `def` written as a hierarchical path + /// passes through before its last segment: the path's first unit (an + /// instance's type, a `bind` target, a top module) and the unit of each + /// hop after it. Empty when no use of `def` is such a path. + pub fn path_units_to(&self, def: &Def) -> BTreeSet { + let mut by_file: HashMap> = HashMap::new(); + for site in self.references_to(def) { + let span = (site.name_span.start, site.name_span.end); + by_file.entry(site.file).or_default().insert(span); + } + let mut out = BTreeSet::new(); + for (file, spans) in by_file { + let Some(facts) = self.facts.get(file.0 as usize) else { continue }; + for fact in &facts.references { + let ReferenceFact::External { + paths, + surface: Surface::Hierarchical, + occurrence, + .. + } = fact + else { + continue; + }; + if spans.contains(&(occurrence.start, occurrence.end)) { + for path in paths { + self.collect_hops(path, &mut out); + } + } + } + } + out + } + + /// The units `path`'s segments before its last stand in, folded as + /// `external::fold_path` folds them, as far as the fold goes. + fn collect_hops(&self, path: &str, out: &mut BTreeSet) { + let mut segments: Vec<&str> = path.split("::").collect(); + segments.pop(); + let Some((first, hops)) = segments.split_first() else { return }; + let mut unit = first.to_string(); + out.insert(unit.clone()); + for hop in hops { + match self.member_unit_in(&unit, hop, Surface::Hierarchical) { + Some(next) => { + unit = next; + out.insert(unit.clone()); + } + None => return, + } + } + } +} diff --git a/crates/vlog_semantic/tests/generate_blocks.rs b/crates/vlog_semantic/tests/generate_blocks.rs index 6ba0011..554fc24 100644 --- a/crates/vlog_semantic/tests/generate_blocks.rs +++ b/crates/vlog_semantic/tests/generate_blocks.rs @@ -229,8 +229,20 @@ fn a_block_and_its_members_are_hierarchical_only_under_the_dotted_key() { fn an_unnamed_block_declares_nothing_a_path_can_name() { let src = "module u (output logic o);\n if (1) begin\n logic w;\n end\n assign o = genblk1.w;\nendmodule\n"; let s = sem(src); - assert_eq!(resolution(&s, at(src, "genblk1", 0, 0)), Resolution::NotFound); - assert!(s.reference_at(at(src, "genblk1.w", 0, 8)).is_none()); + // Nothing here declares `genblk1`, so — as the head of a dotted path — it + // can only be a top-level module some other file declares (TODO §65.4), + // and `w` a member of that module: candidates for the workspace, which + // holds no such module. Never this file's unnamed block. + let top = Resolution::ExternalCandidate { + paths: vec!["genblk1".to_string()], + surface: Surface::Hierarchical, + }; + assert_eq!(resolution(&s, at(src, "genblk1", 0, 0)), top); + let member = Resolution::ExternalCandidate { + paths: vec!["genblk1::w".to_string()], + surface: Surface::Hierarchical, + }; + assert_eq!(resolution(&s, at(src, "genblk1.w", 0, 8)), member); assert!(s.symbols_named("genblk1").next().is_none(), "no symbol is invented for it"); } diff --git a/crates/vlog_semantic/tests/member_access.rs b/crates/vlog_semantic/tests/member_access.rs index 2cabd60..443bcd5 100644 --- a/crates/vlog_semantic/tests/member_access.rs +++ b/crates/vlog_semantic/tests/member_access.rs @@ -196,11 +196,21 @@ endmodule let s = sem(src); for (spelling, why) in [ ("x.bit_field", "a built-in type names no declaration"), - ("stranger.thing", "the head is not declared here"), ("h.absent", "the class is known whole and has no such member"), ] { assert!(s.reference_at(tail(src, spelling, 0)).is_none(), "{spelling}: {why}"); } + // `stranger.thing` was on the list above until TODO §65.4: a head nothing + // here declares is the root of a hierarchical name — a top-level module + // another file declares (IEEE 1800 §23.6) — so its tail is a candidate + // for the workspace (`docs/features/top-rooted-paths/README.md`). + assert_eq!( + resolution_at(&s, tail(src, "stranger.thing", 0)), + Resolution::ExternalCandidate { + paths: vec!["stranger::thing".to_string()], + surface: vlog_semantic::Surface::Hierarchical, + } + ); // The one that does resolve, so the test is not vacuous. assert_eq!( resolution_at(&s, tail(src, "h.known", 0)), diff --git a/crates/vlog_semantic/tests/top_rooted_paths.rs b/crates/vlog_semantic/tests/top_rooted_paths.rs new file mode 100644 index 0000000..a34e6a0 --- /dev/null +++ b/crates/vlog_semantic/tests/top_rooted_paths.rs @@ -0,0 +1,338 @@ +//! Hierarchical paths rooted at a top-level module (TODO §65.4, IEEE 1800 +//! §23.6): `tb.dut.g_sw[0].buf_q` written in a file that does not declare +//! `tb`, and `$root.tb.…`. The head is a candidate for the workspace's unit +//! table, every segment after it a candidate on the hierarchical surface of +//! the unit before it — and a local of the head's name still wins. +//! `docs/features/top-rooted-paths/README.md`. + +use std::path::PathBuf; + +use vlog_parser::parse_source_tolerant; +use vlog_semantic::{ + analyze, resolve_external, ExternalTarget, MemberSite, Resolution, Semantics, Surface, + WorkspaceIndex, +}; + +fn sem(src: &str) -> Semantics { + let (file, _) = parse_source_tolerant(src); + analyze(&file, src) +} + +/// Offset of the `n`th (0-based) occurrence of `needle`, plus `skip` bytes. +fn at(src: &str, needle: &str, n: usize, skip: usize) -> u32 { + (src.match_indices(needle).nth(n).expect("occurrence must exist").0 + skip) as u32 +} + +fn resolution(s: &Semantics, offset: u32) -> Resolution { + s.reference_at(offset).unwrap_or_else(|| panic!("no reference at {offset}")).resolution.clone() +} + +fn candidate(paths: &[&str]) -> Resolution { + Resolution::ExternalCandidate { + paths: paths.iter().map(|p| p.to_string()).collect(), + surface: Surface::Hierarchical, + } +} + +const DUT: &str = "module dut_a; + for (genvar i = 0; i < 2; i++) begin : g_sw + logic buf_q; + end +endmodule +"; +const TB: &str = "module tb; + dut_a dut (); +endmodule +"; +const PROBE: &str = "module probe (output logic o); + assign o = tb.dut.g_sw[0].buf_q; +endmodule +"; + +fn index(extra: &[(&str, &str)]) -> WorkspaceIndex { + let mut files = vec![("dut_a.sv", DUT), ("tb.sv", TB), ("probe.sv", PROBE)]; + files.extend_from_slice(extra); + WorkspaceIndex::build(files.into_iter().map(|(n, t)| (PathBuf::from("/rtl").join(n), t))) +} + +/// What the workspace answers for the reference at `offset`: the kind and +/// name of the one declaration, or a description of a non-answer. +fn external(s: &Semantics, ws: &WorkspaceIndex, offset: u32) -> String { + let id = s.reference_id_at(offset).expect("a reference there"); + match resolve_external(s, ws).get(id) { + Some(ExternalTarget::Resolved(def)) => format!("{:?}", def.kind), + Some(ExternalTarget::Ambiguous(defs)) => format!("ambiguous {}", defs.len()), + Some(ExternalTarget::StillUnresolved) => "unresolved".to_string(), + None => "not a candidate".to_string(), + } +} + +#[test] +fn the_head_and_every_segment_are_candidates_rooted_at_the_head() { + let s = sem(PROBE); + assert_eq!(resolution(&s, at(PROBE, "tb.", 0, 0)), candidate(&["tb"])); + assert_eq!(resolution(&s, at(PROBE, "dut.", 0, 0)), candidate(&["tb::dut"])); + assert_eq!(resolution(&s, at(PROBE, "g_sw", 0, 0)), candidate(&["tb::dut::g_sw"])); + assert_eq!(resolution(&s, at(PROBE, "buf_q", 0, 0)), candidate(&["tb::dut::g_sw::buf_q"])); +} + +#[test] +fn the_workspace_walks_the_path_from_the_top_module() { + let (ws, s) = (index(&[]), sem(PROBE)); + assert_eq!(external(&s, &ws, at(PROBE, "tb.", 0, 0)), "Module"); + assert_eq!(external(&s, &ws, at(PROBE, "dut.", 0, 0)), "Instance"); + assert_eq!(external(&s, &ws, at(PROBE, "g_sw", 0, 0)), "Block"); + assert_eq!(external(&s, &ws, at(PROBE, "buf_q", 0, 0)), "Var"); +} + +#[test] +fn a_root_the_workspace_does_not_declare_stays_unresolved() { + let ws = WorkspaceIndex::build( + [("dut_a.sv", DUT), ("probe.sv", PROBE)] + .into_iter() + .map(|(n, t)| (PathBuf::from("/rtl").join(n), t)), + ); + let s = sem(PROBE); + assert_eq!(external(&s, &ws, at(PROBE, "tb.", 0, 0)), "unresolved"); + assert_eq!(external(&s, &ws, at(PROBE, "g_sw", 0, 0)), "unresolved"); + assert_eq!(external(&s, &ws, at(PROBE, "buf_q", 0, 0)), "unresolved"); +} + +/// Seventy opentitan testbenches are each `module tb`: `tb.dut` then names +/// as many instances, and nothing after it can be told apart. +#[test] +fn two_top_modules_of_one_name_leave_the_path_unresolved() { + let other_tb = "module tb;\n dut_b dut ();\nendmodule\n"; + let ws = index(&[("tb2.sv", other_tb)]); + let s = sem(PROBE); + assert_eq!(external(&s, &ws, at(PROBE, "tb.", 0, 0)), "ambiguous 2"); + assert_eq!(external(&s, &ws, at(PROBE, "dut.", 0, 0)), "ambiguous 2"); + assert_eq!(external(&s, &ws, at(PROBE, "g_sw", 0, 0)), "unresolved"); +} + +/// A package or class is not a root a `.` can follow, and a name declared as +/// a module in one file and a package in another is no root either. +#[test] +fn only_a_module_or_an_interface_is_a_root() { + let pkg = "package tb;\n logic dut;\nendpackage\n"; + let ws = WorkspaceIndex::build( + [("dut_a.sv", DUT), ("tb_pkg.sv", pkg), ("probe.sv", PROBE)] + .into_iter() + .map(|(n, t)| (PathBuf::from("/rtl").join(n), t)), + ); + let s = sem(PROBE); + assert_eq!(external(&s, &ws, at(PROBE, "tb.", 0, 0)), "unresolved"); + let ws = index(&[("tb_pkg.sv", pkg)]); + assert_eq!(external(&s, &ws, at(PROBE, "tb.", 0, 0)), "unresolved", "module and package"); + let iface = "interface tb;\n dut_a dut ();\nendinterface\n"; + let ws = WorkspaceIndex::build( + [("dut_a.sv", DUT), ("tb_if.sv", iface), ("probe.sv", PROBE)] + .into_iter() + .map(|(n, t)| (PathBuf::from("/rtl").join(n), t)), + ); + assert_eq!(external(&s, &ws, at(PROBE, "tb.", 0, 0)), "Interface"); + assert_eq!(external(&s, &ws, at(PROBE, "buf_q", 0, 0)), "Var"); +} + +/// The LRM's upward name resolution finds a local first: a `logic tb` makes +/// `tb.dut` a select of a net this crate models no members of, and an +/// instance named `tb` roots the path in *its* module. +#[test] +fn a_local_of_the_heads_name_wins() { + let net = "module probe (output logic o);\n logic tb;\n assign o = tb.dut.g_sw[0].buf_q;\nendmodule\n"; + let s = sem(net); + let local = s.symbol_at(at(net, "logic tb", 0, 6)).expect("the net"); + assert_eq!(resolution(&s, at(net, "tb.", 0, 0)), Resolution::Resolved(local)); + assert!(s.reference_at(at(net, "dut.", 0, 0)).is_none(), "a net has no members"); + let inst = + "module probe (output logic o);\n other tb ();\n assign o = tb.dut.x;\nendmodule\n"; + let s = sem(inst); + let local = s.symbol_at(at(inst, "other tb", 0, 6)).expect("the instance"); + assert_eq!(resolution(&s, at(inst, "tb.", 0, 0)), Resolution::Resolved(local)); + assert_eq!(resolution(&s, at(inst, "dut.", 0, 0)), candidate(&["other::dut"])); +} + +/// A module this file declares is found lexically, as it always was. +#[test] +fn a_top_module_declared_in_the_same_file_resolves_in_the_file() { + let src = "module tb;\n logic sig;\nendmodule\nmodule probe (output logic o);\n assign o = tb.sig;\nendmodule\n"; + let s = sem(src); + let tb = s.symbol_at(at(src, "module tb", 0, 7)).expect("tb"); + let sig = s.symbol_at(at(src, "logic sig", 0, 6)).expect("sig"); + assert_eq!(resolution(&s, at(src, "tb.sig", 0, 0)), Resolution::Resolved(tb)); + assert_eq!(resolution(&s, at(src, "tb.sig", 0, 3)), Resolution::Resolved(sig)); +} + +/// QA F2: an import that could supply the head makes it the imported name +/// (a local, by the LRM) whether or not the workspace can say so — doubt, so +/// nothing is rooted: the head keeps the import's candidate and no segment +/// after it is a reference. +#[test] +fn an_import_in_scope_wins_and_roots_nothing() { + let src = "module probe (output logic o);\n import p::*;\n assign o = tb.dut.x;\nendmodule\n"; + let s = sem(src); + let imported = Resolution::ExternalCandidate { + paths: vec!["p::*".to_string()], + surface: Surface::Connection, + }; + assert_eq!(resolution(&s, at(src, "tb.", 0, 0)), imported); + assert!(s.reference_at(at(src, "dut.", 0, 0)).is_none()); +} + +/// QA F4: a head written inside a class (any class: a member, inherited or +/// macro-declared, is never a path lucisv can prove), or in a scope where an +/// unexpanded macro stands as an item, roots nothing. +#[test] +fn a_head_inside_a_class_or_beside_a_macro_item_roots_nothing() { + for (src, head) in [ + // A11: a class with no base, `cfg` declared by a macro. + ("class env;\n `DECLARE_CFG\n task run(); if (cfg.en) $display(\"x\"); endtask\nendclass\n", "cfg."), + // D2: a class in a package writing a hierarchical path (illegal). + ("package env_pkg;\n class seq;\n task body(); tb.dut.x = 1; endtask\n endclass\nendpackage\n", "tb."), + // A12: a module whose `st` comes from a macro. + ("module user (output logic o);\n `DECL_STRUCT(st)\n assign o = st.a;\nendmodule\n", "st."), + // The macro one scope out still casts its doubt inward. + ("module user (output logic o);\n `DECL_STRUCT(st)\n initial begin : b\n o = st.a;\n end\nendmodule\n", "st."), + ] { + let s = sem(src); + assert_eq!(resolution(&s, at(src, head, 0, 0)), Resolution::NotFound, "{src}"); + let tail = at(src, head, 0, head.len()); + assert!(s.reference_at(tail).is_none(), "{src}"); + } +} + +/// QA F1: a package sharing the root's name lends the path nothing — neither +/// the head nor any segment after it answers — and a package alone is never +/// a root (`pk.x` is illegal). +#[test] +fn a_package_never_lends_a_top_rooted_path_its_members() { + let pkg = "package tb;\n logic dut;\nendpackage\n"; + let other = "module other;\n initial force tb.dut.x = 0;\nendmodule\n"; + let dut = "module dut_a;\n logic x;\nendmodule\n"; + let both = WorkspaceIndex::build( + [("dut_a.sv", dut), ("tb.sv", TB), ("tb_pkg.sv", pkg), ("other.sv", other)] + .into_iter() + .map(|(n, t)| (PathBuf::from("/rtl").join(n), t)), + ); + let s = sem(other); + for needle in ["tb.", "dut.", ".x"] { + let skip = usize::from(needle.starts_with('.')); + assert_eq!(external(&s, &both, at(other, needle, 0, skip)), "unresolved", "{needle}"); + } + let user = "module user (output logic o);\n assign o = pk.x;\nendmodule\n"; + let only = WorkspaceIndex::build( + [("pk.sv", "package pk;\n logic x;\nendpackage\n"), ("user.sv", user)] + .into_iter() + .map(|(n, t)| (PathBuf::from("/rtl").join(n), t)), + ); + let s = sem(user); + assert_eq!(external(&s, &only, at(user, "pk.", 0, 0)), "unresolved"); + assert_eq!(external(&s, &only, at(user, ".x", 0, 1)), "unresolved"); +} + +/// Inside an extending class the base could supply the head, so it stays the +/// base's candidate and no path is rooted at a module. +#[test] +fn inside_an_extending_class_the_head_is_the_bases() { + let src = "class c extends base;\n function void f();\n cfg.dut.x = 1;\n endfunction\nendclass\n"; + let s = sem(src); + assert!(matches!(resolution(&s, at(src, "cfg.", 0, 0)), Resolution::InheritedCandidate { .. })); + assert!(s.reference_at(at(src, "dut.", 0, 0)).is_none()); +} + +#[test] +fn dollar_root_names_the_top_module_and_skips_the_lexical_walk() { + let src = "module probe (output logic o);\n logic tb;\n assign o = $root.tb.dut.g_sw[0].buf_q;\nendmodule\n"; + let s = sem(src); + // The local `tb` is not what `$root.tb` names. + assert_eq!(resolution(&s, at(src, "tb.dut", 0, 0)), candidate(&["tb"])); + assert_eq!(resolution(&s, at(src, "dut.", 0, 0)), candidate(&["tb::dut"])); + assert_eq!(resolution(&s, at(src, "buf_q", 0, 0)), candidate(&["tb::dut::g_sw::buf_q"])); + let ws = WorkspaceIndex::build( + [("dut_a.sv", DUT), ("tb.sv", TB), ("p.sv", src)] + .into_iter() + .map(|(n, t)| (PathBuf::from("/rtl").join(n), t)), + ); + assert_eq!(external(&s, &ws, at(src, "tb.dut", 0, 0)), "Module"); + assert_eq!(external(&s, &ws, at(src, "buf_q", 0, 0)), "Var"); +} + +#[test] +fn dollar_root_reaches_a_top_module_this_file_declares() { + let src = "module tb;\n logic sig;\nendmodule\nmodule probe (output logic o);\n logic tb;\n assign o = $root.tb.sig;\nendmodule\n"; + let s = sem(src); + let tb = s.symbol_at(at(src, "module tb", 0, 7)).expect("tb"); + let sig = s.symbol_at(at(src, "logic sig", 0, 6)).expect("sig"); + assert_eq!(resolution(&s, at(src, "tb.sig", 0, 0)), Resolution::Resolved(tb)); + assert_eq!(resolution(&s, at(src, "tb.sig", 0, 3)), Resolution::Resolved(sig)); +} + +/// The completion walk (`Semantics::member_site`) does not root an unknown +/// head at a top module — a popup after an unknown head answers nothing, so +/// the ordinary tiers run, until the language server's member list takes the +/// change knowingly (README, Handshakes). `$root.tb.` says what it is and is +/// rooted in both walks. +#[test] +fn the_completion_walk_roots_only_an_explicit_dollar_root() { + let s = sem(PROBE); + let scope = s.reference_at(at(PROBE, "tb.", 0, 0)).expect("tb").scope; + assert_eq!(s.member_site(scope, "tb", &["dut".to_string()]), None); + let rooted = s.member_site(scope, "$root", &["tb".to_string(), "dut".to_string()]); + assert_eq!( + rooted, + Some(MemberSite::Unit { path: "tb::dut".to_string(), surface: Surface::Hierarchical }) + ); + assert_eq!(s.member_site(scope, "$root", &[]), None); + assert_eq!(s.member_site(scope, "`MACRO", &[]), None); +} + +#[test] +fn a_system_name_or_a_macro_roots_nothing() { + let src = "module probe (output logic o);\n assign o = `TOP.dut.x;\n assign o = $unit.x;\nendmodule\n"; + let s = sem(src); + assert!(s.reference_at(at(src, "dut.", 0, 0)).is_none()); + assert!(s.reference_at(at(src, ".x;", 1, 1)).is_none()); +} + +/// QA R1: a macro standing where a declaration could stand — a statement in +/// a `begin`/`end`, a task or a function body, or an entry of the port list — +/// may declare the head, so nothing is rooted from that scope (or one inside +/// it). +#[test] +fn a_macro_where_a_declaration_could_stand_roots_nothing() { + for src in [ + // E1 + "module user;\n initial begin\n `DECL_LOCAL(st)\n st.a = 1;\n end\nendmodule\n", + // E2 + "module user;\n task automatic t();\n `DECL_LOCAL(st)\n st.a = 1;\n endtask\nendmodule\n", + // E6 + "module user;\n function automatic void f();\n `DECL_LOCAL(st)\n begin st.a = 1; end\n endfunction\nendmodule\n", + // E3, the parse is tolerant of the macro port + "module user (`MY_PORTS, output logic o);\n assign o = st.a;\nendmodule\n", + // E3, the macro after a port + "module user (input logic i, `MY_PORTS);\n initial st.a = i;\nendmodule\n", + ] { + let s = sem(src); + let head = at(src, "st.a", 0, 0); + assert!( + matches!(s.reference_at(head).map(|r| &r.resolution), Some(Resolution::NotFound) | None), + "{src}" + ); + assert!(s.reference_at(at(src, "st.a", 0, 3)).is_none(), "{src}"); + } +} + +/// …and the shapes that cannot declare the head keep rooting: a macro used +/// as a data type, and a macro in a *sibling* generate block (E7, E8). +#[test] +fn a_macro_that_cannot_declare_the_head_still_roots() { + for src in [ + "module user;\n `MY_STRUCT_T other;\n initial st.a = 1;\nendmodule\n", + "module user;\n if (1) begin : g1\n `DECL_LOCAL(st)\n end\n if (1) begin : g2\n initial st.a = 1;\n end\nendmodule\n", + "module user;\n initial st.a = $bits(`WIDTH);\nendmodule\n", + ] { + let s = sem(src); + assert_eq!(resolution(&s, at(src, "st.a", 0, 0)), candidate(&["st"]), "{src}"); + assert_eq!(resolution(&s, at(src, "st.a", 0, 3)), candidate(&["st::a"]), "{src}"); + } +} diff --git a/docs/features/top-rooted-paths/README.md b/docs/features/top-rooted-paths/README.md new file mode 100644 index 0000000..d9333e7 --- /dev/null +++ b/docs/features/top-rooted-paths/README.md @@ -0,0 +1,683 @@ +# top-rooted-paths + +TODO §65.4 (from §65.1 QA F1). Wave 0.62.0 (§65.7), serial after lane A. + +## Goal + +A hierarchical path whose head is a top-level module declared in another +file — `tb.dut.u_x.sig`, the shape every opentitan DV `force`, `$deposit` +and `uvm_hdl_*` path takes (IEEE 1800 §23.6: a top-level module name is the +root of a hierarchical name) — resolved nothing: `tb` was a `Target::Lexical` +use that missed in the writing file, `resolve::head_site` stopped the spine +there, no segment after it was a reference, and a rename of `dut`'s +declarations left the path behind (since §65.1 with a warning). The goal is +that such a path resolves through the workspace exactly as an instance path +does, so `find_references` and LSP references list its segments and `rename` +rewrites them, while a root the workspace does not declare stays unchanged +and is warned about. + +## Design + +- **The head is its own target.** `bind/expr.rs`: the bare identifier that + heads a dotted path (`ExprKind::Member` whose base is an `Ident`) is bound + as `Target::PathHead` instead of `Target::Lexical`. Only the head of a dotted + path: a bare identifier anywhere else is unchanged, so a value-position miss + is still never swept through the unit table (the reason `lexical`'s doc + gives). The `with`/`bind` funnel in `bind/mod.rs::use_member` treats + `PathHead` exactly as `Lexical`. +- **`resolve/root.rs` (new)** holds the root rules. **The governing rule + (lead, after QA): a path is rooted only when this file shows the head can + be nothing but a top-level module or interface; in doubt it is not, and the + path stays unresolved and warned about.** + - `roots_at_top(scopes, from)`: false when any scope from the use up to + the file is a class (a member, inherited or macro-declared, is never a + provable path into the hierarchy; a class in a package may not reference + it at all) or holds an unexpanded macro invocation where a declaration + could stand (`Scope::macro_items`, set by `Binder::mark_macro_declarations` + for an item, a statement or block item in any `begin`/`end`, `fork`, task + or function body, and a port-list entry or an unreadable port element; + it may declare the name). A macro inside an expression or used as a data + type cannot declare a name and does not block. + - `path_head`: the lexical answer; on a plain `NotFound` that + `roots_at_top` allows, the candidate `ExternalCandidate { paths: [head], + surface: Hierarchical }`. An import candidate (`import p::*` in scope, + which by the LRM could supply the name) is left exactly as `lexical` + gave it, whether or not the workspace can answer it; so is an + `InheritedCandidate`. + - `unit_root`: the site `MemberSite::Unit { path: head, surface: + Hierarchical }`. + - `$root.tb.…`: `top_site`/`top_module` look `tb` up at file scope only + (an in-file module or interface), else the workspace unit. `$root` skips + the lexical walk, so a local `tb` does not capture `$root.tb`. +- **`resolve.rs::head_site`**: on a plain `NotFound` that `roots_at_top` + allows (the same rule as the head's own reference) the resolution walk + answers `root::unit_root(head)`, so the head reference and the segments + after it are rooted in one unit; anything else roots nothing. The workspace's + `fold_path` then walks `tb` → `dut`'s type → … exactly as for an instance + path. A system name or a macro (`$unit`, `` `TOP``) roots nothing. +- **The completion walk is unchanged.** `member_site` (what + `Semantics::member_site` and the completion popup call) and the resolution + walk share `spine_site`, parameterised by `HeadMiss`: `member_of` passes + `TopModule`, `member_site` passes `Nothing`. A popup after an unknown head + keeps answering `None` (so the ordinary tiers run), which the server's + completion tests pin; offering `tb.`'s members is a server-side change + (Handshake H2). `$root.tb.` is rooted in both walks. +- **Only a module or an interface is a root, and a package is never a + hop.** `workspace/external.rs`: a bare path equal to the name on the + *hierarchical* surface (only a path head produces one) answers through + `root_units` — all instantiable, else nothing. And `fold_path`, on the + hierarchical surface, checks every unit it stands in (`design_unit`): the + first must be declared and only as modules/interfaces; a later one may not + be a module and something else at once (the member table is keyed by name + and would merge the two). A later unit that is only a package would need a + declaration typed with a package's name, which is not code; the separate + "never a package" clause was dropped as unreachable (QA M7). So with a + module and a package both named `tb` the head *and* every segment answer + nothing, and `pk.x` with only a package `pk` resolves to nothing (QA F1). +- **The rename's file set (LSP)**: `WorkspaceIndex::path_units_to(def)` + (new, `workspace/path_units.rs`) lists every unit an indexed hierarchical + use of `def` walks through — the root and each hop's type — read off the + facts the index holds. `lucisv_server/src/state/sources.rs:: + want_declaration` adds those units' declaring files, so a three-hop + `tb.dut.u_core.sig` resolves inside the rename's set as in the whole (QA + F3; lead-granted). A unit outside the index scope adds nothing, and the + path stays warned about. +- **An accurate refusal** (`vlog_refactor/src/rename/mod.rs`): a rename asked + at a path segment the workspace could not walk is refused with "`x` is a + segment of a hierarchical path lucisv could not resolve to one + declaration …", not "declared outside the files lucisv indexes". +- **`FACTS_FORMAT` 21 → 22** (`facts.rs`, reason written there): no new + field, but new records — a 0.61.0 store would answer as though no DV file's + `force tb.dut.…` named anything. +- **The §65.1 path warning** (`vlog_refactor/src/rename/paths.rs`): a segment + of a top-rooted path (head is `$root`, or the head's reference is a root + candidate) whose overlay answer is `StillUnresolved` counts as unresolved, + so the warning still fires for a root the workspace does not declare, or + declares several times. An `Ambiguous` answer is not flagged: when it can + name the renamed declaration `collect_occurrences` already refuses the + rename. +- **Said once** (Handshake H1, lead-granted): `warnings.rs`'s + `unresolved_candidate_warnings` skips a candidate that + `paths::names_top_rooted_miss` says the path scan names, so such a line + carries only the §65.1 path warning. The file is lexed for that check only + when an unanswered candidate is on the hierarchical surface. + +## What resolves now + +- `tb.dut.g_sw[0].buf_q` in a file that does not declare `tb`, with exactly + one `module tb` (or `interface tb`) in the set: `tb` → the module, `dut` → + the instance, `g_sw` → the block, `buf_q` → the variable. Every segment is + a reference: `find_references` lists it, `rename` of any of the four + declarations (or from the segment itself) rewrites it, verified as usual. +- `$root.tb.dut.…`, the same, and `$root.tb.x` against an in-file `tb`. +- Not rooted, by the rule above, and left warned exactly as before §65.4: a + head an import could supply, a head inside any class, a head in (or under) + a scope holding an item-level macro invocation, a head named both a + module and a package, and a package alone. + +## Limits + +- **Several `module tb` in the set** (opentitan: 70 files under `hw/`): + `tb` is `Ambiguous`, `tb.dut` names 70 instances, and `member_unit_in` + refuses an ambiguous hop, so nothing after the head resolves; the rename + leaves the path and warns. Choosing the + `tb` whose branch has the next member was considered and rejected: the + whole-tree `gen_sw_assigns` case is ambiguous between `keymgr` and + `keymgr_dpe` anyway, and an `Ambiguous` answer that can name the renamed + declaration makes `collect_occurrences` refuse the whole rename — so + branching would turn today's warnings into refusals for every common + member name. +- **A renamed top module's `tb` heads are references** to it. With several + same-named tops a rename of one is refused as ambiguous (pinned: + `renaming_one_of_two_same_named_tops_is_refused`); before, the heads were + `NotFound` and only the declaration was renamed. +- **Any wildcard import in scope stops rooting** — including the + `import uvm_pkg::*;` nearly every opentitan DV interface starts with. By + the LRM such an import could supply the head, and `uvm_pkg` is not in the + tree for the index to rule it out, so the path is doubt. Measured: on + opentitan `hw` (and in `hw/ip/keymgr_dpe`) the reference postings are + exactly master's — no DV force path roots. Rooting when every supplying + import is indexed and shown not to hold the head is possible future work; + it would not change opentitan while `uvm_pkg` is outside the tree. +- **Any macro where a declaration could stand blocks rooting** from its + scope down (lead's R1 ruling): a `` `uvm_info `` statement in the block + beside a `force` blocks it too, since the binder cannot tell a logging + macro from a declaring one. A macro statement in an unnamed `begin` whose + statements bind in the enclosing scope blocks that whole scope. +- **Completion after `tb.`** answers nothing (H2, deferred by the lead). +- `undeclared-identifier` no longer sees an unknown path head as `NotFound` + (it is a root candidate now). Measured on opentitan `hw`: 7 findings + before and after, identical. + +## Assumptions + +- A bare identifier followed by `.` whose lexical lookup misses plainly — + no import could supply it, no class or item-level macro on the scope + chain — is a top-level module name (§23.6); a typo there is an unresolved + candidate, not `NotFound`. +- Only the head of a dotted path is a root; `tb[0].x` (an indexed head) is + not modelled as one. +- The surface tag on the head candidate is the only signal that a bare path + must be instantiable; nothing else produces a bare hierarchical path. + +## Handshakes + +- **Consumes**: `WorkspaceIndex::member_unit_in` / `fold_path` (unchanged), + `hierarchy::member` (unchanged), `Scope::analysis().external`. +- **Promises (changed)**: `Resolution::ExternalCandidate` with + `surface: Hierarchical` and a bare path is now produced for a path head; + `follow_one` answers it with modules and interfaces only. `Semantics:: + member_site` is unchanged for every head except `$root`. +- **H1 (granted by the lead 2026-10-19, done)**: `warnings.rs` + `unresolved_candidate_warnings` skips a segment `paths.rs` names + (`paths::names_top_rooted_miss`, `pub(super)`), so an unresolved + top-rooted path is said once, in the §65.1 wording. +- **F3 (granted by the lead, done)**: `lucisv_server/src/state/sources.rs` + `want_declaration` adds the files of `WorkspaceIndex::path_units_to(def)`. + **Promised to the server**: `path_units_to` is a pure read of the index's + facts (no file is read); its cost is one pass over the reference records + of each file holding a use of `def`. +- **Outside the listed files, flagged**: `vlog_refactor/src/rename/mod.rs` + gained `hierarchical`/`unresolved_path` so the refusal at an unresolved + segment is the accurate one the lead's F3 ruling asks for (two call + sites, the message only; no rename decision changes). +- **H2 (deferred by lead → TODO; `lucisv_server/src/completion/member.rs` untouched)**: to offer + `tb.`'s members, call a root-aware member site and answer `None` when the + index holds no unit for the root (the server's + `an_unresolvable_head_answers_nothing_at_all` must keep passing). + +## Status / TODO + +- [x] root lookup in `head_site`, the head recorded as a module use +- [x] QA's repro renames the path instead of warning +- [x] the §65.1 warning stays for an undeclared (or ambiguous) root +- [x] `find_references` and LSP references list the path segments +- [x] the local-shadows-top case +- [x] `$root.` (cheap: done) +- [x] opentitan index/scan cost before and after; `FACTS_FORMAT` bump reasoned +- [x] H1: an unresolved top-rooted path is said once (lead-granted) +- [x] rework after QA: F1 (no package root or hop), F2 (an import wins), + F3 (LSP rename set holds the path's units; accurate refusal), F4 (no + root in a class or beside an item-level macro) +- [ ] H2: completion after `tb.` — deferred by lead → TODO + +## Work log + +**2026-10-19 (dev, Opus).** Worktree fast-forwarded ec492cd → 51b975b. + +- Implemented as designed above. `resolve.rs` 559 → 586 production lines + (the walk split `spine_site`/`HeadMiss`); the root rules are the new + `resolve/root.rs` (29). +- Deviation: the planned single walk would have changed completion after an + unknown head (two server tests), so completion keeps its walk (H2). +- Deviation: rooting a head on an import miss as well as on `NotFound` — + opentitan's DV interfaces import packages, so `NotFound`-only would leave + the target shape unresolved. +- QA's repro `a_path_rooted_at_another_files_top_module_is_never_silently_left_behind` + flipped to assert the rename (granted). Other §65.1 tests that used a + declared `tb` as the vehicle for an *unresolved* root now drop `tb.sv` from + their set (so the root is genuinely undeclared) and gained the declared + counterpart asserting the rename: `qa_generate_label.rs` (three rechecks), + `qa_warning_scope.rs` (two), `rename_generate_label.rs` (two, wording), + `generate_blocks.rs` / `member_access.rs` (an unknown head's tail is now a + candidate, not absent), server `rename_generate_label.rs` (shown wording). +- Invariant 4: `vlog_refactor/src/check/` untouched. +- Tests: `vlog_semantic/tests/top_rooted_paths.rs` (13), + `vlog_refactor/tests/top_rooted_paths.rs` (8), one declared-root + counterpart in `qa_generate_label.rs`, `vlog_refactor/tests/ + opentitan_top_rooted.rs` (3, ignored), `lucisv_server/src/server/tests/ + references_top_rooted.rs` (5). Counts before → after: `vlog_semantic` + 401 → 414 (4 ignored), `vlog_refactor` 727 → 736 (3 → 6 ignored), + `lucisv_server` 1 865 → 1 870 (40 ignored), `lucisv_mcp` 383 → 383; + `vlog_linter` 673 → 673. Gates: fmt, clippy `-D warnings`, the four suites + green. One `lucisv_server` run lost two `large::` linear-time tests to host + load (load average 14–16, another lane's suites); the re-run was green. + +*Opentitan* (eval clone `~/.cache/lucisv-eval/ot`, read-only; release; +engine API, nothing written — `vlog_refactor/tests/opentitan_top_rooted.rs`, +ignored by default): + +| | before (51b975b) | after | +|---|---|---| +| `rename gen_sw_assigns`, set `hw/ip/keymgr_dpe` (23 files, the LSP folder scope) | 1 site in 1 file; warnings: `uvm_info` macro arg :523, path :514,515,517 | **4 sites in 2 files** (label + `keymgr_dpe_if.sv:514,515,517`); warning: `uvm_info` :523 only | +| same, set `hw` (3 979 files, 70 `module tb`) | 1 site; 4 warnings (2 macro args, 2 path lines `keymgr_if.sv:468,469,471`, `keymgr_dpe_if.sv:514,515,517`) | 1 site; 4 warnings, the same 4 (6 before H1: the 2 candidate lines for the same sites) | +| rename time, `hw` | 2.16 s | 2.23 s | +| facts, `hw` (encoded) | 54 297 047 B | 54 465 816 B (+0.31 %) | +| index postings `reference_sites` / keys | 528 532 / 60 559 | 528 719 / 60 573 | +| `WorkspaceIndex::build`, `hw`, best of 3 | 1.65 s | 1.69 s | +| `lucisv check hw` wall, two runs each | 1.050 / 1.051 s (re-run 1.059 / 1.063) | 1.064 / 1.065 s | +| `lucisv check hw` findings | 1 158 | 1 158, byte-identical output | +| `check --select undeclared-identifier hw` | 7 | 7, identical | + +The host was shared with another lane's suites (load average 14–16), so the +sub-2 % time deltas are within noise. + +**2026-10-19 (dev, Opus) — H1.** Lead granted H1, deferred H2. +`paths::names_top_rooted_miss` (`pub(super)`, wraps `is_segment` + +`top_rooted_miss`) is asked by `warnings.rs::unresolved_candidate_warnings` +for each unanswered hierarchical candidate; a hit is skipped. The tests that +tolerated the duplicate now assert exactly one line again +(`qa_generate_label.rs` recheck, `rename_generate_label.rs` back to +`warnings.len() == 1`, `top_rooted_paths.rs` two, server +`an_unresolved_path_in_an_open_buffer_is_shown_as_a_rename_warning` back to +`probe.sv:2:` with no "more"), plus a new +`an_unresolved_top_rooted_path_is_named_by_exactly_one_warning` (QA's repro +undeclared, and with three `module tb`), and the opentitan whole-tree probe +asserts the force lines are said once. Opentitan `rename gen_sw_assigns` +over `hw`: **6 → 4 warnings** (2 macro arguments, 2 path lines), 1 site, +2.16 s; IP folder unchanged (4 sites in 2 files, 1 warning). Counts: +`vlog_refactor` 737 (6 ignored), `lucisv_server` 1 870 (40), `lucisv_mcp` +383 (4) — its `a_rename_names_each_same_named_file_by_its_root_relative_path_once` +passes with the two path lines and no candidate lines. fmt and clippy clean. + +**2026-10-19 (dev, Opus) — rework after QA.** Governing rule (lead): root +only when the engine can show the head is a top module or interface. + +- **F1** (`workspace/external.rs`): `fold_path` checks every unit on the + hierarchical surface (`design_unit`): first unit declared and all + modules/interfaces; later units never a package nor mixed. Tests: + semantic `a_package_never_lends_a_top_rooted_path_its_members`; refactor + `qa_f1_a_package_sharing_the_roots_name_lends_the_path_nothing` (QA's + B12: renaming the package's `dut`, the module's instance `dut`, or `x` + leaves `tb.dut.x` and names it), `qa_f1_a_package_is_never_a_root` + (A3/A4). +- **F2** (`resolve/root.rs`, `resolve.rs::head_site`): an import candidate + is never rooted, and the "bare name last" fallback is gone. Tests: + semantic `an_import_in_scope_wins_and_roots_nothing` (replaces + `an_import_in_scope_is_tried_before_the_top_module`); refactor + `qa_f2_an_imported_head_is_never_rooted_at_a_same_named_module` (A1). +- **F3** (`workspace/path_units.rs` new, `lucisv_server/src/state/sources.rs`, + `vlog_refactor/src/rename/mod.rs` message): server tests + `rename_top_rooted_scope.rs` (5, folder scope): three-hop rename from the + declaration and from the segment, the generate-block `buf_q`, LSP equals + engine over the scope, and a root outside the scope (warned; segment + rename refused with "hierarchical path", not "declared outside"). With + the `sources.rs` rung disabled four of the five fail. +- **F4** (`Scope::macro_items`, `roots_at_top`): semantic + `a_head_inside_a_class_or_beside_a_macro_item_roots_nothing` (A11, D2, + A12, and a macro one scope out); refactor + `qa_f4_a_head_this_crate_cannot_see_is_never_rooted`. +- Mutations: `design_unit` and `roots_at_top` both forced true → both F1 + refactor tests and the F4 test fail; `head_site` rooting an import + candidate again → the F2 test fails. +- Changed tests: `rename_generate_label.rs` genblk1 refusal accepts the new + message; the opentitan probe's IP-folder test is now + `the_ip_folder_leaves_the_imported_head_and_says_so`. +- Counts: `vlog_semantic` 416 (4 ignored), `vlog_refactor` 741 (6), + `lucisv_server` 1 875 (40), `lucisv_mcp` 383 (4), `vlog_linter` 673 (0); + fmt and clippy `-D warnings` clean; every suite through the guard, exit 0. +- Opentitan: `lucisv check hw` stdout and stderr byte-identical to master's + binary (1 158 lines); `--select undeclared-identifier` identical (7). + `rename gen_sw_assigns`: IP folder 1 site, 2 warnings (`uvm_info` :523, + path :514,515,517 — `keymgr_dpe_if.sv` imports `uvm_pkg::*`); whole `hw` + 1 site, 4 warnings, 2.13 s — both exactly master's. Index over `hw`: + `reference_sites` 528 532 / keys 60 559, equal to master; facts + 54 333 266 B (+36 KB, the head candidates). + +**2026-10-19 (dev, Opus) — rework 2 (R1, M7).** + +- **R1**: `Binder::mark_macro_declarations(scope)` (`bind/mod.rs`) is now + called for an item-level macro (`bind/item.rs`), a macro statement + (`bind/stmt.rs`, `StmtKind::MacroStmt`, on the scope the statement binds + in) and a header port list holding a `` ` ``-spelled port or an error + element (`bind/item.rs::port_list_may_hide_declarations`, on the module's + scope). Tests: semantic + `a_macro_where_a_declaration_could_stand_roots_nothing` (E1, E2, E6, E3 + twice) and `a_macro_that_cannot_declare_the_head_still_roots` (data-type + macro, sibling generate block E7, a macro inside an expression); refactor + `qa_r1_a_macro_where_a_declaration_could_stand_blocks_rooting` (E1, E2, + E6 left and named; E3 left) and + `qa_r1_a_macro_off_the_scope_chain_or_as_a_type_still_renames` (E7, E8 + shape). With both new flag sites disabled the refactor R1 test fails. +- **M7**: the later-hop "never a package" clause in `design_unit` dropped + as unreachable (argued in its doc comment); the mixed module+package rule + still refuses QA's B12, pinned by the F1 tests. +- **QA's cases1–6 re-run** against this build (QA's harness + `scratchpad/qa654/attack`, outputs in `scratchpad/p654/cases{1..6}.out`). + Every rename either rewrites the correct sites or leaves the path and + warns: + - A1, A3, A4, A7, A8, A10, A11, A12: left and warned. A2: the package + variable renamed with its use (correct). A5, A6, A9: the head is a local + (clocking block, interface port, virtual interface handle), the path is + another declaration, nothing to warn (correct). + - B1, B7, B8, B10: renamed correctly (local `tb` elsewhere warned in B1). + B2, B3: `$root` paths renamed; the local-`tb` line warned; two `tb` + refused. B4: five colliding renames refused. B5: the instance-array + path warned, the unpacked array and the instance array name renamed. + B6 (bind) and B9 (forward local) warned. B11: warned. B12: both renames + leave `tb.dut.x` and warn. + - C1: renamed from the declaration, the segment and the label; refs list + all three sites. + - D1: the unshadowed module's path renamed, the shadowed one warned. D2, + D3 (struct field), D6 (typo head): warned; D3's `acc` renamed. D4, D5: + renamed correctly. + - E1, E2, E3, E4, E5, E6: left and warned. E7 (sibling block) and E9 + (modport macro): renamed, correctly. E8 (data-type macro): the head is + the local `st`, warned as an unresolved candidate. + - F3 (`cases6`): each `sig` rename edits exactly its own references. +- Counts: `vlog_semantic` 418 (4 ignored), `vlog_refactor` 743 (6), + `lucisv_server` 1 875 (40), `lucisv_mcp` 383 (4), `vlog_linter` 673 (0); + fmt and clippy `-D warnings` clean; every suite through the guard, exit 0. +- Opentitan `lucisv check hw`: stdout and stderr byte-identical to master's + binary (1 158 lines); `--select undeclared-identifier` identical (7). + +## QA log + +**2026-10-19 — QA agent (Opus).** + +**Verdict: conditional pass. F1 needs a fix before release, and the lead +should rule on F2–F4.** Everything else held: the +verifier, the shadow and `$root` rules, the cache bump, opentitan byte +identity, and every guard mutated. + +*Gates* (worktree as handed over, 51b975b + dev diff; every suite through +`tools/guard.sh`, guard exit 0 each, logs kept): +- `cargo fmt --all --check` clean, and `clippy --workspace --all-targets -D + warnings` clean. +- Suites: `vlog_semantic` 414 passed (4 ignored), `vlog_refactor` 737 (6), + `lucisv_server` 1 870 (40), `lucisv_mcp` 383 (4), `vlog_linter` 673 (0). + All 0 failed, and every count matches the work log. No host stall. + +*Tests read.* The new semantic, refactor and server tests assert what their +names say: exact `file:line` sets, the exact texts after the edit, and +warning counts. Flipped tests: +- `qa_generate_label.rs` and `qa_warning_scope.rs` now drop `tb.sv`, so the + root is really undeclared, and each gained a declared counterpart. That is + sound. +- The server rename test covers only the block label `g_sw`, which is one hop + below the root's child. That is exactly the case F3 does not hit. + +*Mutations.* Each was applied in a scratch copy of the workspace +(`scratchpad/qa654/ws`), never in this tree, and each ran the semantic, +refactor and server suites: +- M1: remove the module/interface-only rule in `root_units`. Caught by 1 + semantic test (`only_a_module_or_an_interface_is_a_root`); 0 refactor or + server failures. +- M2: a local of the head's name no longer shadows, in both `path_head` and + `head_site`. Caught by 70 semantic and 37 refactor failures. +- M3: `$root.tb` ignores an in-file `tb`, in `top_site` and `top_module`. + Caught by 1 semantic test (`dollar_root_reaches_a_top_module_this_file_declares`). +- M4: `$root.tb` goes through the lexical walk, so a local `tb` captures it. + Caught by 2 semantic tests (`dollar_root_names_the_top_module_and_skips_the_lexical_walk` + and the previous one). +- All four are caught. M1 and M3 are each pinned by a single unit test, and + nothing at the rename level pins them. + +*Verifier (invariant 4; `check/` untouched).* 8 masked-corruption attacks +went into a scratch-only `check/qa_top_rooted.rs` over `dut_a` / `tb` / +`probe` (`tb.dut.buf_q` ×2 and `$root.tb.dut.buf_q`). All 8 behaved: three +honest edit sets verify, and every corrupt one is refused: +- a leaf rename missing each one of the 3 path segments, or missing the + declaration; +- a top-module rename missing each one of the 3 heads, or also renaming a + local `logic tb`; +- an instance rename missing each segment. + +*Opentitan* (`~/.cache/lucisv-eval/ot`, read-only, `git status` clean before +and after): +- **`lucisv check --no-cache hw`.** Master 51b975b, built in a scratch `git + worktree` that has since been removed, and this branch both print 1 158 + lines. stdout and stderr are byte-identical. +- **`--select undeclared-identifier`.** Identical, 7 findings. +- **`find_references` at 48 seeded random positions.** Half of them follow a + `.`, over `hw/ip/{keymgr_dpe,aes,uart,i2c}`. Before and after are + byte-identical. +- **Targeted top-rooted positions.** These were `pwrmgr_if.sv:191` + `tb.dut.u_slow_fsm…`, and `otp_ctrl_if.sv:169/287` and `tb.sv:248` under + `top_earlgrey/ip_autogen/{pwrmgr,otp_ctrl}`. Every difference is a segment + of a top-rooted path that now has references where it had none. For + example, `gen_partitions` went from no symbol to 12 references (10 force + and release lines, `tb.sv` and the RTL label), and `u_slow_fsm` went from + none to 4. +- **No other names changed.** + +*`FACTS_FORMAT` 22.* The server ran over one fixture first with master's +binary (format 21), then with this branch. The new server analysed every +file afresh, with no `cached:` lines, and answered with the new references. +A second run of the new server read its own cache. The unit tests +`index_cache.rs:846` and `qa_m6.rs:367` already reject every older format. + +*Code.* +- No new `unwrap`, `expect` or `panic`. The index arithmetic in `paths.rs` + `path_head` and `matching_open` is guarded. +- Production lines: `resolve.rs` 586, which is under 600 but at the mark, so + the next arm goes in a module. `resolve/root.rs` is 29, `paths.rs` 158, + `warnings.rs` 555, `external.rs` 224. +- `warnings.rs::unresolved_candidate_warnings` is now about 79 lines, + including its doc comment. That is just under the 80-line investigate mark + (Info). + +*Findings* + +- **F1 (High): silent wrong rename and silent miss when a module and a + package share the root's name.** Location: `vlog_semantic/src/workspace/external.rs:337-342` + (`follow_one`, the multi-segment branch). + - What `root_units` guards: only the bare head path `tb`. + - What it misses: the next segment's path `tb::dut` folds `tb` and asks + `member_chain` on the hierarchical surface, which answers from the + package. + - Repro: `module tb; dut_a dut (); endmodule`, `package tb; logic dut; + endpackage`, and `other.sv`: `initial force tb.dut.x = 0;`. + - Renaming the package's `dut` to `d2` rewrites the path to + `tb.d2.x`, which is wrong because the path names the module's + instance. No warning. + - Renaming the module's instance `dut` to `u_dut` leaves the path, also + with no warning, because it resolved to a different declaration. + - Before §65.4 neither edit touched the path, and the path was warned + about. + - The same root cause makes `pk.x`, with a package `pk` and no module + (illegal code), resolve into the package, and renaming the package + member rewrites it (A3/A4, Low on their own). + - This contradicts the Design bullet "Only a module or an interface is a + root". + - Suggested direction, the dev's to choose: apply the instantiable check + to the first hop of a hierarchical candidate rooted at a top. Then add a + rename-level test, because M1 is caught only by the semantic suite. + +- **F2 (Medium, a documented limit, but a silent wrong rename): an imported + package variable used as a head, next to a same-named module.** Location: + `vlog_semantic/src/resolve.rs:408` (`head_site` roots on + `ExternalCandidate` as well as on `NotFound`). + - Repro: `package p; typedef struct packed {logic field;} s_t; s_t cfg; + endpackage`, `module cfg; logic field; endmodule`, and + `user.sv`: `import p::*; assign o = cfg.field;`. + - The head `cfg` resolves to `p::cfg`, the package variable, but the tail + `field` resolves to the module's `field`. + - Renaming the module's `field` to `fld2` rewrites `cfg.field` to + `cfg.fld2` with no warning. Before, the tail had no reference. + - The head and its tail disagree about the root, which is detectable. The + tail could carry the head's import paths first (`p::cfg::field`, then + `cfg::field`), or rooting could be refused when the head's own answer is + not a unit. + +- **F3 (Medium, loud): LSP rename misses the files of the path's middle + hops.** Location: `lucisv_server/src/state/sources.rs:235-285` + (`fan_out_of` / `want_declaration`; outside this lane's files, so this is a + Handshake request). + - The rename set holds the declaration, the reference postings and the + instantiation sites of the container. It does not hold the root's file + (`tb.sv`) or a middle hop's file. Inside the rename, the root is then + undeclared. + - Repro, fixture `ip/rtl/{core,dut_a}.sv`, `ip/dv/{tb,probe}.sv`, where + `probe.sv` has `force tb.dut.u_core.sig = 1'b0;`, under the default + folder scope: + - LSP references on `core.sv`'s `sig` list `probe.sv:2`. + - LSP rename of `sig` edits `core.sv` only and warns "probe.sv:2: a + hierarchical path through `sig` was not resolved…". + - Rename from the segment in `probe.sv` is refused with "`sig` is + declared outside the files lucisv indexes", which is misleading. + - The same happens for `buf_q` inside `g_sw`: references list + `probe.sv:2,3`, and rename edits the declaration only. + - `top_sig` (one hop) and `g_sw` (the label) rename fine. + - The Goal's own shape `tb.dut.u_x.sig` is the failing one, and most + opentitan force paths are deeper than one hop. The engine API (and so + `lucisv-mcp`) renames them correctly over the whole set. + - Not silent, because it is warned, but references and rename disagree + over LSP. + +- **F4 (Low–Medium, by the §23.6 assumption): a head the binder cannot see + now roots silently.** Location: `vlog_semantic/src/resolve/root.rs:24` + (`path_head`) with `resolve.rs:408`. + - Before, these were the §65.1 path warning. Now each is renamed silently + through a same-named module: + - a class without `extends` whose `cfg` comes from a macro (A11: + `` `DECLARE_CFG `` then `cfg.en`); + - a module whose struct `st` comes from `` `DECL_STRUCT(st) `` (A12); + - a class in a package writing `tb.dut.x` (D2). That is illegal (a + package may not reference the hierarchy), but it is renamed anyway. + - A cheap narrowing: do not root inside a class scope. Opentitan's DV + classes all live in packages, where no head can legally be a top module. + +- **F5 (Low, documented).** `undeclared-identifier` no longer reports an + unknown path head (`tbb.dut.x`), which is now an unresolved candidate. The + rename still warns, and the opentitan count is unchanged (7). + +*Held (no finding).* +- **Locals shadow.** A local `tb` net (same file or another) shadows and is + warned. A forward-declared local instance `tb` shadows. +- **Labels and other heads.** A named block `blk` beats `module blk`. A + clocking block `cb.data`, a modport / interface port head and a `virtual + bus_if vif` head all stay local. A genvar or parameter head, and `f().x`, + are warned. +- **Classes.** An extending class leaves the head alone and warns. +- **`bind` and `$root`.** A `bind` head is warned (the BindScope funnel). + `$root.tb` with a local `tb` reaches the top, and `$unit::` is unaffected. +- **Renaming the root and its instance.** Renaming `tb` rewrites every head + and `$root.tb`, and skips local `tb`s. Two `module tb` is refused. A + colliding rename of a leaf, the instance or the top is refused (5 cases). + `tb.dut.x = y` renamed `x` → `y` correctly. +- **Arrays.** An instance array `u[2].x` is not descended and is warned. + `mem[3]` and the instance array name itself rename. A struct field through + `acc[1].rl` is warned. +- **Interfaces and upward names.** An interface top works, and so does an + upward module-name reference (`par.sig` from a child). +- **LSP references.** Correct with the declaring file open or closed. Under + `workspace` with two `tb`, they answer nothing and rename is refused. +- **H1.** The dedupe predicate is equivalent to the path scan's, and the + path scan's text prefilter trims newlines, so a multi-line path is not + lost. + +*Fixes made by QA:* none. Scratch harnesses: `scratchpad/qa654/attack` +(case files `cases1–4.txt`), `refs_{new,base}`, `lspfx*`, `probe2.py`. + +**2026-10-19 — QA agent (Opus), re-check after "rework after QA".** + +**Verdict: pass for F1–F4 as reworked.** One new Medium finding needs the +lead's ruling (R1: a macro that is not item-level can declare the head), and +there are two Info notes. No QA fixes were made. + +*Gates.* Every suite ran through the guard with exit 0. +- `cargo fmt --all --check` and `clippy --workspace --all-targets -D + warnings` are clean. +- Suites: `vlog_semantic` 416 (4 ignored), `vlog_refactor` 741 (6), + `lucisv_server` 1 875 (40), `lucisv_mcp` 383 (4), `vlog_linter` 673 (0). + All 0 failed, and every count matches the work log. + +*The old attacks, re-run against the new build* (`cases1–4`, plus LSP +`lspfx`, `lspfx2`). +- **F1 is fixed.** B12 (a module `tb` beside a package `tb`): renaming the + package's `dut` or the module's instance `dut` now leaves `tb.dut.x` and + warns about it, both ways. A3 and A4 (`pk.x` through a package) now warn, + and the segment refuses. +- **F2 is fixed.** A1: the imported `cfg` keeps its head. Renaming the + module's `field` leaves `cfg.field` and warns, and the segment has no + reference. +- **F4 is fixed.** A11 (a class with a macro member), A12 (a macro item in a + module) and D2 (a package class) are all warned again, as before §65.4. +- **F3 is fixed.** The three-hop `tb.dut.u_core.sig` renames over LSP from + the declaration and from the segment: 2 edits in 2 files, equal to the + references. So does the generate-block `buf_q` (3 edits in 2 files). Under + `workspace` scope with two `tb`, the segment refusal now says "segment of + a hierarchical path…". +- **Every other round-1 case is byte-identical to round 1.** That covers + B1–B11, D1, D3–D6, `$root`, the shadows, the collisions and the arrays. + +*New attacks.* +- **F3's wider set (`lspfx4`).** + - The fixture puts an unrelated `sig` in every hop file: `tb.sv` (a local + `sig`, plus `dut.sig` and `dut.u_core.sig`), and `dut_a.sv` (its own + `sig`, plus `module helper` with a `sig`). + - Renaming `core`'s, `dut_a`'s or `tb`'s `sig` over LSP edits exactly the + references, and the engine over the whole set gives the same edits. + - `helper` is never touched, and neither is the unrelated `sig` in any + hop file. +- **A macro beside a head that is not item-level** (`cases5.txt`). These + are the R1 cases: + - E1: `` initial begin `DECL_LOCAL(st) st.a = 1; end `` beside `module st; + logic a;`. Renaming `st.a`'s `a` to `b` rewrites `st.a` to `st.b` + silently. + - E2 and E6: the same inside a task body and a function body. + - E3: `` module user (`MY_PORTS, output logic o); … bus.data `` beside + `module bus`. The rename rewrites it silently. +- **Macro shapes that hold or are warned.** + - Held: a macro in a non-ANSI port region (E4), a macro at file scope + (E5), and a macro used as a data type (E8). + - Rooted, and correctly so: a macro in a *sibling* generate block (E7) is + not in the head's lexical chain. + - A macro inside a modport list (E9) still roots. A modport declares no + variables, so this is no finding. + +*Mutations* (scratch copy, re-synced): +- M5: `roots_at_top` without its class check. Caught by 1 semantic test and + `qa_f4_…`. +- M6: `roots_at_top` without its macro check. Caught by the same two tests. +- M7: `design_unit`'s later-hop "never a package" clause removed. **Not + caught** by any of the three suites (Info). A later hop's unit is an + instance's or a variable's type, and a module and package sharing a name + is already refused by the mixed check. So the clause looks unreachable + short of an instance of a package (malformed code). Either pin it with + such a test or drop it. + +*Opentitan* (read-only, `git status` clean): +- **`lucisv check --no-cache hw`.** Against master 51b975b (scratch + worktree, removed afterwards), stdout and stderr are byte-identical, 1 158 + lines each. `--select undeclared-identifier` is identical. +- **`find_references` spot checks.** The 48 seeded positions are identical + to master. The round-1 top-rooted positions (`pwrmgr_if.sv:191`, + `otp_ctrl_if.sv:169/287`) now answer exactly as master, because those + interfaces import `uvm_pkg::*` and the owner's conservative ruling applies. +- **Info:** on opentitan's DV interfaces the feature is therefore dormant; + every one imports a package. + +*Code.* +- No new `unwrap`, `expect` or `panic`. +- Production lines: `resolve.rs` 587 (at the mark), `resolve/root.rs` 38, + `external.rs` 240, `workspace/path_units.rs` 50, `state/sources.rs` 176. + +*Findings* + +- **R1 (Medium, silent wrong rename; the lead to rule): a macro that is not + item-level can declare the head.** + - Location: `vlog_semantic/src/resolve/root.rs:40` (`roots_at_top`) and + `bind/item.rs` (only `ItemKind::MacroItem` sets `macro_items`). + - What escapes it: + - a macro statement in a `begin`/`end`, task or function body, where a + block-item declaration is legal (E1, E2, E6); + - a macro in an ANSI port list (E3). + - These root the head at a same-named module and rename through it + silently. Before §65.4 they were warned about. + - Narrowing would follow the same rule as F4: a macro statement in any + enclosing procedural scope, and a macro in the port list, also count as + doubt. + - The coordinator's brief says statement macros were left out by design. + E1–E3 show that they can declare the head, so the trade-off is the + lead's call. It needs a module sharing the head's name, which is rare + in RTL. + +## Review + +**2026-10-19 — lead.** Accepted after two reworks. QA (Opus) found four +silent-wrong-rename shapes (F1 a package sharing the root's name; F2 an +imported head beside a same-named module; F4 heads the binder cannot see) +plus the LSP rename set missing the middle hops (F3); its re-check found R1 +(a statement-level or port-list macro declaring the head). All fixed with +tests built from QA's repros; QA's cases1–6 re-run against the final build +are each warned or correctly renamed. Owner's ruling: stay conservative — +a head with an import candidate (e.g. `import uvm_pkg::*` with uvm_pkg not +in the project) is doubt and not rooted, so opentitan's DV force paths stay +warned exactly as before; the feature applies where the root is provable. +`lucisv check hw` byte-identical to master. Granted handshakes: `rename/ +warnings.rs` (H1, said once), `lucisv_server/src/state/sources.rs` (F3), +the message in `rename/mod.rs`. H2 (completion after `tb.`) deferred as +TODO §65.8. +