diff --git a/TODO.md b/TODO.md index dff6837..93a1328 100644 --- a/TODO.md +++ b/TODO.md @@ -6860,7 +6860,7 @@ tests (`server/tests/`), `crates/vlog_semantic/src/workspace/hierarchy.rs` only if `member_in` needs a case it lacks (a Handshake entry either way). Nothing else. -- [ ] the fixture sweep first, asserting today's answers, then flipped: +- [x] the fixture sweep first, asserting today's answers, then flipped: `definition`, `references` (from the declaration and from each use, `includeDeclaration` both ways), `hover`, `documentHighlight` over (a) a `bind` connection's bare name, (b) a `u_x.sig` tail from an @@ -6870,19 +6870,66 @@ Nothing else. — the single-file fallback, as today), (g) an unsaved buffer (`untitled:`), (h) the open buffer's own in-file use seen from a cross-file use -- [ ] the fix in both call sites; the §63.1 QA test renamed to say what it +- [x] the fix in both call sites; the §63.1 QA test renamed to say what it now asserts -- [ ] on the real opentitan tree (read-only): `references` on +- [x] on the real opentitan tree (read-only): `references` on `entropy_masking_req` from `aes.sv` lists `aes_bind.sv`; on `state_q` from `entropy_src_main_sm.sv` lists `entropy_src_core.sv`; the `nav`/`navqueue` harness rows within noise (the hierarchical lookup is one more map probe) -- [ ] QA: fixtures re-attacked (a generate-scoped net; a net shadowed by a +- [x] QA: fixtures re-attacked (a generate-scoped net; a net shadowed by a port of the same name in a *different* unit; a class member — must - stay on the connection answer), opentitan census, gates + stay on the connection answer), opentitan census, gates. Verdict: + rework needed — three findings in the closed-declaring-file repair's + handling of a stale-on-disk file (one new to this lane, two + pre-existing and general); see the feature README's QA log. +- [x] rework (dev, per the lead's ruling on QA findings 1–3): one fresh read + per closed file per request, threaded to the rendering step + (`file_view`'s cache is no longer on this path); a re-analysed closed + file's declaration reported at its live span; every index-time + closed-file span guarded with `hover::spells_exactly` (now `pub(crate)`) + and dropped rather than misrendered. `qa_finding_1/2/3` flipped to the + fixed answers and renamed, plus one attack on the guard itself. QA's + +25 % on a local-net request in a 40 000-line file accepted as-is, for + §64.2 to note in `docs/perf/README.md`. +- [x] QA re-check (same worktree): findings 1–3 re-derived by hand and + confirmed fixed (a use-only shift, a deleted declaring file, a UTF-8 + boundary, two independent closed files, an escaped port and an + escaped hierarchical net all attacked and held). **Finding 4, new**: + the `include_declaration` fallback's index-time span is rendered with + **no guard** when the file is *open* (only the closed path calls + `spells_exactly`) — reproduced with a renamed live buffer, a stale + 3-byte span lands on the first three characters of the live token + `sig2`. Verdict: rework needed again; see the feature README's QA log + for the fix suggestion. Gates green (4453 passed), opentitan + re-confirmed byte-identical, size 423 lines. +- [x] rework 2 (dev, finding 4): the `include_declaration` chain lifted into + `nav::declaration_site`; an open buffer's index-time fallback span is + emitted only if `hover::spells_exactly` holds against the live text, + else the declaration is omitted (the closed path keeps its single guard + in `closed_locations`). QA's finding-4 test flipped and renamed, plus a + control (an unsaved edit above the declaration still reports the live + line). Gates green through `tools/guard.sh`. +- [x] QA final (escalated, same worktree): the finding-4 test re-derived + by hand (a real unsaved rename; honest omission, tails unchanged) and + the control shown to come from the live path; the declaration-site + ladder attacked rung by rung — five `qa_final_*` tests (a failed live + lookup with the name still in place → emitted; a suffix of a longer + live name → dropped; off a UTF-8 boundary → dropped, no panic; + `includeDeclaration: false` on the closed rungs; one observation, a + different exact `sig` at the old bytes is reported, for the lead). + `nav.rs` 433 production lines, no unwrap/expect/panic, + `indexed_references` 71 lines (reported). Gates green (4459 passed), + opentitan rows re-confirmed read-only, checkout status identical. + Verdict: **pass**. ### 64.2 Closing -- [ ] `docs/perf/README.md` note if any harness number moved; topo row +- [x] `docs/perf/README.md` note if any harness number moved; topo row (`lucisv_server ──▶ vlog_semantic`: nav asks the hierarchical - surface); release 0.55.0 with assets verified + surface) — done 2026-09-12 (the perf entry records the +25 % on a + local-net `references` and the closed-file parse; the + `references-nav ──▶ workspace-index` row amended) +- [ ] release 0.55.0 with assets verified — owner's call; not run from the + `task_d8afe80f` session (a release chain never runs while a lane is + in flight, and the lane merges first) diff --git a/crates/lucisv_server/src/hover.rs b/crates/lucisv_server/src/hover.rs index 2b0bd0c..444f923 100644 --- a/crates/lucisv_server/src/hover.rs +++ b/crates/lucisv_server/src/hover.rs @@ -455,7 +455,7 @@ fn span_text(text: &str, span: TextRange) -> Option<&str> { /// to not continue an identifier turns that prefix/suffix match back into a /// miss, without needing anything more than the same "is this still a name /// character" question a lexer already answers for `$`, `_` and alnum. -fn spells_exactly(text: &str, span: TextRange, name: &str) -> bool { +pub(crate) fn spells_exactly(text: &str, span: TextRange, name: &str) -> bool { if span_text(text, span) != Some(name) { return false; } @@ -1313,6 +1313,45 @@ endmodule let _ = fs::remove_dir_all(&dir); } + /// TODO §64.1. The same live-span read for a declaration only a + /// **hierarchical** path can reach — a module's internal net, named from + /// another file as `u_leaf.sig`. + /// + /// `declaration_snippet` reaches it through `live_symbol` → + /// `nav::indexed_def_for_symbol`, which asked `WorkspaceIndex::member` + /// (the *connection* surface) until §64.1 and so mapped no live symbol + /// back to this `Def` at all: the card came out with its heading and no + /// fence, on a file that was open and perfectly readable. It now shows the + /// live line, which is the same guarantee the port above gets — and the + /// guard is untouched, so a buffer whose live text no longer declares the + /// name still prints nothing (asserted below). + #[test] + fn a_hierarchical_only_declaration_is_read_at_its_live_span_too() { + let top = + "module top;\n leaf u_leaf ();\n wire w;\n assign w = u_leaf.sig;\nendmodule\n"; + let saved = "module leaf;\n logic [7:0] sig;\nendmodule\n"; + let (dir, mut ws, uri) = included("livehier", &[("leaf.sv", saved), ("top.sv", top)]); + let leaf_uri = path_to_uri(&dir.join("leaf.sv")).expect("uri"); + let edited = + "// two lines\n// pushed it down\nmodule leaf;\n logic [15:0] sig;\nendmodule\n"; + ws.set_document(leaf_uri.clone(), edited.to_string()); + + let body = text_of(&hover(&ws, &uri, at(top, "u_leaf.sig") + 7).expect("hover")); + assert!( + body.contains("```systemverilog\n logic [15:0] sig;\n```"), + "the live line, width and all: got {body}" + ); + assert!(!body.contains("[7:0]"), "not the saved one: got {body}"); + + // The guard half, on the same shape: the net renamed away in the + // buffer leaves the heading and no fence. + ws.set_document(leaf_uri, "module leaf;\n logic [15:0] renamed;\nendmodule\n".to_string()); + let guarded = text_of(&hover(&ws, &uri, at(top, "u_leaf.sig") + 7).expect("hover")); + assert!(guarded.contains("— declared in"), "today's card, intact: got {guarded}"); + assert!(!guarded.contains("```"), "and no snippet at all: got {guarded}"); + let _ = fs::remove_dir_all(&dir); + } + #[test] fn a_stale_indexed_span_drops_the_snippet_rather_than_showing_the_wrong_line() { // The file changed on disk under a live index — a rescan the server has diff --git a/crates/lucisv_server/src/nav.rs b/crates/lucisv_server/src/nav.rs index a379d94..c227ffc 100644 --- a/crates/lucisv_server/src/nav.rs +++ b/crates/lucisv_server/src/nav.rs @@ -3,7 +3,7 @@ use lsp_types::{DocumentHighlight, DocumentHighlightKind, Location, Uri}; use vlog_parser::{LineIndex, TextRange}; -use vlog_semantic::{Def, Definition, ExternalTarget, Semantics, Symbol, SymbolId}; +use vlog_semantic::{Def, Definition, ExternalTarget, Semantics, Surface, Symbol, SymbolId}; use crate::convert::Positions; use crate::includes; @@ -145,6 +145,14 @@ pub fn references( /// file-scope unit, or a member its unit exports. Everything else is a name /// only this file can spell, and asking the workspace about it would read the /// whole project to learn nothing. +/// +/// A member is judged on the **hierarchical** surface, because that is the +/// surface a *use* can reach it by: a connection list may name only a module's +/// ports and parameters (IEEE 1800 §23.3), but a hierarchical path may name +/// anything it declares (§23.6), and `assign w = u_x.sig;` in another file is +/// a reference this request has to list. The connection answer is the first, +/// whole part of the hierarchical one (`hierarchy::member`), so nothing this +/// gate admitted before is judged differently now. fn leaves_this_file(ws: &Workspace, doc: &Document, offset: u32) -> bool { if doc.path.is_none() { // An `untitled:` buffer is in no index and has no path to hand over. @@ -160,15 +168,18 @@ fn leaves_this_file(ws: &Workspace, doc: &Document, offset: u32) -> bool { if !ws.index().units(&symbol.name).is_empty() { return true; } - // A member is reachable as `unit::name` or as `.name` in a connection - // list, so the unit that owns the declaring scope is what to ask about. + // A member is reachable as `unit::name`, as `.name` in a connection list + // or as the tail of a hierarchical path, so the unit that owns the + // declaring scope is what to ask about. let owner = doc .semantics .scope(symbol.scope) .and_then(|scope| scope.owner) .and_then(|owner| doc.semantics.symbol(owner)); match owner { - Some(owner) => !ws.index().member(&owner.name, &symbol.name).is_empty(), + Some(owner) => { + !ws.index().member_in(&owner.name, &symbol.name, Surface::Hierarchical).is_empty() + } None => false, } } @@ -223,30 +234,39 @@ pub(crate) fn indexed_def_for_symbol<'a>( symbol: &Symbol, ) -> Option<&'a Def> { let file = ws.index().file_id(doc.path.as_deref()?)?; - indexed_def_in_file(ws, doc, symbol, file) + indexed_def_in_file(ws, &doc.semantics, symbol, file) } -/// [`indexed_def_for_symbol`] with the document's own [`FileId`] already in -/// hand. +/// [`indexed_def_for_symbol`] with the file's own [`FileId`] already in hand, +/// against any [`Semantics`] for that file rather than an open document's. /// /// Split out for `indexed_references`, which asks about every reference in one /// buffer: the path lookup is a binary search whose comparisons are whole path -/// `cmp`s, and it answers the same thing for all of them. +/// `cmp`s, and it answers the same thing for all of them. Taking `Semantics` +/// rather than a `Document` is what lets [`declaring_file_uses`] ask the same +/// question of a file it has just re-analysed, so the two agree on what a live +/// symbol *is* by construction. +/// +/// A member is looked up on the **hierarchical** surface, for the reason +/// [`leaves_this_file`] gives. The connection records come first and whole +/// from that read, so the single-record rule (`defs.len() != 1`) and the kind +/// filter below keep exactly the meanings they had: a unit that declares one +/// name twice still yields one record, and a live symbol whose kind is not +/// that record's kind is still not that record. fn indexed_def_in_file<'a>( ws: &'a Workspace, - doc: &Document, + semantics: &Semantics, symbol: &Symbol, file: vlog_semantic::FileId, ) -> Option<&'a Def> { - let defs = if symbol.scope == doc.semantics.file_scope() { + let defs = if symbol.scope == semantics.file_scope() { ws.index().units(&symbol.name) } else { - let owner = doc - .semantics + let owner = semantics .scope(symbol.scope) .and_then(|scope| scope.owner) - .and_then(|owner| doc.semantics.symbol(owner))?; - ws.index().member(&owner.name, &symbol.name) + .and_then(|owner| semantics.symbol(owner))?; + ws.index().member_in(&owner.name, &symbol.name, Surface::Hierarchical) }; if defs.len() != 1 { return None; @@ -294,7 +314,7 @@ fn indexed_references( } let matches = match reference.resolved().and_then(|id| doc.semantics.symbol(id)) { Some(symbol) => { - file.and_then(|file| indexed_def_in_file(ws, doc, symbol, file)) + file.and_then(|file| indexed_def_in_file(ws, &doc.semantics, symbol, file)) == Some(&target.def) } None => match doc.external.get(vlog_semantic::ReferenceId(id as u32)) { @@ -311,30 +331,196 @@ fn indexed_references( } } - if include_declaration { - let span = ws - .document_for_path(&target.declaration_path) - .and_then(|doc| { - // Same name-keyed lookup `hover.rs::live_symbol` makes, for - // the same reason: only same-named declarations can be this - // one, and the order they come in is declaration order either - // way, so the first match is unchanged. - doc.semantics - .symbols_named(&target.name) - .filter_map(|id| doc.semantics.symbol(id)) - .find(|symbol| indexed_def_for_symbol(ws, doc, symbol) == Some(&target.def)) - .map(|symbol| symbol.name_span) - }) - .unwrap_or(target.declaration_span); - found.push((target.declaration_path, span)); + let declaring = declaring_file_uses(ws, &target); + if let Some(declaring) = &declaring { + found.extend(declaring.uses.iter().map(|span| (target.declaration_path.clone(), *span))); } - Some(locations(ws, found)) + if include_declaration { + if let Some(span) = declaration_site(ws, &target, declaring.as_ref()) { + found.push((target.declaration_path.clone(), span)); + } + } + + let closed = ClosedText { + name: &target.name, + read: declaring.as_ref().map(|d| (target.declaration_path.as_path(), d.text.as_str())), + }; + Some(locations(ws, found, Some(&closed))) +} + +/// Where to report `target`'s declaration, or `None` for an honest omission. +/// +/// An open buffer answers with its **live** symbol — the same name-keyed +/// lookup `hover.rs::live_symbol` makes, for the same reason: only same-named +/// declarations can be this one, and they come in declaration order either +/// way, so the first match is unchanged. When the buffer no longer declares +/// the name at all (an unsaved rename), the only span left is the index-time +/// one, and it means nothing against the live bytes unless it still spells +/// the name exactly there — so it is checked with the rule `closed_locations` +/// applies to every closed-file span, and dropped otherwise. This is the one +/// guard an open buffer's spans ever pay for: `locations` renders an open +/// document unguarded, and a stale span reaching it would land on a wrong +/// line — QA reproduced exactly that, a 3-byte `sig` on the first three +/// characters of a live `sig2` (finding 4). +/// +/// A closed file this request re-analysed knows where the declaration is +/// *now*; otherwise the index-time span is the last resort, and it is guarded +/// once, in `closed_locations`, against the text it is rendered in — never +/// here as well. +fn declaration_site( + ws: &Workspace, + target: &IndexedTarget, + declaring: Option<&DeclaringFile>, +) -> Option { + if let Some(doc) = ws.document_for_path(&target.declaration_path) { + let live = doc + .semantics + .symbols_named(&target.name) + .filter_map(|id| doc.semantics.symbol(id)) + .find(|symbol| indexed_def_for_symbol(ws, doc, symbol) == Some(&target.def)) + .map(|symbol| symbol.name_span); + return live.or_else(|| { + crate::hover::spells_exactly(&doc.text, target.declaration_span, &target.name) + .then_some(target.declaration_span) + }); + } + Some(declaring.and_then(|declaring| declaring.declaration).unwrap_or(target.declaration_span)) +} + +/// One closed declaring file, read and re-analysed once for this request. +struct DeclaringFile { + /// The bytes this request read, and the only bytes its spans mean + /// anything against. Handed to [`locations`] so the rendering step does + /// not read the same path a second time. + text: String, + /// Where the re-analysis found the declaration — its **live** span in + /// `text`, which is what `include_declaration` reports instead of the + /// index-time span. `None` when that file no longer declares the name. + declaration: Option, + /// Its own uses of the declaration, sorted and deduplicated. + uses: Vec, +} + +/// The declaring file's own uses of a **hierarchical-only** declaration, for +/// the case where no open buffer speaks for that file. +/// +/// The index records a `Local` reference posting only for a use whose +/// declaration is on the *connection* surface +/// (`vlog_semantic`'s `workspace/record.rs`, "the connection surface only"), +/// so [`vlog_semantic::WorkspaceIndex::references_to`] holds a +/// hierarchical-only declaration's **cross-file** sites and nothing else. +/// While its file is open, the loop above supplies its own uses from the live +/// buffer; closed, nobody does, and the answer would omit `assign … = sig;` +/// in the very file the declaration is in while looking complete. So that one +/// file — exactly one, never a project walk — is parsed and analysed here, on +/// exactly that shape. It is the same re-analysis a rename of the same name +/// already runs, which is why the postings were never widened. +/// +/// **The text comes from `Workspace::text_of`, not `Workspace::file_view`, and +/// is returned rather than dropped.** `file_view` is a cache, correctly so for +/// `hover`, which reads a closed file once per *generation* of it to print a +/// snippet and renders nothing else against that read. Here the read feeds a +/// span that a different step — [`locations`] — turns into a line and column, +/// and `locations` fetches its own text with `text_of`, which never caches. +/// Two reads of one path in one request can disagree (an external edit to a +/// closed file is none of the five events that drop a view), and a span from +/// the older bytes rendered against the newer ones lands on a wrong line. +/// QA reproduced exactly that (finding 1). So this path reads **once, fresh**, +/// and hands the same bytes on. +/// +/// `None` for every other target: a connection-surface declaration, whose +/// uses are posted, and any declaration whose file is open. +fn declaring_file_uses(ws: &Workspace, target: &IndexedTarget) -> Option { + // The cheapest of the three tests first: an open buffer has already been + // walked above, and this is one binary search over the open paths. + if ws.document_for_path(&target.declaration_path).is_some() { + return None; + } + if !hierarchical_only(ws, target) { + return None; + } + let text = ws.text_of(&target.declaration_path)?; + let file = ws.index().file_id(&target.declaration_path)?; + let (tree, _) = vlog_parser::parse_source_tolerant(&text); + let semantics = vlog_semantic::analyze(&tree, &text); + // The same logical identity `indexed_def_in_file` asserts everywhere else + // — path, owner, name and kind — so this file's re-analysis and the + // index cannot disagree about which declaration is meant. + let found = semantics.symbols_named(&target.name).find(|&id| { + semantics.symbol(id).and_then(|symbol| indexed_def_in_file(ws, &semantics, symbol, file)) + == Some(&target.def) + }); + // The text is returned even when the name is gone from this file, so the + // one-read-per-closed-file rule holds whatever the re-analysis concludes. + let Some(symbol_id) = found else { + return Some(DeclaringFile { text, declaration: None, uses: Vec::new() }); + }; + let declaration = semantics.symbol(symbol_id).map(|symbol| symbol.name_span); + let uses = occurrences(&semantics, symbol_id, false); + Some(DeclaringFile { text, declaration, uses }) +} + +/// Whether the index exports `target`'s declaration on the **hierarchical** +/// surface only — a module's net, variable or instance, an interface's +/// instance. +/// +/// Asked of the hierarchical-only table itself +/// ([`vlog_semantic::WorkspaceIndex::hierarchical_declarations`]) rather than +/// of `def.kind`: that table is exactly where `hierarchy::surface_of`'s +/// `Surface::Hierarchical` tag routes a record, so this answer cannot drift +/// from the rule. A `matches!(def.kind, Net | Var | Instance)` spelled here +/// would already be wrong for an interface's net, which is on its *connection* +/// surface, and would go stale the next time a kind moves. +/// +/// The walk probes each unit holding hierarchical-only members for this one +/// name and stops at the first hit. It is taken at most once per request, and +/// only once the declaring file is known to be closed. +fn hierarchical_only(ws: &Workspace, target: &IndexedTarget) -> bool { + ws.index().hierarchical_declarations(&target.name).any(|(_, held)| held == &target.def) +} + +/// What one request knows about the **closed** files it is rendering spans in. +/// +/// Two things, and both exist because a closed file's bytes are not pinned by +/// anything this server did: the name every span must still spell, and the +/// text this request already read for the declaring file. +struct ClosedText<'a> { + /// The name the target declaration declares. A closed file's span is a + /// *claim* about bytes nobody pinned — an index-time posting, or an + /// index-time declaration span — so it is emitted only if it still spells + /// this name exactly. + name: &'a str, + /// The declaring file and the bytes [`declaring_file_uses`] computed its + /// spans against, so those spans are rendered against the very text they + /// were parsed from and this request reads that path exactly once. + read: Option<(&'a std::path::Path, &'a str)>, +} + +impl ClosedText<'_> { + /// The text already read for `path`, if this request read it. + fn read_for(&self, path: &std::path::Path) -> Option<&str> { + self.read.filter(|(held, _)| *held == path).map(|(_, text)| text) + } } /// Convert all occurrences in one file with one text fetch and one line /// index, rather than repeating both operations for every location. -fn locations(ws: &Workspace, mut found: Vec<(std::path::PathBuf, TextRange)>) -> Vec { +/// +/// `closed` is `Some` for an indexed answer, whose spans about closed files +/// come from the index rather than from a buffer, and carries the agreement +/// guard those spans need: `hover.rs`'s principle, that a span which no +/// longer spells the name it was recorded for is **dropped**, never rendered +/// — an honest omission beats a wrong line. One slice compare plus two +/// character tests per closed-file location, and none at all for an open +/// buffer's, whose spans came from the very text they are rendered against. +/// `None` is for a caller whose spans are all freshly walked over current +/// texts and name no single declaration (the refactor-walk oracle in tests). +fn locations( + ws: &Workspace, + mut found: Vec<(std::path::PathBuf, TextRange)>, + closed: Option<&ClosedText>, +) -> Vec { found.retain(|(_, span)| !span.is_empty()); found.sort_by(|(a_path, a_span), (b_path, b_span)| { (a_path, a_span.start, a_span.end).cmp(&(b_path, b_span.start, b_span.end)) @@ -358,21 +544,48 @@ fn locations(ws: &Workspace, mut found: Vec<(std::path::PathBuf, TextRange)>) -> .iter() .map(|(_, span)| Location { uri: uri.clone(), range: walker.range(*span) }), ); - } else if let Some(text) = ws.text_of(path) { - let index = LineIndex::new(&text); - let positions = Positions::new(&text, &index); - let mut walker = positions.walker(); - out.extend( - found[start..end] - .iter() - .map(|(_, span)| Location { uri: uri.clone(), range: walker.range(*span) }), - ); + } else { + out.extend(closed_locations(ws, &uri, path, &found[start..end], closed)); } start = end; } out } +/// One **closed** file's spans, rendered against one read of its text. +/// +/// The text is the read this request already took for the declaring file, or +/// one fresh `text_of` — never both, and never a cache, so no span here is +/// paired with bytes other than the ones it was computed or checked against. +/// +/// Each span is then guarded: an index-time posting, or an index-time +/// declaration span, is a claim about bytes nobody pinned, and it is emitted +/// only if it still spells the target's name exactly in this very text. +/// Otherwise it is dropped — `hover.rs`'s rule, that a stale record can only +/// ever omit an answer and never point at a wrong line. +fn closed_locations( + ws: &Workspace, + uri: &Uri, + path: &std::path::Path, + spans: &[(std::path::PathBuf, TextRange)], + closed: Option<&ClosedText>, +) -> Vec { + let held = closed.and_then(|closed| closed.read_for(path)); + let fetched = if held.is_none() { ws.text_of(path) } else { None }; + let Some(text) = held.or(fetched.as_deref()) else { return Vec::new() }; + let index = LineIndex::new(text); + let positions = Positions::new(text, &index); + let mut walker = positions.walker(); + spans + .iter() + .filter(|(_, span)| match closed { + Some(closed) => crate::hover::spells_exactly(text, *span, closed.name), + None => true, + }) + .map(|(_, span)| Location { uri: uri.clone(), range: walker.range(*span) }) + .collect() +} + /// The file's own answer: what `Semantics` alone knows about this symbol. fn in_file_references( ws: &Workspace, @@ -509,7 +722,7 @@ mod tests { use super::*; use crate::perf::mean; use std::fs; - use std::path::PathBuf; + use std::path::{Path, PathBuf}; use std::str::FromStr; fn document(text: &str) -> (Workspace, Uri) { @@ -893,7 +1106,9 @@ endmodule let path = dir.join("top.sv"); let walked = vlog_refactor::find_references(&ws.sources(), &path, offset, true) .expect("the existing refactor walk answers"); - let walked = locations(&ws, walked); + // The oracle's spans are walked over the current texts of the very + // files it read, so there is no index-time claim to guard. + let walked = locations(&ws, walked, None); assert_eq!(indexed, walked); let _ = fs::remove_dir_all(&dir); @@ -933,7 +1148,7 @@ endmodule let walked_module = vlog_refactor::find_references(&ws.sources(), &dir.join("w.sv"), module_offset, true) .expect("the walk answers"); - assert_eq!(indexed_module, locations(&ws, walked_module)); + assert_eq!(indexed_module, locations(&ws, walked_module, None)); assert_eq!(indexed_module.len(), 3, "declaration + 2 live instantiations, not the member"); // The package member `W`: its declaration and the one qualified use, @@ -943,7 +1158,7 @@ endmodule let walked_member = vlog_refactor::find_references(&ws.sources(), &dir.join("p.sv"), member_offset, true) .expect("the walk answers"); - assert_eq!(indexed_member, locations(&ws, walked_member)); + assert_eq!(indexed_member, locations(&ws, walked_member, None)); assert_eq!(indexed_member.len(), 2, "declaration + the one qualified use, not the module"); let _ = fs::remove_dir_all(&dir); @@ -1252,14 +1467,35 @@ endmodule let _ = fs::remove_dir_all(&dir); } + /// The gate, asserted directly. Since §64.1 a module's net **is** a name + /// another file can spell (`u_m.a`), so the gate admits it — that + /// assertion flipped, and the two truths this test was written to protect + /// did not: + /// + /// * `other.sv`'s own `a` is a different signal and is never listed; + /// * a name the index holds **nowhere** still never asks the workspace — + /// a generate-block-scoped net, whose scope is the block's and not the + /// module's, and an undeclared `b`, which is no symbol at all. + /// + /// And the cost argument is unchanged, which is why the gate is still + /// worth having: admitting a name buys two map probes plus the + /// name-prefiltered pass over the *open* buffers, and never a project + /// read. What the gate saves is those probes for every name that could + /// not have left the file anyway. #[test] fn a_local_signal_never_asks_the_workspace() { - // The gate, asserted directly: a name the index does not hold cannot - // be named from another file, so `references` must not walk one. The - // functional half is below; this is the half that would otherwise - // only show up as a slow editor. let dir = temp_dir("xrefs_local"); - let text = "module m;\n wire a;\n assign a = 1;\n assign b = a;\nendmodule\n"; + let text = "\ +module m; + wire a; + assign a = 1; + assign b = a; + if (1) begin : g + wire gen_only; + assign gen_only = a; + end +endmodule +"; fs::write(dir.join("m.sv"), text).expect("write"); fs::write(dir.join("other.sv"), "module other;\n wire a;\nendmodule\n").expect("write"); let mut ws = Workspace::default(); @@ -1268,15 +1504,34 @@ endmodule ws.set_document(uri.clone(), text.to_string()); let doc = ws.document(&uri).expect("open"); - assert!(!leaves_this_file(&ws, doc, at(text, "wire a") + 5), "a net is not indexed"); - assert!(leaves_this_file(&ws, doc, at(text, "module m") + 7), "but the module is"); + assert!( + leaves_this_file(&ws, doc, at(text, "wire a") + 5), + "a module's net is on its hierarchical surface, so `u_m.a` could name it" + ); + assert!(leaves_this_file(&ws, doc, at(text, "module m") + 7), "and the module is a unit"); + assert!( + !leaves_this_file(&ws, doc, at(text, "wire gen_only") + 5), + "but a generate-block-scoped net is on neither surface" + ); + assert!( + !leaves_this_file(&ws, doc, at(text, "assign b") + 7), + "and an undeclared name is no symbol at all" + ); let found = references(&ws, &uri, at(text, "wire a") + 5, true); assert_eq!( places(&found), - vec![("m.sv".to_string(), 1), ("m.sv".to_string(), 2), ("m.sv".to_string(), 3)], + vec![ + ("m.sv".to_string(), 1), + ("m.sv".to_string(), 2), + ("m.sv".to_string(), 3), + ("m.sv".to_string(), 6), + ], "this file only — `other.sv`'s own `a` is a different signal" ); + // No file was read to answer that: `other.sv` holds a same-named net + // and was never opened, which `held_views` is the witness for. + assert!(ws.held_views().is_empty(), "no project read: {:?}", ws.held_views()); let _ = fs::remove_dir_all(&dir); } @@ -1320,33 +1575,28 @@ endmodule let _ = fs::remove_dir_all(&dir); } - /// TODO §63.1 QA. A `bind`'s connection expressions elaborate in the - /// target's scope (IEEE 1800 §23.11), and the index now records that - /// reach on the target's hierarchical surface (`resolve::in_bind_target`, - /// `FACTS_FORMAT` 20). `definition` from the bind file's expression half - /// does jump to the target's net (never to `aes_reseed_if`'s `.port` half - /// of the same name) — the overlay's `Resolution::ExternalCandidate` - /// carries the real `Def` straight through, unremapped. + /// TODO §63.1 QA, closed by §64.1. A `bind`'s connection expressions + /// elaborate in the target's scope (IEEE 1800 §23.11), and the index + /// records that reach on the target's hierarchical surface + /// (`resolve::in_bind_target`, `FACTS_FORMAT` 20). `definition` from the + /// bind file's expression half jumps to the target's net, never to + /// `aes_reseed_if`'s `.port` half of the same name — the overlay's + /// `Resolution::ExternalCandidate` carries the real `Def` straight + /// through, unremapped. /// - /// `references`, in both directions, does **not** yet see it, and the gap - /// is not new to this lane: `leaves_this_file` and `indexed_def_in_file` - /// (`nav.rs`, above) look a declaration's owner up with - /// `WorkspaceIndex::member`, which answers only the **connection** - /// surface (ports and parameters). A net, a variable or an instance lives - /// on the **hierarchical** surface only (`workspace/hierarchy.rs`, - /// 2026-09-05) and so is invisible to both functions — `leaves_this_file` - /// judges such a declaration incapable of being referenced elsewhere and - /// falls back to the single-file answer, and `indexed_def_in_file` maps a - /// *live* symbol back to its persisted `Def` the same wrong way, so even - /// an open buffer's own in-file use of such a name fails to re-identify - /// itself once the request has gone through the external-candidate path. - /// A plain (non-`bind`) hierarchical tail reaches the same dead end for - /// the same reason — this is not a bind-specific hole. Filed as a - /// standalone finding; out of §63.1's stated files - /// (`crates/lucisv_server/src/nav.rs` is not in its file list) and not - /// introduced by this lane. + /// `references` now sees it from **both** directions. It could not until + /// `leaves_this_file` and `indexed_def_in_file` stopped asking + /// `WorkspaceIndex::member` — the *connection* surface, ports and + /// parameters — about a declaration that lives on the **hierarchical** + /// surface only (`workspace/hierarchy.rs`, 2026-09-05). The two locations + /// this test was written to demand are the ones it asserts now: the bind + /// file's expression half seen from the declaration, and `aes.sv`'s own + /// `assign idle_o = entropy_masking_req;` seen from the bind file. The + /// same fix serves a plain (non-`bind`) tail, which was never a + /// bind-specific hole — see + /// `a_hierarchical_nets_references_reach_every_file_that_names_it`. #[test] - fn a_binds_connection_expression_is_reachable_by_definition_not_yet_by_references() { + fn a_binds_connection_expression_is_reachable_by_definition_and_by_references() { let dir = temp_dir("xrefs_bind_wire"); let aes = "module aes (input logic clk_i, output logic idle_o);\n \ logic entropy_masking_req;\n assign idle_o = entropy_masking_req;\nendmodule\n"; @@ -1364,8 +1614,8 @@ endmodule let bind_uri = path_to_uri(&dir.join("aes_bind.sv")).expect("uri"); ws.set_document(bind_uri.clone(), bind_file.to_string()); - // Works: the expression half's `definition` is the target's net, not - // the checker's `.port` of the same name. + // The expression half's `definition` is the target's net, not the + // checker's `.port` of the same name. let expr_offset = at(bind_file, "(entropy_masking_req)") + 1; let locations = definition(&ws, &bind_uri, expr_offset); assert_eq!( @@ -1374,26 +1624,24 @@ endmodule "the expression half names `aes`'s net: {locations:?}" ); - // Known gap, pinned rather than silently regressed further: from the - // declaration, `references` falls back to the single-file answer - // (`leaves_this_file` above) and never sees the bind file at all. + // Both directions answer one set: the declaration, `aes.sv`'s own use + // of it, and the bind file's expression half. + let everywhere = vec![ + ("aes.sv".to_string(), 1), + ("aes.sv".to_string(), 2), + ("aes_bind.sv".to_string(), 2), + ]; let found = references(&ws, &aes_uri, at(aes, "entropy_masking_req"), true); - assert_eq!( - places(&found), - vec![("aes.sv".to_string(), 1), ("aes.sv".to_string(), 2)], - "the bind file's expression half is invisible from here today: {found:?}" - ); - - // And from the bind file's own expression half, `references` finds - // the declaration and its own occurrence, but not `aes.sv`'s in-file - // use two lines below the declaration — `indexed_def_in_file` cannot - // map that live local reference back to its persisted `Def` either. + assert_eq!(places(&found), everywhere, "from the declaration: {found:?}"); let from_bind = references(&ws, &bind_uri, expr_offset, true); - assert_eq!( - places(&from_bind), - vec![("aes.sv".to_string(), 1), ("aes_bind.sv".to_string(), 2)], - "aes.sv's own in-file use is missing too: {from_bind:?}" - ); + assert_eq!(places(&from_bind), everywhere, "from the bind file: {from_bind:?}"); + + // And with `aes.sv` closed, which is how a DV engineer reads a bind + // file: its own in-file use comes from the one re-analysis + // `declaring_file_uses` runs, not from a posting that does not exist. + ws.close_document(&aes_uri); + let closed = references(&ws, &bind_uri, expr_offset, true); + assert_eq!(places(&closed), everywhere, "with the declaring file shut: {closed:?}"); let _ = fs::remove_dir_all(&dir); } @@ -1761,6 +2009,1203 @@ endmodule let _ = fs::remove_dir_all(&dir); } + // ------------------------------------------------------------------ + // TODO §64.1 — the hierarchical member surface + // ------------------------------------------------------------------ + + /// `leaf` declares a net only a hierarchical path can reach, plus a port + /// and a parameter that a connection list can, so one fixture answers both + /// "did the widening land" and "did the connection answers move". + const LEAF: &str = "\ +module leaf #(parameter int W = 1) (input logic clk_i); + logic sig; + assign sig = clk_i; +endmodule +"; + /// One level up: `u_leaf.sig`. + const SINGLE: &str = "\ +module single; + leaf u_leaf (.clk_i(1'b0)); + wire v; + assign v = u_leaf.sig; +endmodule +"; + /// Two levels up, through `mid`'s own instance. + const MID: &str = "\ +module mid; + leaf u_leaf (.clk_i(1'b0)); +endmodule +"; + const TWO_LEVEL: &str = "\ +module top; + mid u_mid (); + wire w; + assign w = u_mid.u_leaf.sig; +endmodule +"; + + /// The four-file hierarchical workspace, with the named files opened as + /// buffers holding exactly their on-disk text. + fn hierarchical(tag: &str, open: &[&str]) -> (PathBuf, Workspace) { + let dir = temp_dir(tag); + for (name, text) in + [("leaf.sv", LEAF), ("single.sv", SINGLE), ("mid.sv", MID), ("top.sv", TWO_LEVEL)] + { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + for name in open { + let path = dir.join(name); + let uri = path_to_uri(&path).expect("uri"); + let text = fs::read_to_string(&path).expect("read"); + ws.set_document(uri, text); + } + (dir, ws) + } + + fn uri_in(dir: &Path, name: &str) -> Uri { + path_to_uri(&dir.join(name)).expect("uri") + } + + /// The byte offset of `leaf`'s net declaration, its one-level tail and its + /// two-level tail — the three positions the sweep below asks from. + fn sig_positions() -> (u32, u32, u32) { + ( + at(LEAF, "logic sig") + 6, + at(SINGLE, "u_leaf.sig;") + 7, + at(TWO_LEVEL, "u_mid.u_leaf.sig") + 13, + ) + } + + /// The declaration, its own in-file use, and both cross-file tails. + fn every_place_naming_sig() -> Vec<(String, u32)> { + vec![ + ("leaf.sv".to_string(), 1), + ("leaf.sv".to_string(), 2), + ("single.sv".to_string(), 3), + ("top.sv".to_string(), 3), + ] + } + + /// Cases (b) and (c): asked **from the declaration** of a net that only a + /// hierarchical path can reach, with `includeDeclaration` both ways. + #[test] + fn a_hierarchical_nets_references_reach_every_file_that_names_it() { + let (dir, ws) = hierarchical("hier_from_decl", &["leaf.sv", "single.sv", "top.sv"]); + let leaf_uri = uri_in(&dir, "leaf.sv"); + let (decl, _, _) = sig_positions(); + + assert_eq!( + places(&references(&ws, &leaf_uri, decl, true)), + every_place_naming_sig(), + "the declaration, its own use, the one-level tail and the two-level one" + ); + assert_eq!( + places(&references(&ws, &leaf_uri, decl, false)), + every_place_naming_sig()[1..].to_vec(), + "`includeDeclaration: false` drops the declaration and nothing else" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// Case (h): asked **from a tail**, the answer must include the declaring + /// buffer's own in-file use — the half `indexed_def_in_file` could not + /// re-identify. Both tails answer the same set, from one and from two + /// levels up. + #[test] + fn a_hierarchical_nets_references_from_a_tail_include_the_declaring_files_own_uses() { + let (dir, ws) = hierarchical("hier_from_tail", &["leaf.sv", "single.sv", "top.sv"]); + let single_uri = uri_in(&dir, "single.sv"); + let top_uri = uri_in(&dir, "top.sv"); + let (_, one, two) = sig_positions(); + + assert_eq!( + places(&references(&ws, &single_uri, one, true)), + every_place_naming_sig(), + "from `u_leaf.sig`" + ); + assert_eq!( + places(&references(&ws, &top_uri, two, true)), + every_place_naming_sig(), + "from `u_mid.u_leaf.sig` — the same declaration, so the same set" + ); + assert_eq!( + places(&references(&ws, &single_uri, one, false)), + every_place_naming_sig()[1..].to_vec(), + "and the declaration is the only thing `includeDeclaration` drops" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// Case (i). The index posts no `Local` fact for a hierarchical-only + /// declaration, so with `leaf.sv` **closed** neither the postings nor the + /// open-buffer overlay can supply its own `assign sig = clk_i;`. An answer + /// that silently omitted it would be worse than the single-file fallback, + /// because it looks complete. + #[test] + fn a_hierarchical_nets_own_uses_are_found_with_its_declaring_file_closed() { + let (dir, ws) = hierarchical("hier_closed", &["single.sv"]); + let single_uri = uri_in(&dir, "single.sv"); + let (_, one, _) = sig_positions(); + + assert_eq!( + places(&references(&ws, &single_uri, one, true)), + every_place_naming_sig(), + "`leaf.sv` is closed and `top.sv` too, and both are still listed" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// `definition` and `documentHighlight` over the same three positions. + /// Neither reads the reachability gate — `definition` goes through the + /// overlay and `documentHighlight` is a *document* answer by contract + /// (`docs/features/references-nav/README.md`, 2026-08-28) — so both are + /// pinned here to stay exactly what they were. + #[test] + fn definition_and_document_highlight_over_a_hierarchical_tail_are_unchanged() { + let (dir, ws) = hierarchical("hier_def_highlight", &["leaf.sv", "single.sv", "top.sv"]); + let leaf_uri = uri_in(&dir, "leaf.sv"); + let single_uri = uri_in(&dir, "single.sv"); + let top_uri = uri_in(&dir, "top.sv"); + let (decl, one, two) = sig_positions(); + + let declaration = vec![("leaf.sv".to_string(), 1)]; + assert_eq!(places(&definition(&ws, &leaf_uri, decl)), declaration, "itself"); + assert_eq!(places(&definition(&ws, &single_uri, one)), declaration, "from one level up"); + assert_eq!(places(&definition(&ws, &top_uri, two)), declaration, "from two"); + + let lines = |uri: &Uri, offset: u32| { + let doc = ws.document(uri).expect("open"); + document_highlights(doc, offset) + .map(|found| found.iter().map(|h| h.range.start.line).collect::>()) + }; + assert_eq!(lines(&leaf_uri, decl), Some(vec![1, 2]), "this file's two spans"); + assert_eq!(lines(&single_uri, one), Some(vec![3]), "the tail, in its own file only"); + assert_eq!(lines(&top_uri, two), Some(vec![3]), "same, two levels up"); + let _ = fs::remove_dir_all(&dir); + } + + /// Case (d). The connection surface is a *prefix* of the hierarchical one + /// (`hierarchy::member` returns the connection records whole whenever they + /// are non-empty), so a port and a parameter of the very same module must + /// answer exactly what they answered before the widening. + #[test] + fn a_port_and_a_parameter_of_the_same_unit_keep_their_connection_answers() { + let (dir, ws) = hierarchical("hier_port", &["leaf.sv", "single.sv", "top.sv"]); + let leaf_uri = uri_in(&dir, "leaf.sv"); + + assert_eq!( + places(&references(&ws, &leaf_uri, at(LEAF, "clk_i)"), true)), + vec![ + ("leaf.sv".to_string(), 0), + ("leaf.sv".to_string(), 2), + ("mid.sv".to_string(), 1), + ("single.sv".to_string(), 1), + ], + "the port: its declaration, its own use, and both `.clk_i(...)` connections" + ); + assert_eq!( + places(&references(&ws, &leaf_uri, at(LEAF, "W = 1"), true)), + vec![("leaf.sv".to_string(), 0)], + "the parameter: declared, never named again anywhere" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// A **class** member stays on the connection answer — the attack case + /// §49's QA asked for, re-asked here because the widening is one call + /// away from it. A class has one surface, so `member_in` cannot move it. + #[test] + fn a_class_member_keeps_its_connection_answer() { + let dir = temp_dir("hier_class"); + let pkg = "\ +package cp; + class c; + int fld; + function void f(); + fld = 1; + endfunction + endclass +endpackage +"; + let user = "module cuser;\n cp::c h;\n initial h.fld = 2;\nendmodule\n"; + for (name, text) in [("cp.sv", pkg), ("cuser.sv", user)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let pkg_uri = uri_in(&dir, "cp.sv"); + ws.set_document(pkg_uri.clone(), pkg.to_string()); + let user_uri = uri_in(&dir, "cuser.sv"); + ws.set_document(user_uri, user.to_string()); + + assert_eq!( + places(&references(&ws, &pkg_uri, at(pkg, "int fld") + 4, true)), + vec![("cp.sv".to_string(), 2), ("cp.sv".to_string(), 4), ("cuser.sv".to_string(), 2)], + "the field, its use in the method, and the handle access in the other file" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// A net declared inside a **generate block** is on neither surface: its + /// scope is the block's, not the module's (`hierarchical-tail`, "a unit's + /// members are the symbols of its own scope"). So the gate still says no + /// and the answer is still the honest single-file one — the same refusal + /// a rename gives `u_x.g.sig`. + #[test] + fn a_generate_block_scoped_net_still_never_asks_the_workspace() { + let dir = temp_dir("hier_generate"); + let leaf = "\ +module gleaf; + if (1) begin : g + wire gsig; + assign gsig = 1'b0; + end +endmodule +"; + let user = + "module guser;\n gleaf u_g ();\n wire z;\n assign z = u_g.g.gsig;\nendmodule\n"; + for (name, text) in [("gleaf.sv", leaf), ("guser.sv", user)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let leaf_uri = uri_in(&dir, "gleaf.sv"); + ws.set_document(leaf_uri.clone(), leaf.to_string()); + let user_uri = uri_in(&dir, "guser.sv"); + ws.set_document(user_uri, user.to_string()); + + let decl = at(leaf, "wire gsig") + 5; + let doc = ws.document(&leaf_uri).expect("open"); + assert!(!leaves_this_file(&ws, doc, decl), "the index exports it on no surface"); + assert_eq!( + places(&references(&ws, &leaf_uri, decl, true)), + vec![("gleaf.sv".to_string(), 2), ("gleaf.sv".to_string(), 3)], + "this file only, and `u_g.g.gsig` is left to the editor" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// A net in one unit and a **port of the same name in another** — each + /// keeps its own answer. The widening is per unit, so `sb`'s net gaining + /// its cross-file tail must not pull `sa`'s port along, and `sa`'s port + /// must answer exactly what it did. + #[test] + fn a_net_and_a_like_named_port_in_another_unit_keep_their_answers_apart() { + let dir = temp_dir("hier_shadow"); + let with_port = + "module sa (input logic shared);\n wire x;\n assign x = shared;\nendmodule\n"; + let with_net = "module sb;\n logic shared;\n assign shared = 1'b0;\nendmodule\n"; + let user = "\ +module suse; + sa u_a (.shared(1'b1)); + sb u_b (); + wire q; + assign q = u_b.shared; +endmodule +"; + for (name, text) in [("sa.sv", with_port), ("sb.sv", with_net), ("suse.sv", user)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let port_uri = uri_in(&dir, "sa.sv"); + ws.set_document(port_uri.clone(), with_port.to_string()); + let net_uri = uri_in(&dir, "sb.sv"); + ws.set_document(net_uri.clone(), with_net.to_string()); + let user_uri = uri_in(&dir, "suse.sv"); + ws.set_document(user_uri, user.to_string()); + + assert_eq!( + places(&references(&ws, &port_uri, at(with_port, "logic shared") + 6, true)), + vec![("sa.sv".to_string(), 0), ("sa.sv".to_string(), 2), ("suse.sv".to_string(), 1)], + "`sa`'s port: unchanged, and never `sb`'s net" + ); + assert_eq!( + places(&references(&ws, &net_uri, at(with_net, "logic shared") + 6, true)), + vec![("sb.sv".to_string(), 1), ("sb.sv".to_string(), 2), ("suse.sv".to_string(), 4)], + "`sb`'s net: its own file plus the `u_b.shared` tail, and never `sa`'s connection" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// Case (f) as it actually exists. `vlog_semantic` records **one symbol + /// per name per scope** — a second declaration of a name already declared + /// becomes a `Duplicate` and a reference to the first — so "a name that is + /// both a parameter and an internal net of one unit" is one symbol, one + /// index record, and one surface: the first declaration's. The + /// single-record rule (`defs.len() != 1`) therefore never sees two records + /// for one `(unit, name)` from one file, and both cursor positions answer + /// the same complete set. Asserted rather than argued, because the + /// alternative — two records, the port silently winning — is what §64.1 + /// asked to be ruled out. + #[test] + fn a_name_declared_twice_in_one_unit_is_one_symbol_and_one_record() { + let dir = temp_dir("hier_redeclared"); + let both = "\ +module pboth #(parameter int q = 1) (); + wire q; + assign q = 1'b0; +endmodule +"; + let user = + "module puse;\n pboth #(.q(2)) u_p ();\n wire s;\n assign s = u_p.q;\nendmodule\n"; + for (name, text) in [("pboth.sv", both), ("puse.sv", user)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let both_uri = uri_in(&dir, "pboth.sv"); + ws.set_document(both_uri.clone(), both.to_string()); + let user_uri = uri_in(&dir, "puse.sv"); + ws.set_document(user_uri, user.to_string()); + + let everywhere = vec![ + ("pboth.sv".to_string(), 0), + ("pboth.sv".to_string(), 1), + ("pboth.sv".to_string(), 2), + ("puse.sv".to_string(), 1), + ("puse.sv".to_string(), 3), + ]; + assert_eq!( + places(&references(&ws, &both_uri, at(both, "int q") + 4, true)), + everywhere, + "from the parameter" + ); + assert_eq!( + places(&references(&ws, &both_uri, at(both, "wire q") + 5, true)), + everywhere, + "and from the redeclaration, which is a use of it" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// Two files declaring one module, each with a net of one name: the gate + /// now admits the net, and the **single-record rule** refuses it — two + /// `Def`s for `(dleaf, dsig)` is exactly the ambiguity `defs.len() != 1` + /// has always declined. So the answer is the in-file one, as before, and + /// the tail that cannot be placed answers nothing rather than guessing. + #[test] + fn two_modules_of_one_name_keep_a_hierarchical_net_on_the_in_file_answer() { + let dir = temp_dir("hier_two_modules"); + let leaf = "module dleaf;\n logic dsig;\n assign dsig = 1'b0;\nendmodule\n"; + let user = "module duse;\n dleaf u_d ();\n wire r;\n assign r = u_d.dsig;\nendmodule\n"; + for (name, text) in [("a.sv", leaf), ("b.sv", leaf), ("duse.sv", user)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let a_uri = uri_in(&dir, "a.sv"); + ws.set_document(a_uri.clone(), leaf.to_string()); + let user_uri = uri_in(&dir, "duse.sv"); + ws.set_document(user_uri.clone(), user.to_string()); + + assert_eq!( + places(&references(&ws, &a_uri, at(leaf, "logic dsig") + 6, true)), + vec![("a.sv".to_string(), 1), ("a.sv".to_string(), 2)], + "`a.sv`'s own answer — `b.sv`'s `dsig` is another declaration" + ); + assert_eq!( + places(&references(&ws, &user_uri, at(user, "u_d.dsig") + 4, true)), + Vec::new(), + "the tail is ambiguous between two `dleaf`s, so nothing is claimed" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// Case (g). An `untitled:` buffer is in no index and has no path to hand + /// over, so the gate declines before any surface question is asked — the + /// widening cannot reach it. + #[test] + fn an_untitled_buffer_never_asks_the_workspace() { + let untitled = Uri::from_str("untitled:Untitled-1").expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(untitled.clone(), LEAF.to_string()); + let doc = ws.document(&untitled).expect("open"); + let (decl, _, _) = sig_positions(); + + assert!(!leaves_this_file(&ws, doc, decl), "no path, no index entry"); + let found = references(&ws, &untitled, decl, true); + assert_eq!( + found.iter().map(|l| l.range.start.line).collect::>(), + vec![1, 2], + "its own two spans, reported against the `untitled:` uri" + ); + assert!(found.iter().all(|l| l.uri == untitled)); + } + + // ------------------------------------------------------------------ + // TODO §64.1 — QA attacks (task-d8afe80f) + // ------------------------------------------------------------------ + + /// The disk edit shared by the three findings below: three comment lines + /// pushed in above `leaf`'s net declaration, keeping the net's name, kind + /// and owner so every identity check downstream still finds it. + const LEAF_MOVED: &str = "\ +module leaf #(parameter int W = 1) (input logic clk_i); + // one + // two + // three + logic sig; + assign sig = clk_i; +endmodule +"; + + /// Every `leaf.sv` line in an answer, in the order it came — the three + /// stale-file findings all turn on which lines of the *closed declaring + /// file* a request reports. + fn leaf_lines(found: &[Location]) -> Vec { + found + .iter() + .filter(|l| l.uri.as_str().ends_with("leaf.sv")) + .map(|l| l.range.start.line) + .collect() + } + + /// **FINDING 1**, QA's scenario, now fixed. `declaring_file_uses` used to + /// read the declaring file through `ws.file_view` — a *cache*, dropped + /// only on `set_document`/`close_document`/`update_one`/ + /// `rebuild_index_with`/`begin_widen`, none of which an external edit to a + /// closed file is — while `locations` renders every closed-file span + /// against `Workspace::text_of`, which never caches. Two reads of one path + /// in one request, free to disagree, and the older offsets landed on the + /// newer bytes: QA saw `leaf.sv`'s "own use" reported at line `3` + /// (`// two`). The path now reads **once, fresh**, with `text_of`, and + /// hands those same bytes to `locations`. + /// + /// Worked out from `LEAF_MOVED` above, which is `LEAF` with three comment + /// lines pushed in under the header: line `4` is ` logic sig;` and line + /// `5` is ` assign sig = clk_i;`. Both come from the re-analysis of the + /// fresh text — the declaration too, because a file this request just + /// re-analysed knows where the declaration is *now* and the index-time + /// span is only the last resort. + #[test] + fn qa_finding_1_a_disk_edited_closed_declaring_file_reports_its_live_spans() { + let (dir, ws) = hierarchical("hier_stale_disk_1", &["top.sv"]); + let top_uri = uri_in(&dir, "top.sv"); + let (_, _, two) = sig_positions(); + + // One request first, which is what used to prime the view cache: + // `leaf.sv` is closed, so this walks `declaring_file_uses`. + let before = references(&ws, &top_uri, two, true); + assert_eq!(places(&before), every_place_naming_sig(), "sanity: correct before any edit"); + + fs::write(dir.join("leaf.sv"), LEAF_MOVED).expect("write"); + + let after = references(&ws, &top_uri, two, true); + assert_eq!( + leaf_lines(&after), + vec![4, 5], + "the declaration and its own use, both at their live lines" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// **FINDING 2**, now fixed, and the half that needed no primed cache at + /// all. The `include_declaration` tail used to fall straight to + /// `target.declaration_span` — a span fixed at the last index rebuild — + /// for a closed file, and `locations` rendered it against a fresh read + /// with no check that the two still agreed: QA saw the declaration at + /// line `1` (`// one`). It is now taken from the same re-analysis that + /// supplies the uses, so a single fresh request answers `4` and `5` from + /// `LEAF_MOVED`'s own text. + #[test] + fn qa_finding_2_one_fresh_request_reports_the_live_declaration_line() { + let (dir, ws) = hierarchical("hier_stale_disk_2", &["top.sv"]); + let top_uri = uri_in(&dir, "top.sv"); + let (_, _, two) = sig_positions(); + + fs::write(dir.join("leaf.sv"), LEAF_MOVED).expect("write"); + + let after = references(&ws, &top_uri, two, true); + assert_eq!( + leaf_lines(&after), + vec![4, 5], + "declaration 4, own use 5 — nothing on this path caches" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// **FINDING 3**, the pre-existing half, now an honest omission. Asked + /// from `single.sv`'s `.clk_i(1'b0)` connection, the target is a **port**: + /// on the connection surface, its uses already posted, so no re-analysis + /// of the declaring file runs and every `leaf.sv` span in the answer is an + /// index-time claim about bytes nobody pinned. The guard now decides each + /// one against the text it is about to be rendered in: + /// + /// * the declaration, `clk_i` in the module header — `LEAF_MOVED` inserts + /// its three lines *below* the header, so line `0` is untouched, the + /// recorded span still spells `clk_i`, and it is reported (correctly, at + /// `0`); + /// * the posted use, `clk_i` in `assign sig = clk_i;` — that line is now + /// line `5` and the recorded span points into `// two`, which does not + /// spell `clk_i`, so it is **dropped**. + /// + /// QA saw `[0, 3]`: the `3` was the wrong line this guard exists to + /// refuse. The right answer is not to invent `5` either — nothing + /// re-analysed this file, so the request does not know `5`; it knows only + /// that what it held is no longer true. + #[test] + fn qa_finding_3_a_stale_index_span_in_a_closed_file_is_dropped_not_misreported() { + let (dir, ws) = hierarchical("hier_stale_disk_3", &["single.sv"]); + let single_uri = uri_in(&dir, "single.sv"); + let clk_offset = at(SINGLE, ".clk_i(1'b0)") + 1; + + // Sanity: before the edit, both `leaf.sv` spans are true and reported. + assert_eq!( + leaf_lines(&references(&ws, &single_uri, clk_offset, true)), + vec![0, 2], + "the header's port and its own use, before any edit" + ); + + fs::write(dir.join("leaf.sv"), LEAF_MOVED).expect("write"); + + let after = references(&ws, &single_uri, clk_offset, true); + assert_eq!( + leaf_lines(&after), + vec![0], + "the unmoved header still spells `clk_i`; the moved use is omitted, not misreported" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// The guard itself, attacked the way `hover.rs`'s own QA attacked it: a + /// disk edit that leaves a recorded span still *covering* the name, as a + /// **prefix** of a longer identifier. + /// + /// `leafp` declares one port and uses it nowhere, so the only `leafp.sv` + /// span in the answer is the index-time declaration span — `clk_i` in the + /// header. The edit renames the port to `clk_i2` and changes nothing + /// before it, so that span's bytes still read exactly `clk_i` and a + /// length-and-content check alone would emit it, under the old name, on a + /// line that now declares something else. `spells_exactly` requires the + /// character immediately outside the span not to continue an identifier, + /// which is what turns this prefix match back into a miss. + #[test] + fn qa_a_stale_span_that_now_spells_a_longer_name_is_dropped() { + let dir = temp_dir("hier_stale_prefix"); + let leaf = "module leafp (input logic clk_i);\nendmodule\n"; + let user = "module userp;\n leafp u_p (.clk_i(1'b0));\nendmodule\n"; + for (name, text) in [("leafp.sv", leaf), ("userp.sv", user)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let user_uri = uri_in(&dir, "userp.sv"); + ws.set_document(user_uri.clone(), user.to_string()); + let offset = at(user, ".clk_i(1'b0)") + 1; + + assert_eq!( + places(&references(&ws, &user_uri, offset, true)), + vec![("leafp.sv".to_string(), 0), ("userp.sv".to_string(), 1)], + "sanity: the declaration and the connection, before the edit" + ); + + // The same header, one longer name, nothing before it moved. + fs::write(dir.join("leafp.sv"), "module leafp (input logic clk_i2);\nendmodule\n") + .expect("write"); + + assert_eq!( + places(&references(&ws, &user_uri, offset, true)), + vec![("userp.sv".to_string(), 1)], + "the prefix match is refused: the connection only, no invented declaration" + ); + let _ = fs::remove_dir_all(&dir); + } + + // ------------------------------------------------------------------ + // Re-check round, 2026-09-12 — the rework's guard and one-read invariant + // ------------------------------------------------------------------ + + /// Re-check item 2(a): a disk edit that moves only the **use**, leaving + /// the declaration's own line untouched. The target is hierarchical-only, + /// so `declaring_file_uses` always re-analyses the whole file regardless + /// of what moved — both spans must come out live and correct, not just + /// the one that happened to move. + #[test] + fn qa_recheck_a_disk_edit_that_moves_only_the_use_is_still_fully_reanalysed() { + let (dir, ws) = hierarchical("hier_recheck_use_only", &["top.sv"]); + let top_uri = uri_in(&dir, "top.sv"); + let (_, _, two) = sig_positions(); + + let moved_use_only = "\ +module leaf #(parameter int W = 1) (input logic clk_i); + logic sig; + // one + // two + assign sig = clk_i; +endmodule +"; + fs::write(dir.join("leaf.sv"), moved_use_only).expect("write"); + + let after = references(&ws, &top_uri, two, true); + assert_eq!( + leaf_lines(&after), + vec![1, 4], + "declaration unmoved at 1, its own use moved to 4 — both live and correct" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// Re-check item 2(b): the closed declaring file is **deleted** after the + /// index was built, with no rescan. `declaring_file_uses`'s `text_of` + /// read fails (`?` short-circuits to `None`), and the `include_declaration` + /// fallback's own `ws.text_of` read in `closed_locations` fails the same + /// way — no text, no panic, an honest omission of *that file* rather than + /// a guess. `single.sv` is untouched and perfectly readable, so its own + /// posted tail still answers normally — only `leaf.sv` itself vanishes + /// from the set. + #[test] + fn qa_recheck_a_deleted_closed_declaring_file_is_an_honest_omission_not_a_panic() { + let (dir, ws) = hierarchical("hier_recheck_deleted", &["top.sv"]); + let top_uri = uri_in(&dir, "top.sv"); + let (_, _, two) = sig_positions(); + + fs::remove_file(dir.join("leaf.sv")).expect("delete"); + + let after = references(&ws, &top_uri, two, true); + assert!( + leaf_lines(&after).is_empty(), + "leaf.sv cannot be read at all, so it is omitted, not guessed at: {:?}", + leaf_lines(&after) + ); + assert_eq!( + places(&after), + vec![("single.sv".to_string(), 3), ("top.sv".to_string(), 3)], + "single.sv (untouched, still readable) and the live top.sv buffer, no panic, no crash" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// Re-check item 2(c): a stale index-time span that, reinterpreted + /// against the edited disk text, no longer lands on a `char` boundary at + /// all — a multi-byte character straddling the exact byte offset the + /// index recorded. `spells_exactly`/`span_text` use `str::get`, which + /// answers `None` off a boundary rather than panicking; this is the + /// direct attack on that, on the **port** shape (finding 3's case, an + /// index-time span with no re-analysis to save it). + #[test] + fn qa_recheck_a_stale_span_off_a_utf8_boundary_does_not_panic() { + let (dir, ws) = hierarchical("hier_recheck_utf8", &["single.sv"]); + let single_uri = uri_in(&dir, "single.sv"); + let clk_offset = at(SINGLE, ".clk_i(1'b0)") + 1; + + // The old, index-time byte offset of `clk_i`'s own use in `LEAF` + // (inside `assign sig = clk_i;`, the second occurrence). + let old_use_offset = LEAF.rfind("clk_i").expect("second occurrence"); + + // A new `leaf.sv` in which that same raw byte offset lands on the + // second byte of a 4-byte emoji — never a `char` boundary. + let mut edited = "a".repeat(old_use_offset.saturating_sub(1)); + edited.push('🎉'); + edited.push_str("\nmodule leaf (input logic clk_i2);\nendmodule\n"); + assert!( + !edited.is_char_boundary(old_use_offset), + "test bug: byte {old_use_offset} must land mid-character" + ); + fs::write(dir.join("leaf.sv"), &edited).expect("write"); + + // Must not panic. The header itself changed too (`clk_i` -> `clk_i2` + // and garbage before it), so nothing about `leaf.sv` need survive — + // the only requirement is that answering does not crash the server. + let after = references(&ws, &single_uri, clk_offset, true); + assert!(leaf_lines(&after).is_empty(), "garbage text spells nothing: {:?}", after); + let _ = fs::remove_dir_all(&dir); + } + + /// Re-check item 2(d): **two** closed files in one answer — `leaf.sv` + /// (the declaring file, fully re-analysed) and `single.sv` (a posted + /// `External` cross-file site, never re-analysed, guarded the same way a + /// port's own use is) — asked from a third, open file. An edit to one + /// must not affect the other's answer, and each is rendered against its + /// own, independently-read text. + #[test] + fn qa_recheck_two_closed_files_in_one_answer_are_independent() { + let (dir, ws) = hierarchical("hier_recheck_two_closed", &["top.sv"]); + let top_uri = uri_in(&dir, "top.sv"); + let (_, _, two) = sig_positions(); + + assert_eq!( + places(&references(&ws, &top_uri, two, true)), + every_place_naming_sig(), + "leaf.sv re-analysed, single.sv posted-only, top.sv live — before any edit" + ); + + // Move `single.sv`'s own tail down by two lines; `leaf.sv` untouched. + let single_moved = "\ +module single; + // one + // two + leaf u_leaf (.clk_i(1'b0)); + wire v; + assign v = u_leaf.sig; +endmodule +"; + fs::write(dir.join("single.sv"), single_moved).expect("write"); + + let after = references(&ws, &top_uri, two, true); + assert_eq!( + leaf_lines(&after), + vec![1, 2], + "leaf.sv is untouched and unaffected by single.sv's own edit" + ); + let single_lines: Vec = after + .iter() + .filter(|l| l.uri.as_str().ends_with("single.sv")) + .map(|l| l.range.start.line) + .collect(); + // `single.sv`'s own tail is a posted `External` site, never + // re-analysed (only the *declaring* file is) — so it is exactly the + // finding-3 shape one file over: the moved span no longer spells + // `sig` and is dropped, an honest omission, not misreported at its + // old line (3) nor invented at its new one (5). + assert!( + single_lines.is_empty(), + "single.sv's own tail moved and is not re-analysed, so it is dropped: {single_lines:?}" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// QA finding 4 (re-check round), fixed. The direction the closed-file + /// guard did not cover: an **open** buffer whose live text no longer + /// declares the name. `leaf.sv` is open with `sig` renamed away + /// (unsaved); the request comes from `single.sv`'s tail, which still + /// resolves to the original `Def`. `declaring_file_uses` declines (the + /// file is open) and the live lookup finds nothing (no symbol is named + /// `sig` in the buffer any more), so the only span left is the + /// index-time one — and `locations` renders an open document with no + /// guard. Before the fix that stale 3-byte span was reported at line 1, + /// columns 8..11: a strict *prefix* of the live token `sig2` (8..12), the + /// very shape `spells_exactly` refuses for a closed file + /// (`qa_a_stale_span_that_now_spells_a_longer_name_is_dropped`). + /// `declaration_site` now asks the same question of the live buffer and + /// omits the declaration: `leaf.sv` does not appear at all, and every + /// other location is unchanged. + #[test] + fn qa_recheck_a_renamed_open_buffers_stale_declaration_is_omitted_not_misreported() { + let (dir, ws) = hierarchical("hier_recheck_open_stale", &["single.sv", "leaf.sv"]); + let single_uri = uri_in(&dir, "single.sv"); + let leaf_uri = uri_in(&dir, "leaf.sv"); + let (_, one, _) = sig_positions(); + + // Sanity: with the buffer holding its on-disk text, the answer is + // complete, declaration included. + assert_eq!( + places(&references(&ws, &single_uri, one, true)), + every_place_naming_sig(), + "before the rename: the full answer" + ); + + // Rename `sig` away in the live, unsaved `leaf.sv` buffer. The index + // still holds the original `Def` for `sig`, at the same offsets. + let renamed = "\ +module leaf #(parameter int W = 1) (input logic clk_i); + logic sig2; + assign sig2 = clk_i; +endmodule +"; + let mut ws = ws; + ws.set_document(leaf_uri, renamed.to_string()); + + // Asked from `single.sv`'s tail, which still names the original + // declaration by its persisted `Def`. + let after = references(&ws, &single_uri, one, true); + assert_eq!( + places(&after), + vec![("single.sv".to_string(), 3), ("top.sv".to_string(), 3)], + "leaf.sv is honestly omitted — no stale prefix of `sig2` — and the two tails stay: {after:?}" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// The control for the guard above: an open buffer with an unsaved edit + /// **above** the declaration, which still spells `sig` and has only + /// moved. The live-symbol path answers first (`indexed_def_for_symbol` + /// matches logically — path, owner, name, kind — not positionally), so + /// the declaration is reported at its live line and the guard never + /// fires. The index-time span, rendered blind, would have pointed into + /// the header line; dropped by the guard, it would be missing. Either + /// way the live line `3` at `sig`'s own columns is the only right answer, + /// and it is the one the request gives with `includeDeclaration` on and + /// not without it. + #[test] + fn an_open_buffer_edited_above_its_declaration_reports_the_live_declaration_line() { + let (dir, ws) = hierarchical("hier_open_edit_above", &["single.sv", "leaf.sv"]); + let single_uri = uri_in(&dir, "single.sv"); + let leaf_uri = uri_in(&dir, "leaf.sv"); + let (_, one, _) = sig_positions(); + + let edited = "\ +// pushed +// down +module leaf #(parameter int W = 1) (input logic clk_i); + logic sig; + assign sig = clk_i; +endmodule +"; + let mut ws = ws; + ws.set_document(leaf_uri, edited.to_string()); + + let with = references(&ws, &single_uri, one, true); + let leaf_spans: Vec<(u32, u32, u32)> = with + .iter() + .filter(|l| l.uri.as_str().ends_with("leaf.sv")) + .map(|l| (l.range.start.line, l.range.start.character, l.range.end.character)) + .collect(); + assert_eq!( + leaf_spans, + vec![(3, 8, 11), (4, 9, 12)], + "the live declaration and the live use, both shifted down two lines: {with:?}" + ); + assert_eq!( + places(&with), + vec![ + ("leaf.sv".to_string(), 3), + ("leaf.sv".to_string(), 4), + ("single.sv".to_string(), 3), + ("top.sv".to_string(), 3), + ], + "and nothing else moved" + ); + + let without = references(&ws, &single_uri, one, false); + assert_eq!( + places(&without), + vec![ + ("leaf.sv".to_string(), 4), + ("single.sv".to_string(), 3), + ("top.sv".to_string(), 3), + ], + "line 3 is the declaration: it goes when includeDeclaration is off" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// Re-check (coordinator's follow-up): an escaped port name + /// (`\my-clk `), reachable before §64.1 too (connection surface). The + /// declaration is an index-time span like any port's, so it goes through + /// `closed_locations`'s `spells_exactly` guard — which must recognise the + /// escaped name (backslash and all) rather than silently dropping every + /// closed-file location for it. + #[test] + fn qa_recheck_an_escaped_port_name_survives_the_guard() { + let dir = temp_dir("qa_escaped_port"); + let sub = "module sub (input logic \\my-clk );\nendmodule\n"; + let top = "module top;\n sub u (.\\my-clk (1'b0));\nendmodule\n"; + for (name, text) in [("sub.sv", sub), ("top.sv", top)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let top_uri = uri_in(&dir, "top.sv"); + ws.set_document(top_uri.clone(), top.to_string()); + let offset = at(top, "\\my-clk (1'b0)") + 1; + + let found = references(&ws, &top_uri, offset, true); + assert_eq!( + places(&found), + vec![("sub.sv".to_string(), 0), ("top.sv".to_string(), 1)], + "sub.sv's declaration must survive the guard, escaped name and all" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// Re-check: the hierarchical twin of the escaped-name attack above — an + /// escaped **net**, hierarchical-only, closed declaring file. This one + /// goes through the *re-analysis* path (`declaring_file_uses`) rather + /// than the guard directly, so it is really testing whether the parser + /// and `Semantics::symbols_named` round-trip an escaped name at all + /// under re-analysis. + #[test] + fn qa_recheck_an_escaped_net_survives_the_closed_file_reanalysis() { + let dir = temp_dir("qa_escaped_net"); + let leaf = "module eleaf;\n logic \\my-sig ;\n assign \\my-sig = 1'b0;\nendmodule\n"; + let top = "module etop;\n eleaf u_leaf ();\n wire w;\n assign w = u_leaf.\\my-sig ;\nendmodule\n"; + for (name, text) in [("eleaf.sv", leaf), ("etop.sv", top)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let top_uri = uri_in(&dir, "etop.sv"); + ws.set_document(top_uri.clone(), top.to_string()); + let offset = at(top, "u_leaf.\\my-sig") + 8; + + let found = references(&ws, &top_uri, offset, true); + assert_eq!( + places(&found), + vec![("eleaf.sv".to_string(), 1), ("eleaf.sv".to_string(), 2), ("etop.sv".to_string(), 3)], + "eleaf.sv's declaration and its own use, escaped name and all, via the closed-file repair" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// Case (a), sharpened: an **indexed generate array**, not just a named + /// block. `u_g.gen[0].gsig` is still on neither surface — the array + /// index changes how many instances of the scope exist, not which scope + /// `gsig` belongs to — so the honest single-file fallback must hold here + /// too. + #[test] + fn qa_a_generate_for_arrays_scoped_net_still_never_asks_the_workspace() { + let dir = temp_dir("qa_generate_for"); + let leaf = "\ +module gfleaf; + for (genvar i = 0; i < 2; i++) begin : gen + wire gsig; + assign gsig = 1'b0; + end +endmodule +"; + let user = + "module gfuser;\n gfleaf u_g ();\n wire z;\n assign z = u_g.gen[0].gsig;\nendmodule\n"; + for (name, text) in [("gfleaf.sv", leaf), ("gfuser.sv", user)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let leaf_uri = uri_in(&dir, "gfleaf.sv"); + ws.set_document(leaf_uri.clone(), leaf.to_string()); + let user_uri = uri_in(&dir, "gfuser.sv"); + ws.set_document(user_uri, user.to_string()); + + let decl = at(leaf, "wire gsig") + 5; + let doc = ws.document(&leaf_uri).expect("open"); + assert!(!leaves_this_file(&ws, doc, decl), "an indexed generate scope is on no surface"); + assert_eq!( + places(&references(&ws, &leaf_uri, decl, true)), + vec![("gfleaf.sv".to_string(), 2), ("gfleaf.sv".to_string(), 3)], + "this file only; `u_g.gen[0].gsig` is left to the editor" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// An interface's signal, reached through a virtual-interface handle + /// (`vif.data`) from another file. Interface members are on the + /// **connection** surface already (`hierarchy.rs`, 2026-09-01), so + /// `member_in(…, Hierarchical)` answers exactly what `member` always did + /// — confirmed, not merely assumed unchanged. + #[test] + fn qa_an_interface_signal_through_a_virtual_interface_handle_is_unchanged() { + let dir = temp_dir("qa_interface"); + let iface = "interface bus_if;\n logic data;\nendinterface\n"; + let agent = "\ +class agent; + virtual bus_if vif; + function void f(); + vif.data = 1; + endfunction +endclass +"; + for (name, text) in [("bus_if.sv", iface), ("agent.sv", agent)] { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let iface_uri = uri_in(&dir, "bus_if.sv"); + ws.set_document(iface_uri.clone(), iface.to_string()); + let agent_uri = uri_in(&dir, "agent.sv"); + ws.set_document(agent_uri, agent.to_string()); + + assert_eq!( + places(&references(&ws, &iface_uri, at(iface, "logic data") + 6, true)), + vec![("agent.sv".to_string(), 3), ("bus_if.sv".to_string(), 1)], + "the interface signal, from the declaration" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// Case (k). `documentHighlight` from the declaration and from the bind + /// file's connection: a *document* answer by contract regardless of + /// cross-file reachability (`references-nav`, 2026-08-28) — same-file + /// only, non-empty, unchanged by this lane. + #[test] + fn qa_document_highlight_over_the_bind_fixture_stays_same_file_only() { + let dir = temp_dir("qa_bind_highlight"); + let aes = "module aes (input logic clk_i, output logic idle_o);\n \ + logic entropy_masking_req;\n assign idle_o = entropy_masking_req;\nendmodule\n"; + let chk = "module aes_reseed_if (input logic entropy_masking_req);\nendmodule\n"; + let bind_file = "module aes_bind;\n bind aes aes_reseed_if u_aes_reseed_if (\n \ + .entropy_masking_req(entropy_masking_req)\n );\nendmodule\n"; + for (name, text) in [("aes.sv", aes), ("aes_reseed_if.sv", chk), ("aes_bind.sv", bind_file)] + { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let aes_uri = uri_in(&dir, "aes.sv"); + ws.set_document(aes_uri.clone(), aes.to_string()); + let bind_uri = uri_in(&dir, "aes_bind.sv"); + ws.set_document(bind_uri.clone(), bind_file.to_string()); + + let decl_doc = ws.document(&aes_uri).expect("open"); + let decl_highlights = document_highlights(decl_doc, at(aes, "entropy_masking_req") + 4) + .expect("highlights from the declaration"); + assert_eq!( + decl_highlights.iter().map(|h| h.range.start.line).collect::>(), + vec![1, 2], + "aes.sv's own two lines, never the bind file" + ); + + let bind_doc = ws.document(&bind_uri).expect("open"); + let expr_offset = at(bind_file, "(entropy_masking_req)") + 1; + let bind_highlights = + document_highlights(bind_doc, expr_offset).expect("highlights from the bind file"); + assert_eq!( + bind_highlights.iter().map(|h| h.range.start.line).collect::>(), + vec![2], + "the bind file's own connection line only, never aes.sv" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// Case (e), completed. `leaf.sv` closed, `top.sv` open: references from + /// the tail already include `leaf.sv`'s own in-file uses (the + /// closed-file repair). Then `leaf.sv` is **opened** with an unsaved + /// edit above the declaration: the answer must reflect the live, + /// shifted spans, not the ones the closed-file repair (or the index) + /// last computed. + #[test] + fn qa_reopening_the_declaring_file_with_an_unsaved_edit_gives_live_spans() { + let (dir, mut ws) = hierarchical("hier_reopen_live", &["top.sv"]); + let top_uri = uri_in(&dir, "top.sv"); + let (_, _, two) = sig_positions(); + + let closed = references(&ws, &top_uri, two, true); + assert_eq!( + places(&closed), + every_place_naming_sig(), + "closed: the repair supplies leaf.sv" + ); + + // Open `leaf.sv` with two lines pushed in above the declaration, + // never saved. + let leaf_uri = uri_in(&dir, "leaf.sv"); + let edited = "\ +// pushed +// down +module leaf #(parameter int W = 1) (input logic clk_i); + logic sig; + assign sig = clk_i; +endmodule +"; + ws.set_document(leaf_uri, edited.to_string()); + + let live = references(&ws, &top_uri, two, true); + let leaf_lines: Vec = live + .iter() + .filter(|l| l.uri.as_str().ends_with("leaf.sv")) + .map(|l| l.range.start.line) + .collect(); + assert_eq!(leaf_lines, vec![3, 4], "the live, shifted spans — not the closed-file ones"); + let _ = fs::remove_dir_all(&dir); + } + + /// Oracle helper: `vlog_refactor::find_references`'s answer, as + /// `(file name, line)` — the same shape `places` gives `references`'s + /// own answer, so the two can be compared directly. + fn oracle_places( + files: &[(PathBuf, String)], + file: &Path, + offset: u32, + include_declaration: bool, + ) -> Vec<(String, u32)> { + let found = vlog_refactor::find_references(files, file, offset, include_declaration) + .expect("the oracle resolves it"); + let mut out: Vec<(String, u32)> = found + .iter() + .map(|(path, span)| { + let text = + files.iter().find(|(p, _)| p == path).map(|(_, t)| t.as_str()).unwrap_or(""); + let line = text[..span.start as usize].matches('\n').count() as u32; + (path.file_name().unwrap().to_string_lossy().to_string(), line) + }) + .collect(); + out.sort(); + out + } + + /// Equivalence with the whole-scope oracle (charter item 4): the plain + /// hierarchical tail. `references` must equal what a rename would edit, + /// now that the indexed path answers this shape at all. + #[test] + fn qa_references_agrees_with_the_rename_oracle_over_a_plain_tail() { + let (dir, ws) = hierarchical("hier_oracle_tail", &["leaf.sv", "single.sv", "top.sv"]); + let leaf_uri = uri_in(&dir, "leaf.sv"); + let (decl, _, _) = sig_positions(); + + let mut got = places(&references(&ws, &leaf_uri, decl, true)); + got.sort(); + + let files: Vec<(PathBuf, String)> = + [("leaf.sv", LEAF), ("single.sv", SINGLE), ("mid.sv", MID), ("top.sv", TWO_LEVEL)] + .into_iter() + .map(|(name, text)| (dir.join(name), text.to_string())) + .collect(); + let oracle = oracle_places(&files, &dir.join("leaf.sv"), decl, true); + + assert_eq!(got, oracle, "references must equal what a rename would edit"); + let _ = fs::remove_dir_all(&dir); + } + + /// Equivalence with the oracle over the **bind** fixture. + #[test] + fn qa_references_agrees_with_the_rename_oracle_over_the_bind_fixture() { + let dir = temp_dir("qa_oracle_bind"); + let aes = "module aes (input logic clk_i, output logic idle_o);\n \ + logic entropy_masking_req;\n assign idle_o = entropy_masking_req;\nendmodule\n"; + let chk = "module aes_reseed_if (input logic entropy_masking_req);\nendmodule\n"; + let bind_file = "module aes_bind;\n bind aes aes_reseed_if u_aes_reseed_if (\n \ + .entropy_masking_req(entropy_masking_req)\n );\nendmodule\n"; + for (name, text) in [("aes.sv", aes), ("aes_reseed_if.sv", chk), ("aes_bind.sv", bind_file)] + { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![dir.clone()]); + let aes_uri = uri_in(&dir, "aes.sv"); + ws.set_document(aes_uri.clone(), aes.to_string()); + let bind_uri = uri_in(&dir, "aes_bind.sv"); + ws.set_document(bind_uri, bind_file.to_string()); + + let offset = at(aes, "entropy_masking_req"); + let mut got = places(&references(&ws, &aes_uri, offset, true)); + got.sort(); + + let files: Vec<(PathBuf, String)> = + [("aes.sv", aes), ("aes_reseed_if.sv", chk), ("aes_bind.sv", bind_file)] + .into_iter() + .map(|(name, text)| (dir.join(name), text.to_string())) + .collect(); + let oracle = oracle_places(&files, &dir.join("aes.sv"), offset, true); + + assert_eq!(got, oracle, "references must equal what a rename would edit, bind included"); + let _ = fs::remove_dir_all(&dir); + } + + /// Case (h) + equivalence: the **instance name** itself. Does the + /// instance segment of a hierarchical tail count as a reference, and + /// does `references` answer the same set a rename would edit? + #[test] + fn qa_an_instance_names_references_agree_with_the_rename_oracle() { + let (dir, ws) = + hierarchical("hier_oracle_instance", &["leaf.sv", "single.sv", "mid.sv", "top.sv"]); + let single_uri = uri_in(&dir, "single.sv"); + let offset = at(SINGLE, "u_leaf"); + + let mut got = places(&references(&ws, &single_uri, offset, true)); + got.sort(); + + let files: Vec<(PathBuf, String)> = + [("leaf.sv", LEAF), ("single.sv", SINGLE), ("mid.sv", MID), ("top.sv", TWO_LEVEL)] + .into_iter() + .map(|(name, text)| (dir.join(name), text.to_string())) + .collect(); + let oracle = oracle_places(&files, &dir.join("single.sv"), offset, true); + + assert_eq!(got, oracle, "the instance name: same set a rename would edit"); + let _ = fs::remove_dir_all(&dir); + } + #[test] fn a_package_import_resolves_into_the_packages_file() { let dir = temp_dir("pkg"); @@ -1782,4 +3227,183 @@ endmodule let _ = fs::remove_dir_all(&dir); } + + // ------------------------------------------------------------------ + // Final QA (2026-09-12): the declaration-site ladder, rung by rung. + // Rung (a) is the control test above; the prefix half of rung (c) is the + // flipped finding-4 test; rungs (e) and (f) with the declaration on are + // `qa_finding_2` and `qa_finding_3`. + // ------------------------------------------------------------------ + + /// The `leaf.sv` spans of an answer as `(line, start col, end col)`. + fn leaf_spans(found: &[Location]) -> Vec<(u32, u32, u32)> { + found + .iter() + .filter(|l| l.uri.as_str().ends_with("leaf.sv")) + .map(|l| (l.range.start.line, l.range.start.character, l.range.end.character)) + .collect() + } + + /// Rung (b): an open buffer whose live lookup fails while the index-time + /// span still spells the name at the same bytes. `logic sig;` becomes + /// `wire sig;` — one byte longer keyword, one space fewer, so nothing + /// moves — and `logic` is `Var` where `wire` is `Net` (`bind/decl.rs`), + /// so `indexed_def_in_file`'s kind filter rejects the live symbol and the + /// live path finds nothing. The fallback span reads exactly `sig` at line + /// 1, columns 8..11, and is emitted; the buffer's own use resolves to the + /// rejected live symbol and is (consistently) not listed; and with + /// `includeDeclaration: false` the fallback is never consulted. + #[test] + fn qa_final_b_a_failed_live_lookup_with_the_name_still_in_place_emits_the_index_span() { + let (dir, mut ws) = hierarchical("hier_final_b", &["single.sv", "leaf.sv"]); + let single_uri = uri_in(&dir, "single.sv"); + let (_, one, _) = sig_positions(); + let rekinded = "\ +module leaf #(parameter int W = 1) (input logic clk_i); + wire sig; + assign sig = clk_i; +endmodule +"; + assert_eq!(at(rekinded, "sig;"), at(LEAF, "sig;"), "the edit moves nothing"); + ws.set_document(uri_in(&dir, "leaf.sv"), rekinded.to_string()); + + let with = references(&ws, &single_uri, one, true); + assert_eq!( + leaf_spans(&with), + vec![(1, 8, 11)], + "the index-time span, still `sig`: {with:?}" + ); + assert_eq!( + places(&with), + vec![ + ("leaf.sv".to_string(), 1), + ("single.sv".to_string(), 3), + ("top.sv".to_string(), 3) + ], + "nothing else changes" + ); + let without = references(&ws, &single_uri, one, false); + assert_eq!( + places(&without), + vec![("single.sv".to_string(), 3), ("top.sv".to_string(), 3)], + "includeDeclaration: false never reaches the fallback" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// Rung (c), the suffix half: `logic sig;` becomes `wire _sig;`, so bytes + /// 8..11 of line 1 still read `sig` but the byte before them is `_`, a + /// name character. No live symbol is named `sig`, the fallback is a + /// suffix of `_sig`, and `spells_exactly` refuses it: `leaf.sv` is absent. + #[test] + fn qa_final_c_an_index_span_now_a_suffix_of_a_longer_live_name_is_dropped() { + let (dir, mut ws) = hierarchical("hier_final_c", &["single.sv", "leaf.sv"]); + let single_uri = uri_in(&dir, "single.sv"); + let (_, one, _) = sig_positions(); + let suffixed = "\ +module leaf #(parameter int W = 1) (input logic clk_i); + wire _sig; + assign _sig = clk_i; +endmodule +"; + let o = at(LEAF, "sig;") as usize; + assert_eq!(&suffixed[o..o + 3], "sig", "the old bytes still read `sig`"); + assert_eq!(&suffixed[o - 1..o], "_", "as the tail of `_sig`"); + ws.set_document(uri_in(&dir, "leaf.sv"), suffixed.to_string()); + + let after = references(&ws, &single_uri, one, true); + assert_eq!( + places(&after), + vec![("single.sv".to_string(), 3), ("top.sv".to_string(), 3)], + "a suffix match is a miss: {after:?}" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// Rung (d): the index-time span starts inside a multi-byte character of + /// the live text. Line 1 becomes a comment of two four-byte emoji placed + /// so the span's start byte is the last byte of the first one, and the + /// declaration below is renamed away so the live path finds nothing. + /// `spells_exactly` slices with `str::get`, which is `None` off a + /// boundary: no panic, and `leaf.sv` is omitted. + #[test] + fn qa_final_d_an_open_buffers_span_off_a_utf8_boundary_is_dropped_without_a_panic() { + let (dir, mut ws) = hierarchical("hier_final_d", &["single.sv", "leaf.sv"]); + let single_uri = uri_in(&dir, "single.sv"); + let (_, one, _) = sig_positions(); + let emoji = "\ +module leaf #(parameter int W = 1) (input logic clk_i); + // \u{1F642}\u{1F642} + logic sig2; + assign sig2 = clk_i; +endmodule +"; + let o = at(LEAF, "sig;") as usize; + assert!(!emoji.is_char_boundary(o), "the span starts mid-character"); + ws.set_document(uri_in(&dir, "leaf.sv"), emoji.to_string()); + + let after = references(&ws, &single_uri, one, true); + assert_eq!( + places(&after), + vec![("single.sv".to_string(), 3), ("top.sv".to_string(), 3)], + "off a boundary is a miss, not a panic: {after:?}" + ); + let _ = fs::remove_dir_all(&dir); + } + + /// Rung (g) on the closed rungs: `includeDeclaration: false` emits no + /// declaration whether the closed declaring file is re-analysed (rung (e), + /// a hierarchical-only net, its live declaration known) or postings-only + /// (rung (f), a port, its index-time span guarded once) — before and + /// after a disk edit that moves the declaration. The open rungs are pinned + /// the same way by the control test and by rung (b). + #[test] + fn qa_final_g_include_declaration_false_emits_no_declaration_on_the_closed_rungs() { + let (dir, ws) = hierarchical("hier_final_g", &["single.sv"]); + let single_uri = uri_in(&dir, "single.sv"); + let (_, sig, _) = sig_positions(); + let clk = at(SINGLE, ".clk_i(1'b0)") + 1; + + assert_eq!(leaf_lines(&references(&ws, &single_uri, sig, false)), vec![2]); + assert_eq!(leaf_lines(&references(&ws, &single_uri, clk, false)), vec![2]); + + fs::write(dir.join("leaf.sv"), LEAF_MOVED).expect("write"); + // (e): the re-analysis knows the live declaration (4) and the live + // use (5); without the declaration only the use is left. + assert_eq!(leaf_lines(&references(&ws, &single_uri, sig, true)), vec![4, 5]); + assert_eq!(leaf_lines(&references(&ws, &single_uri, sig, false)), vec![5]); + // (f): the header's port survives its guard (0); the moved use does + // not; without the declaration nothing in `leaf.sv` is left. + assert_eq!(leaf_lines(&references(&ws, &single_uri, clk, true)), vec![0]); + assert_eq!(leaf_lines(&references(&ws, &single_uri, clk, false)), Vec::::new()); + let _ = fs::remove_dir_all(&dir); + } + + /// Observation, pinned rather than argued: the fallback is a textual + /// claim, on an open buffer exactly as on a closed file. A buffer whose + /// declaration is gone but where a *different* `sig` — here an undeclared + /// gate output — now sits at the very same bytes is reported as the + /// declaration. The token is a whole, exact `sig`, so `spells_exactly` + /// is right to accept it; whether that occurrence *is* the declaration is + /// a question the guard was never meant to answer, and the lead's to rule + /// on. + #[test] + fn qa_final_observation_a_different_exact_sig_at_the_old_bytes_is_reported() { + let (dir, mut ws) = hierarchical("hier_final_obs", &["single.sv", "leaf.sv"]); + let single_uri = uri_in(&dir, "single.sv"); + let (_, one, _) = sig_positions(); + let reused = "\ +module leaf #(parameter int W = 1) (input logic clk_i); + buf b(sig, clk_i); +endmodule +"; + let o = at(LEAF, "sig;") as usize; + assert_eq!(&reused[o..o + 3], "sig"); + assert_eq!(&reused[o - 1..o + 4], "(sig,"); + ws.set_document(uri_in(&dir, "leaf.sv"), reused.to_string()); + + let after = references(&ws, &single_uri, one, true); + assert_eq!(leaf_spans(&after), vec![(1, 8, 11)], "{after:?}"); + let _ = fs::remove_dir_all(&dir); + } } diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index e5d54a1..119cc4d 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -8631,3 +8631,113 @@ fn organize_imports_is_offered_under_its_own_kind_and_runs_as_a_command() { let _ = std::fs::remove_dir_all(&dir); } + +/// TODO §64.1 over the wire. `leaf` declares an internal net; `top.sv` names it +/// through a hierarchical tail and `leaf.sv` uses it itself. Before §64.1 +/// `textDocument/references` answered `leaf.sv`'s two lines from the +/// declaration and never the tail, while `textDocument/rename` at the same +/// position edited both files — lucisv could change a reference it could not +/// list. Asserted here from both ends, with `leaf.sv` the only open buffer, so +/// the tail comes out of the persisted postings and `leaf.sv`'s own use out of +/// the live one; then from `top.sv` with `leaf.sv` closed, where that file's +/// own use is served by one re-analysis of it. +#[test] +fn a_hierarchical_nets_references_and_rename_agree_over_the_wire() { + let dir = temp_dir("hierrefs"); + let leaf = dir.join("leaf.sv"); + let leaf_text = "\ +module leaf (input logic clk_i); + logic sig; + assign sig = clk_i; +endmodule +"; + std::fs::write(&leaf, leaf_text).expect("write"); + let top = dir.join("top.sv"); + let top_text = "\ +module top; + leaf u_leaf (.clk_i(1'b0)); + wire w; + assign w = u_leaf.sig; +endmodule +"; + std::fs::write(&top, top_text).expect("write"); + + let root = format!("file://{}", dir.display()); + let leaf_uri = format!("file://{}", leaf.display()); + let top_uri = format!("file://{}", top.display()); + + // `sig` is declared at line 1 column 8 of `leaf.sv`, used at line 2 + // column 9 there, and named at line 3 column 20 of `top.sv`. + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(WIDE_SCOPE), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{leaf_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(leaf_text).expect("json") + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/references","params":{{"textDocument":{{"uri":"{leaf_uri}"}},"position":{{"line":1,"character":8}},"context":{{"includeDeclaration":true}}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/rename","params":{{"textDocument":{{"uri":"{leaf_uri}"}},"position":{{"line":1,"character":8}},"newName":"renamed"}}}}"# + )), + // Now from the other side, with `leaf.sv` shut. + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didClose","params":{{"textDocument":{{"uri":"{leaf_uri}"}}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(top_text).expect("json") + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/references","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":3,"character":20}},"context":{{"includeDeclaration":true}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + let response = |id: u32| -> &serde_json::Value { + messages + .iter() + .find(|m| m["id"] == id) + .unwrap_or_else(|| panic!("no response {id} in {messages:#?}")) + }; + + // Every place naming the net, as `(file, line)`. + let places = |id: u32| -> Vec<(String, i64)> { + let mut out: Vec<(String, i64)> = response(id)["result"] + .as_array() + .expect("a list") + .iter() + .map(|location| { + let uri = location["uri"].as_str().expect("a uri"); + let name = uri.rsplit('/').next().unwrap_or("?").to_string(); + (name, location["range"]["start"]["line"].as_i64().expect("a line")) + }) + .collect(); + out.sort(); + out + }; + let everywhere = + vec![("leaf.sv".to_string(), 1), ("leaf.sv".to_string(), 2), ("top.sv".to_string(), 3)]; + assert_eq!(places(2), everywhere, "from the declaration"); + assert_eq!(places(4), everywhere, "from the tail, with `leaf.sv` closed"); + + // And the rename that was already editing both files edits exactly those + // places — the asymmetry §64.1 was filed for, closed from both sides. + let changes = &response(3)["result"]["changes"]; + let own = changes[&leaf_uri].as_array().expect("edits for the declaring file"); + assert_eq!(own.len(), 2, "{own:#?}"); + let elsewhere = changes[&top_uri].as_array().expect("edits for the naming file"); + assert_eq!(elsewhere.len(), 1, "{elsewhere:#?}"); + assert_eq!(elsewhere[0]["range"]["start"]["line"], 3); + assert_eq!(elsewhere[0]["range"]["start"]["character"], 20); + assert!(elsewhere.iter().all(|e| e["newText"] == "renamed"), "{elsewhere:#?}"); + + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/vlog_semantic/src/workspace/record.rs b/crates/vlog_semantic/src/workspace/record.rs index f8b651f..2be5204 100644 --- a/crates/vlog_semantic/src/workspace/record.rs +++ b/crates/vlog_semantic/src/workspace/record.rs @@ -347,13 +347,22 @@ fn facts_from_analysis( } // The **connection** surface only. A `Local` posting exists so that a // declaration another file can point at carries its own file's uses - // without that file being re-read, and every consumer of the postings - // that matters here — the rename, which re-analyses the declaring file - // anyway — already has them. Posting a module's every internal net use - // would multiply the reference table by the size of an RTL body for an - // answer nothing reads; the hierarchical surface is what a *cross-file* - // tail resolves through, and that half is an `External` fact below. - // See `docs/features/hierarchical-tail/README.md`, "what did not widen". + // without that file being re-read. Posting a module's every internal net + // use would multiply the reference table by the size of an RTL body; the + // hierarchical surface is what a *cross-file* tail resolves through, and + // that half is an `External` fact below. + // + // Two consumers read the postings for a hierarchical-only declaration, + // and each supplies the missing local half by re-analysing that one file: + // a rename (`vlog_refactor`), which re-analyses the declaring file + // anyway, and — since §64.1 — `lucisv_server`'s + // `nav::declaring_file_uses`, which parses exactly the declaring file + // when it is closed and a `references` request arrived from a cross-file + // use. So the narrow table costs one file's parse on one request shape, + // paid by the caller that needs it, instead of a reference table sized by + // every RTL body in the workspace. See + // `docs/features/hierarchical-tail/README.md`, "what did not widen", and + // `docs/features/references-hierarchical-surface/README.md`. // Which kind lands on which surface is `hierarchy::surface_of`, the one // rule this filter and the member tables both read (§49's QA asked for // the pointer). diff --git a/docs/features/hierarchical-tail/README.md b/docs/features/hierarchical-tail/README.md index cc42924..9b94893 100644 --- a/docs/features/hierarchical-tail/README.md +++ b/docs/features/hierarchical-tail/README.md @@ -128,10 +128,26 @@ The `propagate-ports` engine reads `member`/`members_of` and is untouched. - **Reference postings.** `facts_from_analysis` records a `Local` posting only for a use whose declaration is on the **connection** surface. Posting a module's every internal-net use would multiply the reference table by the - size of an RTL body for an answer nothing reads: the only consumer is a - rename, which re-analyses the declaring file anyway. The *cross-file* half — - the tail in the other file — is an `External` fact, and that is what makes - the rename work. + size of an RTL body. The *cross-file* half — the tail in the other file — + is an `External` fact, and that is what makes the rename work. + + **Amended 2026-09-12 (§64.1).** This bullet used to end "for an answer + nothing reads: the only consumer is a rename, which re-analyses the + declaring file anyway". There are two consumers now, and the sentence is + true again only with the second one named: `textDocument/references` reads + the postings too, and since §64.1 it answers for a hierarchical-only + declaration. It is served the way the rename is — + `lucisv_server`'s `nav::declaring_file_uses` parses **exactly the declaring + file, exactly once**, and only when that file has no open buffer and the + request came in from a cross-file use; an open buffer's own uses come from + the live overlay as they always did. Measured on opentitan: `references` + from `u_entropy_src_main_sm.state_q` with `entropy_src_main_sm.sv` closed + costs 1.0–1.5 ms against the 0.1–0.2 ms of the incomplete answer it + replaces, and every connection-surface row of the `nav` harness is + unchanged in both result count and time. So the decision stands, with its + cost now written down: one file's parse on one request shape, instead of a + reference table sized by every RTL body in the workspace. See + `docs/features/references-hierarchical-surface/README.md`. - **`workspace/symbol`.** An internal net is still not a workspace symbol: the request answers what a user can name from outside, and a design with 20 000 modules has hundreds of thousands of internal signals. diff --git a/docs/features/hover-declarations/README.md b/docs/features/hover-declarations/README.md index c397da5..b421c05 100644 --- a/docs/features/hover-declarations/README.md +++ b/docs/features/hover-declarations/README.md @@ -142,6 +142,17 @@ The character cap counts `char`s and cuts on a boundary. ## Work log +### 2026-09-12 — dev (§64.1: `spells_exactly` is now `pub(crate)`) + +Visibility only, no behaviour change here. `nav.rs` needed the same +agreement check for a closed file's *span* that this feature applies to a +closed file's *snippet* — after §64.1 an index-time `references` span can be +rendered against bytes that moved — and QA's lesson above (a fixed-length +span still spelling the old name as a **prefix** of a longer identifier) is +exactly the case a second copy of the check would have got wrong. So +`hover::spells_exactly` is shared rather than duplicated; see +`docs/features/references-hierarchical-surface/README.md`. + ### 2026-08-27 — dev - Read the brief, `hover.rs`, `nav.rs`, `state.rs` and `convert.rs`. Confirmed diff --git a/docs/features/references-hierarchical-surface/README.md b/docs/features/references-hierarchical-surface/README.md new file mode 100644 index 0000000..0332cd7 --- /dev/null +++ b/docs/features/references-hierarchical-surface/README.md @@ -0,0 +1,1099 @@ +# references-hierarchical-surface + +TODO.md §64.1 — `textDocument/references` for a declaration that only a +**hierarchical** path can reach. `docs/topo.md` §2.9 row for +`lucisv_server ──▶ vlog_semantic`. Ships in 0.55.0. + +## Goal + +With `module leaf` declaring `logic sig` and another file writing +`assign w = u_leaf.sig;` (or a `bind`'s connection expression naming it), +`textDocument/references` answered `leaf.sv` alone. It could not list a use +that a rename since 0.45.0 happily *edits* — the same asymmetry +`references-nav` was written to remove, re-opened for one class of +declaration by `hierarchical-tail`. + +The cause was in `crates/lucisv_server/src/nav.rs`, in the two functions that +map a name onto the index: + +- `leaves_this_file` asked `WorkspaceIndex::member(owner, name)` — the + **connection** surface, a module's ports and parameters. A module's net, + variable or instance is exported on the **hierarchical** surface only + (`workspace/hierarchy.rs::surface_of`, since 2026-09-05), so the gate judged + such a declaration unable to leave its file and the request degraded to the + single-file answer. +- `indexed_def_in_file` — wrapped by `indexed_def_for_symbol`, which + `hover.rs::live_symbol` shares — mapped a *live* `Symbol` back to its + persisted `Def` the same way. So even a request that did go cross-file (from + a use the overlay resolved) could not re-identify an open buffer's own + in-file uses of the net, and dropped them. + +Both now ask `member_in(owner, name, Surface::Hierarchical)`. The connection +answer is a prefix of the hierarchical one (`hierarchy::member` consults the +connection table first and returns it whole when it is non-empty), so a port, +a parameter, a package member, a class field and a struct field keep their +answers byte-for-byte. + +A second, consequential gap had to close in the same change: the index +deliberately records **no `Local` reference posting** for a use whose +declaration is hierarchical-only (`workspace/record.rs::facts_from_analysis`, +"the connection surface only"), so `references_to(def)` holds the *cross-file* +`External` sites and nothing else. The declaring file's own uses came from +`indexed_references`' open-documents loop — which only sees it while it is +open. Requesting references from the bind file with `leaf.sv` closed would +therefore have listed the cross-file sites and the declaration and silently +omitted `leaf.sv`'s own `assign … = sig` lines. `indexed_references` now +analyses that one file once, on exactly that shape. + +## Assumptions + +- **Reachability is judged on the surface a use can actually reach the + declaration by.** Not on the surface a *connection list* may name, which is + what `member` answers. The two call sites ask + `Surface::Hierarchical` because a `references` answer must cover every way + another file can spell the name, and a hierarchical path is one of them + (IEEE 1800 §23.6). +- **The hierarchical answer contains the connection one**, first, whole — + `hierarchy::member`'s own contract, asserted there by + `a_tail_naming_a_port_is_one_answer_and_one_edit`. That is what makes this a + widening and not a change: every name the connection read answered is + answered identically by the hierarchical read. +- **A name declared twice in one unit is not silently the port.** For a unit + declaring both a port `x` and a net `x`, the hierarchical read returns the + port record (connection first). `indexed_def_in_file`'s kind filter + (`def.kind == symbol.kind`) then rejects the *net* symbol, so the net gets + the honest single-file answer and the port keeps its cross-file one. The + single-record rule (`defs.len() != 1`) and `references_are_ambiguous` keep + their meaning unchanged over the wider answer. +- **A declaration on neither surface still never asks the workspace.** A net + declared inside a generate block belongs to the block's scope, not the + module's (`hierarchical-tail`, "a unit's members are the symbols of its own + scope"), so `member_in` answers nothing for it and the gate is `false` — the + same honest single-file fallback `u_x.gen_b.sig` gets from a rename. +- **The closed-file re-analysis is a completeness repair, not a second + authority.** It runs only when the target declaration is hierarchical-only + *and* its declaring file has no open buffer, it parses exactly that one file, + and it contributes spans for exactly the one symbol that maps back to the + same `Def` the request is about — the same logical identity check + (`path`, owner, name, kind) `indexed_def_in_file` makes everywhere else. Its + spans go through the same sort/dedup/empty-drop `locations` already applies, + so it can add occurrences and never reorder or duplicate them. +- **One text per closed file per request, and it is a fresh one** (added + 2026-09-12 in rework; QA finding 1). A span means nothing except against the + bytes it was computed from. `declaring_file_uses` reads with + `Workspace::text_of`, which never caches, and **returns** that text so + `locations` renders its spans against the same bytes instead of taking a + second, independent read of the same path. `Workspace::file_view` is + deliberately *not* used here: it is the right cache for `hover`, which reads + a closed file once per generation of it and renders nothing but a snippet + from that read, and it is the wrong input for a span that a different step in + the same request turns into a line and column. An external edit to a closed + file is none of the five events that drop a view, so the cached bytes and + `locations`' fresh bytes can disagree — which is precisely how QA got a + wrong line rather than an omission. +- **A closed file's index-time span is a claim, and it is checked.** Every + span about a closed file that did *not* come from this request's own read — + a `references_to` posting, the `include_declaration` fallback — is emitted + only if it still spells the target's name exactly in the text it is about to + be rendered against (`hover::spells_exactly`, shared rather than copied, so + the prefix/suffix lesson its QA taught applies here too). Otherwise it is + dropped. A stale record can then only ever *omit* a location, never point at + a wrong line — the same guarantee `hover` gives a stale snippet, and it holds + for **open buffers too** (QA finding 4, fixed 2026-09-12). An open buffer's + *own* spans pay nothing: they came from the very text they are rendered + against. The one index-time span that can reach an open buffer is the + `include_declaration` fallback, taken only when the buffer no longer + declares the name at all (an unsaved rename); `declaration_site` emits it + only if it still spells the name exactly in the live text, else omits the + declaration. Cost: one slice compare plus two character tests per + closed-file location, and the same once per request on that one fallback. +- **`hierarchical_only` reads the index, not a rule restated in the protocol + layer.** `WorkspaceIndex::hierarchical_declarations(name)` enumerates the + hierarchical-**only** table, which is exactly where `surface_of`'s + `Surface::Hierarchical` tag routes a record (`workspace/update.rs` ~301). So + the test cannot drift from `surface_of` the way a `matches!(def.kind, Net | + Var | Instance)` restated in `nav.rs` would: that spelling would be wrong for + an interface's net (connection) and would go stale the next time + `surface_of` moves a kind. + +## Handshakes + +**Consumed from `vlog_semantic`** (all already public before this change; no +new API, no `FACTS_FORMAT` bump, no index field): + +- `WorkspaceIndex::member_in(unit, name, Surface)` and `Surface` — the two + call sites' new question. `member_in` needed no new case; `surface_of` + already tags a module's nets, variables and instances + `Surface::Hierarchical` and an interface's instances likewise. +- `WorkspaceIndex::hierarchical_declarations(name)` — the hierarchical-only + census, previously read only by rename's fan-out. Used here to ask whether + one `Def` is hierarchical-only. It iterates the units that have + hierarchical-only members and probes each for `name`, with an early-out; + this lane asks it at most once per `references` request, and only when the + declaring file is closed. +- `parse_source_tolerant` + `analyze` + `Semantics::{symbols_named, + references_of, symbol, scope, file_scope}` — the one-file re-analysis, the + same pair `FileFacts::analyzed` and rename's engine run. + +**Request (not taken here):** a `WorkspaceIndex` query keyed by `Def` — say +`fn hierarchical_only(&self, def: &Def) -> bool` beside +`references_are_ambiguous` — would turn the census iteration above into one +map probe. It belongs in `crates/vlog_semantic/src/workspace/index.rs`, which +is outside this lane's file list, and the measured cost of the iteration did +not justify asking for the widening now. Recorded so the next lane in that +file can take it. + +**Promised to `hover.rs`:** `nav::indexed_def_for_symbol` keeps its signature +and its contract (a live symbol maps to the indexed `Def` that *is* it, by +path/owner/name/kind). It now also answers for a hierarchical-only member, so +`hover`'s `live_symbol` finds a live net's declaration in an edited buffer and +the card gains the snippet it used to drop. Nothing hover already answered +changed. No production edit was needed in `hover.rs`. + +**Consumed from this crate's own `hover.rs`:** `spells_exactly`, made +`pub(crate)` (visibility only, no behaviour change) so the closed-file span +guard is the *same* check hover applies to a closed-file snippet rather than a +second copy of it — QA's prefix/suffix lesson lives in that function and must +not be re-learned. Noted in `docs/features/hover-declarations/README.md`'s +work log. + +**Promised to `vlog_semantic`'s `record.rs`:** its "an answer nothing reads" +comment is no longer true and now names this consumer and how it is served. +Comment only; no code, no format change. + +**Unchanged by contract:** `documentHighlight` stays a *document* answer even +for a cross-file name (`references-nav`, 2026-08-28). It reads +`Semantics`/the overlay, never the index's reachability gate, so it needed no +change; it is pinned here from both ends anyway. + +**`verify.rs`:** untouched. No normalization added or broadened, so no +masked-corruption attack tests are owed. + +## Status / TODO + +- [x] feature README skeleton before the work +- [x] the fixture sweep, asserting today's answers first and then flipped: + `definition`, `references` (from the declaration and from each use, + `includeDeclaration` both ways), `hover`, `documentHighlight` over + (a) a `bind` connection's bare name, (b) a `u_x.sig` tail from an + instantiating file, (c) a two-level tail, (d) a port of the same unit + (unchanged), (e) a package member (unchanged), (f) a name declared + twice in one unit (one symbol, one record — see the work log), + (g) an `untitled:` buffer, (h) the open buffer's own in-file use seen from a cross-file + use, (i) the declaring file **closed** +- [x] the fix in both call sites +- [x] the closed-declaring-file completeness repair +- [x] the §63.1 QA test renamed and its assertions flipped +- [x] `a_local_signal_never_asks_the_workspace` rewritten honestly +- [x] the attack cases pre-empted (generate-scoped net; a net shadowed by a + port of the same name in another unit; both a port and a net of one + unit; a class member; a package member; `untitled:`; two like-named + modules) +- [x] opentitan, read-only: `entropy_masking_req` from `aes.sv` lists + `aes_bind.sv`; `state_q` from `entropy_src_main_sm.sv` lists + `entropy_src_core.sv`; the `nav` harness row before/after +- [x] gates: `cargo fmt --all -- --check`, `cargo clippy --all-targets`, + `cargo test --workspace`, all through `tools/guard.sh` +- [x] TODO §64.1 ticked; the two neighbouring READMEs amended + +**Rework round (QA findings 1–3), 2026-09-12:** + +- [x] finding 1: `declaring_file_uses` reads with `text_of` (fresh, never + cached) and returns that text; `locations` renders the declaring file's + spans against it, so one closed file is read exactly once per request +- [x] finding 1: the declaration reported for a re-analysed closed file is its + **live** span, not the index-time one +- [x] findings 2–3: every index-time span about a closed file is guarded with + `hover::spells_exactly` against the text it is rendered in, and dropped + if it no longer spells the name — open buffers pay nothing +- [x] `hover::spells_exactly` made `pub(crate)`, noted in + `docs/features/hover-declarations/README.md`'s work log +- [x] `qa_finding_1/2/3` flipped to the fixed answers and renamed to say what + they pin; one new attack on the guard itself + (`qa_a_stale_span_that_now_spells_a_longer_name_is_dropped`) +- [x] gates re-run; opentitan rows re-confirmed byte-identical + +**Rework round 2 (QA finding 4), 2026-09-12:** + +- [x] the `include_declaration` block lifted into `declaration_site` (a pure + move plus the guard); an open buffer's index-time fallback span emitted + only if `hover::spells_exactly` holds against the live text, else the + declaration is omitted — the closed path still guarded exactly once +- [x] QA's finding-4 test flipped to the fixed answer and renamed + (`qa_recheck_a_renamed_open_buffers_stale_declaration_is_omitted_not_misreported`), + its unsaved-rename setup kept; one control test + (`an_open_buffer_edited_above_its_declaration_reports_the_live_declaration_line`) +- [x] gates re-run through `tools/guard.sh` + +## Work log + +### 2026-09-12 — dev + +**What changed, in production code.** Three edits in +`crates/lucisv_server/src/nav.rs` and nothing else: + +1. `leaves_this_file` — the member branch now asks + `member_in(&owner.name, &symbol.name, Surface::Hierarchical)` where it + asked `member`. +2. `indexed_def_in_file` — the same swap, and its first parameter became + `&Semantics` instead of `&Document`. It only ever read `doc.semantics`, + and taking the analysis directly is what lets the closed-file repair below + ask the identity question the same way, by construction rather than by a + second copy of the rule. `indexed_def_for_symbol` (shared with + `hover.rs::live_symbol`) keeps its signature. +3. `indexed_references` gained one line — `found.extend(declaring_file_uses(ws, + &target))` — plus the two new functions it calls, `declaring_file_uses` + (26 lines) and `hierarchical_only` (3). + +**Why the closed-file repair exists.** The lead's second gap, confirmed on +the real tree. With `member_in` in place but nothing else, `references` from +`entropy_src_core.sv`'s `u_entropy_src_main_sm.state_q` with the declaring +file closed answered `entropy_src_main_sm.sv: [42]` — the declaration alone — +and silently dropped lines 46, 49 and 60. The index posts no `Local` fact for +a hierarchical-only declaration, so `references_to` holds only the cross-file +`External` sites, and the open-documents overlay can only speak for a file +that is open. `declaring_file_uses` closes it with one +`parse_source_tolerant` + `analyze` of exactly that file, behind three gates +in increasing cost order: the declaring file has no open buffer (one binary +search), the declaration is hierarchical-only (the census below), and the file +could be read. The spans go through `locations`' existing +sort/dedup/empty-drop, so the repair can only add occurrences. + +*(Amended by the rework entry below: this first pass read the file through +`Workspace::file_view`, a cache, which is what QA's finding 1 caught. It now +reads once through `text_of` and hands the same bytes to the rendering step.)* + +**The `hierarchical_only` test, and why this one.** The brief offered two +spellings. The `member(unit, name).is_empty() && !member_in(…)` pair needs +the owner's *unit name*, which `indexed_target` has in its `Definition::Local` +branch and does **not** have in its `Definition::External` branch — and the +External branch is exactly the shape that matters (a request from the bind +file or from `top.sv`). A `matches!(def.kind, Net | Var | Instance)` spelled +in `nav.rs` needs no unit name but restates `hierarchy::surface_of`, and +would already be wrong for an **interface's** net, which that rule puts on the +*connection* surface. So the test asks the index's hierarchical-only table +itself: `hierarchical_declarations(name).any(|(_, held)| held == &target.def)`. +A `Def` is in that table exactly when `surface_of` tagged it +`Surface::Hierarchical` (`workspace/update.rs` routes on `decl.surface`), which +is precisely "no `Local` posting was recorded for it" — the condition the +repair is for. Cost: an iteration over the units that hold hierarchical-only +members, with an early-out, taken at most once per request and only after the +declaring file is known to be closed. **Measured, not assumed:** the `nav` +harness's two `references` rows are 1.39–1.86 → 1.12–1.58 ms (`aes`, a unit) +and 1.05–1.65 → 1.14–1.59 ms (`.clk_i`, a port whose declaring file is +closed — the row that pays for the census and nothing else), with identical +result counts. A `WorkspaceIndex` query keyed by `Def` would make it one map +probe; that is filed as a Handshake request above rather than taken, because +`workspace/index.rs` is outside this lane's files and the measurement does not +justify asking. + +**What the fixture sweep found, in order.** Written first against today's +behaviour: the eleven new `nav.rs` tests were run before the production edits +and exactly four failed, with exactly the incomplete answers §64.1 describes — +from the declaration `[leaf.sv 1, leaf.sv 2]` (both tails missing); from a +tail `[leaf.sv 1, single.sv 3, top.sv 3]` (the declaring file's own use +missing); the same with the declaring file closed; and the shadowed-net attack +`[sb.sv 1, sb.sv 2]`. The other seven — `definition`, `documentHighlight`, the +port, the parameter, the class member, the redeclared name, the two like-named +modules, the `untitled:` buffer — passed before the change and pass after it, +which is the byte-identity claim asserted rather than argued. The new hover +test and the new wire-level `e2e` test were each also run against a +deliberately reverted binary and each failed there (no fence on the card; +`[leaf.sv 1, leaf.sv 2]` over the wire). + +**Case (f) as posed cannot arise, and that is the finding.** §64.1 asked that +"a name declared both as a port and as an internal net of the same unit is +ambiguous, not silently the port". `vlog_semantic` records **one symbol per +name per scope** — a redeclaration becomes a `Duplicate` and a *reference* to +the first declaration — so one `(unit, name)` never has two records from one +file, and there is no port for the answer to silently become. Tried both +spellings (`module both (input logic x); wire x;` and +`module pboth #(parameter int q = 1) (); wire q;`): one symbol, one index +record, one complete answer from either cursor position, before and after the +change. Pinned as `a_name_declared_twice_in_one_unit_is_one_symbol_and_one_record`. +What *is* reachable is the same name declared in **two files** — two records +for one `(unit, name)` — and there the single-record rule (`defs.len() != 1`) +declines exactly as before; pinned as +`two_modules_of_one_name_keep_a_hierarchical_net_on_the_in_file_answer`. The +port-versus-net asymmetry does still exist one level down, in +`indexed_def_in_file`'s kind filter, and is written up in Assumptions. + +**`a_local_signal_never_asks_the_workspace`, rewritten.** Its +`!leaves_this_file` assertion on a module's net was the old contract and is +now false, so it flipped; the two truths it protected did not, and are +asserted more sharply than before — `other.sv`'s same-named net is still +never listed, and a generate-block-scoped net and an undeclared name still +never ask the workspace. `ws.held_views()` is now asserted empty in that test, +so "no project read" is a witness rather than a claim. + +**opentitan, read-only.** Both confirmations hold, through a scratch driver +over `tools/perf/lspclient.py` (stdio, workspace scope, cache in the +scratchpad; `didOpen` + `references` only, no edit request sent): + +| row | before | after | +|---|---|---| +| `entropy_masking_req` from `aes.sv:89` | `aes.sv [89 137 140 203]` | + `aes_bind.sv [45 54]` | +| `state_q` from `entropy_src_main_sm.sv:42` | `…sm.sv [42 46 49 60]` | + `entropy_src_core.sv [3092]` | +| `state_q` from the tail, declaring file **closed** | `core [3092]`, `sm [42]` | `core [3092]`, `sm [42 46 49 60]` | +| `references on aes` (control) | 9 files, 14 locations | identical | +| `references on .clk_i` (control) | 9 files, 12 locations | identical | + +Costs: 0.2 → 0.1–0.4 ms (row 1), 0.2 → 0.4–0.7 ms (row 2), 0.1–0.2 → 0.9–1.5 ms +(row 3, the parse), controls within noise. `git -C status --short` +lists the same three files, with the same Aug 29/30 mtimes, before and after +every run — a pre-existing dirty state in the owner's checkout, not this +lane's (reported, not touched). + +**Deviations from the brief.** Two, both recorded above: the sweep's +"today's answers" were captured as the four recorded *failures* of the +post-fix assertions on the unmodified binary rather than as a committed +intermediate set of stale assertions — the same evidence, in the same order, +without a second edit of every test; and case (f) is pinned as +"unrepresentable, here is why" rather than as an ambiguity fallback. + +**Not done, deliberately.** `verify.rs`, the formatter and the corpus / +opentitan byte-identity gates are untouched by this change and were not +re-run: no normalization was added or broadened and no formatting code was +edited, so nothing is owed there. `docs/perf/README.md` and `docs/topo.md` are +§64.2's closing items and belong to the lead, not to this lane's file list; +the numbers they need are in the table above. + +**Gates**, all through `tools/guard.sh`, no kill: + +``` +tools/guard.sh -m 8 -t 900 -- cargo fmt --all -- --check # clean +tools/guard.sh -m 10 -t 1200 -- cargo clippy --all-targets # clean +tools/guard.sh -m 10 -t 1800 -- cargo test --workspace # 4435 passed, 0 failed +``` + +Test counts: workspace 4422 → 4435 (+13); `lucisv_server` 1772 → 1785 +(+11 in `nav.rs`, +1 in `hover.rs`, +1 in `tests/e2e.rs`); `vlog_semantic` +377 → 377 (comment only). `nav.rs` production lines 354 → 383, so the +closed-file repair stayed in `nav.rs` rather than earning a module. + +### 2026-09-12 — dev (rework: QA findings 1–3, the stale-closed-file hazard) + +The lead ruled all three fixed in this lane. Three production changes in +`crates/lucisv_server/src/nav.rs` and one visibility change in `hover.rs`; +nothing else moved. + +**1. One text per closed file per request, and it is the fresh one (finding +1 — this lane's own defect).** `declaring_file_uses` read the declaring file +through `ws.file_view`, a cache, and threw the text away; `locations` then +read the same path again through `ws.text_of`, which never caches, and +rendered the first read's spans against the second read's bytes. An external +edit to a *closed* file is none of the five events that drop a view, so the +two reads disagreed and a stale offset landed on a wrong line — QA's +`leaf.sv` "own use" at line `3` (`// two`). `declaring_file_uses` now reads +once with `text_of` and returns a `DeclaringFile { text, declaration, uses }`; +`indexed_references` hands that text to `locations` in a `ClosedText`, and +`closed_locations` uses it instead of fetching the path again. Why not +`file_view`: it is exactly right for `hover`, which reads a closed file once +per *generation* of it and renders nothing but a snippet from that read, and +exactly wrong as the input to a span that a **different step of the same +request** turns into a line and column. The doc comment on +`declaring_file_uses` says so, in those terms. + +**2. The declaration of a re-analysed closed file is its live span (finding +2).** `include_declaration` fell straight from "is the file open?" to +`target.declaration_span`, the index-time span. A file this request just +re-analysed knows where the declaration is *now*, so `DeclaringFile` carries +it and `indexed_references` prefers it; the index-time span is the last resort +and the only declaration span the guard has to catch. + +**3. A closed file's index-time span is checked before it is rendered +(findings 2–3).** `closed_locations` emits a span only if it still spells +`target.name` exactly in the text it is about to be rendered against — +`hover::spells_exactly`, made `pub(crate)` and *shared* rather than copied, +because the lesson inside it (a fixed-length span still spelling the old name +as a **prefix** of a longer identifier passes a length-and-content check) is +the thing a second copy would get wrong. A stale record can now only ever omit +a location, never point at a wrong line. Open-buffer spans are not guarded at +all: they came from the very text they are rendered against, so they would pay +for nothing. Cost: one slice compare plus two character tests per closed-file +location. + +**What the three QA tests assert now**, each worked out from `LEAF_MOVED`, +which is `LEAF` with three comment lines pushed in below the header — so line +`0` is the module header, `4` is ` logic sig;` and `5` is +` assign sig = clk_i;`: + +| test (renamed) | was | is | why | +|---|---|---|---| +| `qa_finding_1_a_disk_edited_closed_declaring_file_reports_its_live_spans` | `[1, 3]` | `[4, 5]` | both spans come from the re-analysis of the fresh text | +| `qa_finding_2_one_fresh_request_reports_the_live_declaration_line` | `[1, 5]` | `[4, 5]` | the declaration is the re-analysed span, not the index-time one | +| `qa_finding_3_a_stale_index_span_in_a_closed_file_is_dropped_not_misreported` | `[0, 3]` | `[0]` | a **port**: no re-analysis runs, so both spans are index-time claims. The header at line `0` is untouched by the edit and still spells `clk_i`, so it is reported; the posted use's span now points into `// two`, so it is dropped. Inventing `5` was never an option — nothing re-analysed that file, so the request does not know `5`, only that what it held is no longer true. | + +`qa_finding_3` also gained a pre-edit sanity assertion (`[0, 2]`), so the +test proves the guard drops a span that *was* being reported rather than one +that never was. + +**One new attack on the guard itself**, +`qa_a_stale_span_that_now_spells_a_longer_name_is_dropped`: `leafp` declares +one port and uses it nowhere, so the only closed-file span in the answer is +the index-time declaration span; the disk edit renames `clk_i` to `clk_i2` and +changes nothing before it, leaving that span's bytes still reading exactly +`clk_i`. A length-and-content check would emit it. The answer is the +connection in the open buffer and nothing else. + +**Function sizes** after the split (`locations`' closed branch moved into +`closed_locations`, a pure extraction): `locations` 35 lines, +`closed_locations` 22, `declaring_file_uses` 29 — all inside 10–50. `nav.rs` +production lines 383 → 422 by this lane's counting method (QA's method reads +one line higher throughout, as their log notes), still well under 600. + +**The regression the guard could have caused, and did not.** Every +pre-existing cross-file test passes unchanged, including the ones whose +closed-file spans sit inside a qualified or hierarchical name — +`p::WIDTH` in a closed `b.sv`, `u_mid.u_leaf.sig` in a closed `top.sv`, the +bind fixture's connection expression. `spells_exactly` sees `.`, `(` and `:` +around those spans, none of which continues an identifier. The five opentitan +rows are byte-identical to the pre-rework run, so the guard drops nothing on a +real, in-sync workspace. + +**Accepted as-is per the ruling:** QA's +25 % (1.22 → 1.54 ms median) on a +`references` request for a purely local net in a 40 000-line file. The lead +notes it in `docs/perf/README.md` at closing; no change made here. + +**Gates**, all through `tools/guard.sh`, no kill: + +``` +tools/guard.sh -m 8 -t 900 -- cargo fmt --all -- --check # clean +tools/guard.sh -m 10 -t 1200 -- cargo clippy --all-targets # clean +tools/guard.sh -m 10 -t 1800 -- cargo test --workspace # 4446 passed, 0 failed +``` + +Test counts: workspace 4445 (QA's post-attack count) → **4446** (+1, the +guard attack); `lucisv_server` 1795 → **1796**; `nav.rs`'s `mod tests` +60 → 61 of the 64 non-ignored tests it runs. No test was deleted or weakened: +the three `qa_finding_*` tests kept their fixtures and their disk edits and +had their expected sets flipped, with the derivation of each set written into +the test. `fmt` wanted one `cargo fmt --all` pass twice during the rework (a +`found.extend` line, then the extraction), after which `--check` is clean. + +### 2026-09-12 — dev (rework 2: QA finding 4, the open-buffer declaration fallback) + +The lead confirmed the finding and asked for the minimal fix. One production +change in `crates/lucisv_server/src/nav.rs`; nothing else moved. + +**The gap.** `indexed_references`' `include_declaration` chain was: the open +buffer's live symbol, else the re-analysed closed file's live declaration, +else `target.declaration_span` — an index-time span. The closed path guards +that last span in `closed_locations`. The open path never could: `locations` +renders an open document's spans unguarded, correctly, because every span it +normally sees came from that very buffer. The one that did not is this +fallback, reached exactly when the live lookup fails — the user renamed the +declaration in the buffer without saving, so the buffer no longer declares +`target.name` while a cross-file use still names the persisted `Def`. QA's +reproduction: a stale 3-byte `sig` rendered on the first three characters of +the live `sig2`. + +**The fix.** The block is lifted into `declaration_site(ws, target, +declaring) -> Option` — a pure move of the three-way chain plus one +guard. For an open buffer: the live symbol's span, else the index-time span +*only if* `hover::spells_exactly(&doc.text, span, &target.name)` holds against +the live text, else `None` and the declaration is omitted — the same rule and +the same function the closed path applies, so QA's prefix/suffix lesson is +not re-learned. For a closed file the chain is unchanged (re-analysed live +span, else the index-time span) and the span still meets its one guard in +`closed_locations`; `declaration_site` does not check it, so no closed span is +guarded twice. `locations` is untouched. + +**Why omit rather than search.** The buffer does not declare the name; there +is nothing correct to point at. An honest omission is the guarantee the rest +of this feature gives a stale record, now without an exception for the open +case. + +**Tests.** QA's `qa_recheck_a_renamed_open_buffer_and_the_unguarded_declaration_fallback` +is flipped and renamed +`qa_recheck_a_renamed_open_buffers_stale_declaration_is_omitted_not_misreported`: +same fixture, same unsaved rename of `sig` to `sig2` in the open `leaf.sv`, +asked from `single.sv`'s tail. It now asserts a pre-rename sanity answer +(`every_place_naming_sig`) and, after the rename, +`[single.sv 3, top.sv 3]` — `leaf.sv` absent, the two tails unchanged (the +`top.sv` one is a closed-file posting that still spells `sig` and passes its +own guard). The control, +`an_open_buffer_edited_above_its_declaration_reports_the_live_declaration_line`: +the open `leaf.sv` gets two comment lines pushed in above the header, unsaved, +so the declaration only moved and still spells `sig`. The live-symbol path +answers first, so `leaf.sv` reports `(3, 8..11)` and `(4, 9..12)`, the whole +answer is `[leaf.sv 3, leaf.sv 4, single.sv 3, top.sv 3]`, and line 3 goes +away with `includeDeclaration: false` — so it is the declaration and it came +from the live path (the index-time offsets land inside the header line, which +spells no `sig`; had the guard been consulted the line would be missing, not +moved). + +**Sizes.** `indexed_references` 86 → 71 lines (comments included); +`declaration_site` 19. `nav.rs` production lines 423 → 433 (this lane's +counting method), under 600. + +**Gates**, all through `tools/guard.sh`, no kill — verbatim tails: + +``` +$ tools/guard.sh -m 8 -t 900 -- cargo fmt --all -- --check +(no output; exit 0) + +$ tools/guard.sh -m 10 -t 1200 -- cargo clippy --all-targets + Checking lucisv_server v0.54.0 (/Users/guoliangchen/repo/verilogrustformatter-d8afe80f/crates/lucisv_server) + Finished `dev` profile [unoptimized + debuginfo] target(s) in 3.33s +(0 warnings) + +$ tools/guard.sh -m 10 -t 1800 -- cargo test --workspace + Doc-tests vlog_semantic +running 0 tests +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s +(exit 0; 60 `test result: ok` lines, summed: 4454 passed, 0 failed) +``` + +Test counts: workspace 4453 (QA's re-check count) → **4454** (+1, the +control); `nav.rs`'s `mod tests` 72 non-ignored (71 + 1; the flipped test kept +its slot). No test deleted or weakened. + +## QA log + +### 2026-09-12 — QA (task-d8afe80f) + +**Gates, re-run from a clean checkout of the lane, all through +`tools/guard.sh`, no kill:** + +``` +tools/guard.sh -m 8 -t 900 -- cargo fmt --all -- --check # clean +tools/guard.sh -m 10 -t 1200 -- cargo clippy --all-targets # clean +tools/guard.sh -m 10 -t 1800 -- cargo test --workspace # 4435 passed, 0 failed +``` + +Sum of every crate's "passed" count verified by script, matches the dev's +report exactly (4435). After adding the ten attack tests below (all in +`nav.rs`'s `mod tests`), re-ran fmt/clippy/test again: fmt needed one +`cargo fmt --all` pass on the new tests (two `for`-loop line breaks), then +clean; clippy clean; `cargo test --workspace` 4445 passed (4435 + 10), 0 +failed. + +**Pins re-derived by hand.** Walked every new/flipped assertion in `nav.rs` +against its fixture text: `every_place_naming_sig()` +(`leaf.sv 1/2, single.sv 3, top.sv 3`), the port/parameter test, the bind +fixture's `everywhere` set (`aes.sv 1/2, aes_bind.sv 2`), the class-member +test, the shadowed-net test, the redeclared-name test and the two-modules +test — all correct against the literal fixture strings, both +`includeDeclaration` values. No wrong-but-passing assertion found. + +**Size.** `nav.rs` production lines (non-blank, non-comment, before +`mod tests`): **384** (dev reported 383; the one-line difference is a +counting-method artifact, not a discrepancy in the actual diff — confirmed +byte-identical against 9d1eb16 up to the `mod tests` line). Well under 600. + +**Attack tests added** (10, all passing, in `nav.rs`'s `mod tests`, +prefixed `qa_`): + +1. `qa_a_generate_for_arrays_scoped_net_still_never_asks_the_workspace` — + an **indexed** generate array (`for (genvar i...) begin : gen`, + `u_g.gen[0].gsig`), sharper than the dev's named-block case. Confirms the + gate still declines and the single-file fallback still holds. +2. `qa_an_interface_signal_through_a_virtual_interface_handle_is_unchanged` + — `vif.data` from a class in another file. Confirmed unchanged (the + dev's Assumptions bullet, verified rather than trusted). +3. `qa_document_highlight_over_the_bind_fixture_stays_same_file_only` — the + bind fixture specifically (the dev's own `documentHighlight` pin used the + plain-tail fixture, not bind). Confirmed same-file-only from both the + declaration and the bind file's connection. +4. `qa_reopening_the_declaring_file_with_an_unsaved_edit_gives_live_spans` + — closed → answered by the repair → **opened** with an unsaved edit + above the declaration. Confirmed the live, shifted spans are reported + (`3, 4`), not the closed-file repair's stale ones. +5. `qa_references_agrees_with_the_rename_oracle_over_a_plain_tail`, +6. `qa_references_agrees_with_the_rename_oracle_over_the_bind_fixture`, +7. `qa_an_instance_names_references_agree_with_the_rename_oracle` — all + three assert `references(...)` (sorted) equals + `vlog_refactor::find_references` (sorted) over the same files. All + **pass**: no disagreement found between `references` and the whole-scope + rename oracle for the tail, the bind fixture, or the instance name + itself (the instance segment of a hierarchical tail *does* count as a + reference, and the answer is exactly what a rename would edit). +8–10. `qa_finding_1/2/3` — see Findings below. + +**opentitan, read-only, independent of the dev's driver.** Wrote a +standalone script (`tools/perf/lspclient.py`'s transport only, not +`bench.py`/`phases_*.py`) driving a freshly-built release `lucisv-server` +against the real checkout: + +| check | result | +|---|---| +| `entropy_masking_req` from `aes.sv`, `includeDeclaration: true` | 6 locations across `['aes.sv', 'aes_bind.sv']` — confirmed | +| `state_q` from `entropy_src_main_sm.sv` | 5 locations across `['entropy_src_core.sv', 'entropy_src_main_sm.sv']` — confirmed | + +(Note: `aes_bind.sv` is at `hw/ip/aes/dv/sva/aes_bind.sv`, not +`hw/ip/aes/dv/aes_bind.sv` as the briefs' shorthand path read; not a defect, +just a path correction for the record.) + +`git -C /Users/guoliangchen/repo/opentitan status --short` identical before +and after every run (the same three pre-existing dirty files, untouched). + +**Census**, over every `.sv` file in `hw/ip/aes/rtl` (40 files), every +module-level `logic`/`wire`/`reg` declaration found by a QA-only regex (not +a parser — see caveat): 948 declarations probed, 0 errors, 15 answered with +more than one file, 933 stayed single-file. Spot-checked (by reading the +source, not trusting the tool) four of the 15: + +- `aes.sv`'s `edn_data` → `aes_bind.sv` line 35/57 (`.entropy_i(edn_data)`) + — genuine, a bind connection expression. Confirmed correct. +- `aes_core.sv`'s `key_touch_forces_reseed` → `aes_bind.sv` line 40 + (`.key_touch_forces_reseed(u_aes_core.key_touch_forces_reseed)`) — genuine, + a hierarchical tail through the bind target's own instance. Confirmed + correct. +- `aes_pkg.sv`'s `alert_fatal_fault` and `input_ready`/`output_valid` — **not** + module-hierarchical hits at all: they are `struct packed` fields inside + `aes_pkg.sv` (confirmed by reading the file, e.g. line 158–160), which + were already on the **connection** surface before this lane (a package's + members are one surface). My regex census cannot distinguish a module net + from a struct field inside a package, so it over-counts; the genuinely + *new* hierarchical-surface hits in this 948-declaration sample are the two + above (and plausibly a handful more among the 15 I did not individually + read) — the census's absolute "15" should not be read as "15 newly + reachable module nets". Recorded as a methodology caveat, not a finding + against the fix: both spot-checked module-net hits are correct, and 0 of + 948 probes errored or produced an implausible file list. + +**Cost**, independently measured (not the dev's numbers, a fresh +measurement): `references` on `reg_we` — a purely local net used 576 times +in `pinmux_reg_top.sv` (40 267 lines), never referenced from another file — +with that file the only open buffer, 7 tries each, before this lane +(`9d1eb16`, built fresh in a throwaway worktree, removed after) and after +(this lane, freshly rebuilt release binary): + +| | result count | times (ms) | min | median | +|---|---|---|---|---| +| before | 573 | 5.184, 1.349, 1.218, 1.163, 1.385, 1.163, 1.135 | 1.135 | 1.218 | +| after | 573 | 1.973, 1.613, 1.541, 1.449, 1.733, 1.449, 1.421 | 1.421 | 1.541 | + +Result counts identical (correctness unaffected). Timing: a small, +**consistent** increase (every "after" sample, first-run JIT/cache outlier +excepted, sits above every "before" sample except its own outlier) — roughly ++0.3 ms, about +25% relative, though both stay well under 2 ms absolute. +This is the specific case the gate's cost argument is about (a name that +never leaves its file now takes the indexed path anyway), and it is real, +not noise, though small in absolute terms. Flagged for the closing review +to note in `docs/perf/README.md` rather than as a blocking defect — the +dev's own two opentitan rows (connection-surface controls) were correctly +reported "within noise"; this specific local-net-in-a-huge-file shape was +not previously measured and is not quite noise-level. + +**Findings.** + +1. **`declaring_file_uses` can render a wrong location, not just an + omission, if `Workspace::file_view`'s cache goes stale against an + external disk edit to the closed declaring file.** + `crates/lucisv_server/src/nav.rs::declaring_file_uses` (~line 391) reads + the declaring file's text through `ws.file_view`, a **cache** dropped + only by `set_document`/`close_document`/`update_one`/ + `rebuild_index_with`/`begin_widen` (`state/mod.rs::file_view`'s own + comment names these as the only four). An edit to a *closed* file made + outside the editor (another tool, `git checkout`, a build step) is none + of them. Reproduced: `qa_finding_1_a_primed_file_view_cache_mislocates_after_a_disk_edit` + (`nav.rs`) — prime the cache with one `references` call, edit `leaf.sv` + on disk (three lines pushed above the declaration, name/kind/owner + unchanged), ask again: the answer reports `leaf.sv`'s "own use" at line + `3` (`// two`) instead of the correct `5`, because `declaring_file_uses` + recomputes the span against the **stale cached** text while + `locations()` (same file, ~line 425) renders every span through + `Workspace::text_of`, which re-reads the file **fresh** with no cache of + its own — pairing a stale offset with new bytes exactly as the charter + asked to check for. Expected: the live spans, or an honest omission + (the same guarantee `hover.rs::spells_exactly` gives a stale view — "can + only ever omit a snippet, never show a wrong line"); actual: a silent + wrong line. +2. **The same closed-file mislocation happens with *no* cache priming at + all, from the shared `include_declaration` fallback — not + `declaring_file_uses`'s own code.** Reproduced: + `qa_finding_2_the_declaration_span_fallback_mislocates_with_no_priming_at_all`. + One fresh `references` call after the same disk edit: the declaration + line is wrong (`1`, `// one`, instead of `4`) while `declaring_file_uses`'s + own "own use" contribution is *correct* (`5`, freshly reparsed, nothing + had cached `leaf.sv` yet). The wrong half comes from + `indexed_references`'s `include_declaration` tail (~line 342 in the pre-QA + file, `.unwrap_or(target.declaration_span)`): for a closed file, + `target.declaration_span` is a span fixed at the last index rebuild, and + it is rendered the same way — through `locations()`'s `text_of`, a fresh + read, with no check that the two agree. +3. **The hazard predates this lane and is general, not specific to a + hierarchical-only net** — filed for the closing record, not as a defect + introduced here. Reproduced: + `qa_finding_3_the_same_hazard_predates_this_lane_for_a_port`. Same disk + edit, asked from a **port** connection (`single.sv`'s `.clk_i(1'b0)`, + reachable before §64.1 too): the port's own in-file use in the closed + file is *also* misrendered (`3`, wrong, instead of `5`); its declaration + survives at `0` only by coincidence (the module header line is unmoved + by the edit). This confirms the mechanism is a pre-existing, general + property of `nav.rs`'s closed-file handling (a persisted or cached span + rendered through a second, independent, always-fresh text read, with + no `spells_exactly`-style agreement check) — §64.1 does not introduce it, + it only widens *who* can reach it: every internal net in the workspace, + where before only a port or a parameter could. + +None of the three findings are `verify.rs`/formatter-facing (the hard +invariants are unaffected — this is `lucisv-server`, not the formatter), and +none are regressions the dev introduced in the sense of "worked before, +broken now": finding 3 proves the underlying bug already existed. But +finding 1 is materially new exposure (the closed-file repair's own cache +read is a second, distinct way to hit the same class of bug, on top of the +pre-existing one), and the widening in general (§64.1's whole point) makes +findings 2 and 3's pre-existing hazard reachable for a vastly larger set of +names than before. Recommend: either a `spells_exactly`-equivalent guard +before `nav.rs`'s `locations()` accepts a closed-file span (verify the span +still spells the target name in the text it's about to be rendered +against, drop silently if not — the same principle `hover.rs` already +enforces), or documenting the gap explicitly in `references-nav`'s README +next to the "same staleness window every other cross-file answer already +has" sentence, since right now that sentence undersells what "stale" can +do here (a wrong line, not just a late one). + +**Verdict: rework needed** — not because the widening's core logic is wrong +(the pins, the fixture sweep, the oracle equivalence checks, and the +opentitan confirmations all check out), but because of Finding 1 (this +lane's own new code path can mislocate) and the closing review's need to +decide how findings 2–3 (pre-existing, general) get tracked. Findings 2–3 +could reasonably be filed as a separate backlog item instead of blocking +this lane, at the lead's discretion, since they are not new; Finding 1 is +this lane's own new surface and should be addressed or explicitly accepted +with a documented reason before release. + +### 2026-09-12 — QA re-check (task-d8afe80f, same worktree) + +The lead ruled all three prior findings fixed; the dev's rework (work log +above, same date) is in the tree: `declaring_file_uses` returns +`DeclaringFile { text, declaration, uses }` from one `text_of` read; +`indexed_references` hands that text to `locations` as `ClosedText`; +`closed_locations` (a pure extraction from `locations`) guards every +closed-file span with `hover::spells_exactly`, now `pub(crate)`; the three +`qa_finding_*` tests are renamed and flipped. + +**1. Findings 1–3 re-derived by hand from `LEAF_MOVED`** (module header, +three comment lines, then `logic sig;` at line 4, `assign sig = clk_i;` at +line 5): + +- Finding 1 (`qa_finding_1_a_disk_edited_closed_declaring_file_reports_its_live_spans`): + primed cache, disk edit, re-ask → `[4, 5]`. Confirmed: both spans now come + from one fresh `text_of` re-analysis, not a second, independent read. +- Finding 2 (`qa_finding_2_one_fresh_request_reports_the_live_declaration_line`): + no priming at all → `[4, 5]`. Confirmed: the declaration is the + re-analysed live span (`DeclaringFile.declaration`), not + `target.declaration_span`. +- Finding 3 (`qa_finding_3_a_stale_index_span_in_a_closed_file_is_dropped_not_misreported`, + a **port**, no re-analysis runs at all): sanity `[0, 2]` before the edit, + `[0]` after — the unmoved header still spells `clk_i` and is reported; the + moved use's stale span no longer spells `clk_i` (it now sits in `// two`) + and is dropped, not misreported and not invented at `5`. Confirmed: this + is an honest omission, exactly the guarantee `hover.rs` already gives a + stale snippet. +- The new guard attack, `qa_a_stale_span_that_now_spells_a_longer_name_is_dropped` + (`clk_i` → `clk_i2` in place, nothing before it moved — the prefix-match + shape `spells_exactly`'s own boundary check exists for): confirmed + refused; only the live connection is reported. + +All four ran against a **real disk edit** in every case (`fs::write` to the +fixture's actual path) — none were weakened into an in-memory-only check. +Re-ran `cargo test -p lucisv_server --bin lucisv-server nav::tests::qa_finding` +and the guard-attack test directly: 4/4 pass. + +**2. New attacks against the guard and the one-read invariant** (all added +to `nav.rs`'s `mod tests`, prefixed `qa_recheck_`, all run and green): + +- `qa_recheck_a_disk_edit_that_moves_only_the_use_is_still_fully_reanalysed` + — only the use shifts, declaration line untouched. Since the target is + hierarchical-only, `declaring_file_uses` re-analyses the *whole* file + regardless of what moved: `[1, 4]`, both live and correct. +- `qa_recheck_a_deleted_closed_declaring_file_is_an_honest_omission_not_a_panic` + — `leaf.sv` deleted after the index was built, no rescan. No panic. + `leaf.sv` vanishes from the answer entirely (`text_of` fails in both + `declaring_file_uses` and `closed_locations`, both handled with `?`/`Option`, + never a crash); `single.sv` — untouched, still readable — keeps answering + normally, so only the one unreadable file is omitted, not the whole + request. (My first draft of this test asserted the wrong expected set — + `top.sv` only — before checking `single.sv`'s own posted tail was still + live and correct; fixed once I read the actual output.) +- `qa_recheck_a_stale_span_off_a_utf8_boundary_does_not_panic` — a stale + index-time port-use span (`clk_i`'s own use in `LEAF`) engineered, via a + disk edit, to land on the second byte of a 4-byte emoji in the new text — + never a `char` boundary. No panic: `spells_exactly`/`span_text` go through + `str::get`, which answers `None` off a boundary rather than panicking (Rust's + own guarantee, not new code to trust) — the file is correctly dropped + wholesale. +- `qa_recheck_two_closed_files_in_one_answer_are_independent` — `leaf.sv` + (re-analysed) and `single.sv` (a posted `External` site, never + re-analysed) both closed, asked from a third open file (`top.sv`). Edited + only `single.sv`'s own tail line on disk: `leaf.sv`'s answer (`[1, 2]`) is + completely unaffected, and `single.sv`'s own moved tail is dropped by the + *same* guard a port's stale use would be — confirmed each closed file is + rendered against its own, independently-read text, and an edit to one + cannot leak into the other's answer. +- `qa_recheck_an_escaped_port_name_survives_the_guard` and + `qa_recheck_an_escaped_net_survives_the_closed_file_reanalysis` + (added for the coordinator's specific follow-up on escaped identifiers): + `\my-clk` as a port (closed `sub.sv`, connection from open `top.sv`) and + `\my-sig` as a hierarchical-only net (closed `eleaf.sv`, tail + `u_leaf.\my-sig` from open `etop.sv`, plus `eleaf.sv`'s own + `assign \my-sig = …;`). **Both pass, unchanged.** The lexer's contract + (`docs/features/escaped-identifiers/README.md`: the token text is the `\` + through the last non-whitespace byte, matching `src[span]` exactly) means + `Symbol::name`/`name_span` already carry the backslash consistently, so + `spells_exactly`'s `span_text(text, span) == Some(name)` compares + backslash-inclusive strings correctly, and its boundary check + (`continues_a_name`) is right to ignore the escaped name's terminating + whitespace (not alnum/`_`/`$`) either side. No regression found here. +- `qa_recheck_a_renamed_open_buffer_and_the_unguarded_declaration_fallback` + — the direction not yet attacked: **an open buffer**, not a closed one. + +**3. One closed file, one read, per request — verified by code inspection, +corroborated empirically.** `ws.text_of` is called at exactly two static +sites in this path: once in `declaring_file_uses` (only for a +hierarchical-only target whose declaring file has no open buffer), and once +in `closed_locations`, guarded by `if held.is_none()` — and `held` is +`Some` exactly when the path equals the declaring path *and* +`declaring_file_uses` ran, so the declaring file's second read is skipped +by construction. `locations` groups `found` by path (sorted first, then +partitioned) before calling `closed_locations` once per group, so a given +path is never split across two calls and never read twice. No production +change was needed to verify this — a read counter would have needed one +(`text_of` is a plain `fs::read_to_string`, uninstrumented) — but +`qa_recheck_two_closed_files_in_one_answer_are_independent` is the +empirical corroboration: if either file's read leaked into or reused the +other's, editing only `single.sv` could not have left `leaf.sv`'s answer +byte-identical while independently affecting `single.sv`'s own. + +**4. FINDING 4 (new).** **An open buffer's `include_declaration` fallback +can emit a stale index-time span with no guard at all — the same "wrong +location, not omission" failure mode the rework just fixed for closed +files, reopened for open ones.** `crates/lucisv_server/src/nav.rs`, the +`include_declaration` block in `indexed_references` (~line 339): the chain +tries the live buffer's own symbol lookup, then `declaring.declaration` +(only set when `declaring_file_uses` ran, which it does not for an *open* +file — see its own early return), then falls to `target.declaration_span` +— an index-time span. When this fallback fires for a file that **is** +open, `found.push((target.declaration_path, span))` puts that stale span +under a path `locations` (~line 496) will render through the **open** +branch (`if let Some(doc) = ws.document_for_path(path) { … }`), which +never calls `closed_locations` and so never runs `spells_exactly` — no +guard exists on this branch at all, for any span. + +Reproduced: `qa_recheck_a_renamed_open_buffer_and_the_unguarded_declaration_fallback`. +`leaf.sv` is open with `sig` renamed to `sig2` (unsaved); the request comes +from `single.sv`'s tail, which still names the original `Def` by the +persisted index. The live lookup and `declaring_file_uses` both correctly +find nothing (no symbol named `sig` remains in the live buffer). The +fallback reaches `target.declaration_span` — the original 3-byte span for +`sig` — and it is rendered against `leaf.sv`'s *live* line index unguarded: +the answer includes `leaf.sv:1:8-11`, which is ` logic sig2;`'s columns +8..11 — a **strict prefix** of the live token `sig2` (columns 8..12), not +a complete identifier at all. This is exactly the "prefix of a longer +identifier" shape `spells_exactly` exists to refuse +(`qa_a_stale_span_that_now_spells_a_longer_name_is_dropped` proves it does, +for a *closed* file); for an open one, nothing is asked at all. + +Likely lower real-world frequency than findings 1–3 (it needs an unsaved +edit that removes the *particular* symbol the request's `Def` still points +at, in a buffer some *other* open or closed file's cross-file reference +still resolves to), but the failure shape is identical and arguably worse +for user trust: a "go to references" that lands on `sig2`'s first three +characters looks like a real, if odd, location rather than an obvious +non-answer. Suggest either running the same `spells_exactly` check on the +`include_declaration` fallback's span *unconditionally* (open or closed — +the guard is one slice compare plus two character tests, cheap enough to +never special-case), or restricting the fallback to only ever apply when +the file is closed (an open file with no live match should report nothing +for that file instead of trusting `target.declaration_span`). + +**Gates**, all through `tools/guard.sh`, no kill: + +``` +tools/guard.sh -m 8 -t 900 -- cargo fmt --all -- --check # clean +tools/guard.sh -m 10 -t 1200 -- cargo clippy --all-targets # clean +tools/guard.sh -m 10 -t 1800 -- cargo test --workspace # 4453 passed, 0 failed +``` + +Test counts: dev's rework count (4446) → **4453** (+7, the re-check attacks: +5 new scenarios plus the 2 escaped-identifier tests). `nav.rs` production +lines: **423** (dev's own count after the rework was 422; same one-line +counting-method difference noted in the first QA pass, not a real +discrepancy). Well under 600. + +**opentitan, read-only, re-confirmed** against a freshly rebuilt release +binary (the rework included): `entropy_masking_req` from `aes.sv` still +lists `aes_bind.sv` (6 locations); `state_q` from `entropy_src_main_sm.sv` +still lists `entropy_src_core.sv` (5 locations); the `hw/ip/aes/rtl` census +(948 declarations, 40 files) is byte-identical to the pre-rework run (15 +cross-file, 933 single-file, 0 errors). `git -C +/Users/guoliangchen/repo/opentitan status --short` identical before and +after (the same three pre-existing dirty files). + +**Verdict: rework needed, again — one new finding, findings 1–3 confirmed +fixed.** The rework correctly closes findings 1–3: re-derived by hand, +attacked further (a use-only shift, a deleted file, a UTF-8 boundary, two +independent closed files, both escaped-identifier shapes) and every one of +those held. But the same underlying class of bug — a stale span rendered +against text it was never checked against — has one more instance the +rework did not cover: the open-buffer path's `include_declaration` +fallback (Finding 4, above). Recommend fixing Finding 4 the same way +findings 2–3 were fixed (apply `spells_exactly`, or drop the fallback to +`target.declaration_span` entirely for an open file) before this ships. + +### 2026-09-12 — QA, final (escalated, task-d8afe80f, same worktree) + +Charter: verify the dev's rework 2 (finding 4) end to end, do not redesign. +No production code touched; five `qa_final_*` tests added to `nav.rs`'s +`mod tests`, nothing else in the tree changed by this pass. + +**1. The flipped finding-4 test, re-derived by hand.** Fixture +`hierarchical(.., &["single.sv", "leaf.sv"])`, asked from `single.sv`'s +`u_leaf.sig` tail. `Workspace::set_document` re-analyses the buffer against +the *unchanged* index (`Document::new(path, text, &self.index)`) and never +touches the index, so the setup is a real unsaved rename: the persisted `Def` +for `(leaf, sig)` survives and `single.sv`'s external target still resolves +to it. Walk: `leaves_this_file` → the tail's `best()`; `indexed_target` → +`Definition::External([def])`, `declaration_span` = the index-time +line 1 cols 8..11 (bytes 64..67); `references_to` posts `top.sv`'s closed +tail; the open loop finds `single.sv`'s tail and nothing named `sig` in the +renamed `leaf.sv`; `declaring_file_uses` declines (open); `declaration_site`: +`symbols_named("sig")` empty → fallback, `spells_exactly` on bytes 64..67 of +` logic sig2;` = `sig` followed by `2` (a name character) → `false` → `None`. +Rendered: `[single.sv 3, top.sv 3]`. That is the honest omission: the +declaration dropped, both tails unchanged (`top.sv`'s through its own closed +guard). `leaf.sv 2` is also absent, and correctly so — the live buffer's own +use spells `sig2`, so it is the overlay's answer, not the guard's. The +sanity assertion (`every_place_naming_sig` before the rename) pins that the +same request was complete when the buffer matched the disk. + +The control (`an_open_buffer_edited_above_its_declaration_reports_the_live_declaration_line`) +does discriminate: the index-time bytes 64..67 fall inside the *header* +line of the shifted text (`...input logic clk_i);` cols 46..49 = `c c`), +which spells no `sig` — so had the fallback been consulted the guard would +have dropped line 3, and had it been consulted unguarded line 2 would have +appeared; the asserted `(3, 8..11)` can only come from the live-symbol path. +Confirmed. + +**2. The ladder, rung by rung.** Existing tests cover (a) the control, +(c)-prefix the flipped finding-4 test, (e) `qa_finding_1/2`, (f) +`qa_finding_3` and `qa_a_stale_span_that_now_spells_a_longer_name_is_dropped`. +Added, all derived by hand first and green on the first run: + +- `qa_final_b_a_failed_live_lookup_with_the_name_still_in_place_emits_the_index_span` + — rung (b). `logic sig;` → `wire sig;` (same length; `Var` → `Net`, + `bind/decl.rs:179`), so the live lookup fails on `indexed_def_in_file`'s + kind filter while bytes 64..67 still read exactly `sig`. Emitted at + `(1, 8..11)`; the answer is `[leaf.sv 1, single.sv 3, top.sv 3]` (the + buffer's own use resolves to the rejected live symbol and is consistently + not listed); `includeDeclaration: false` → `[single.sv 3, top.sv 3]`. + The missing `leaf.sv 2` is what proves the fallback, not the live path, + produced line 1. +- `qa_final_c_an_index_span_now_a_suffix_of_a_longer_live_name_is_dropped` + — rung (c), suffix half: `wire _sig;` puts `_` at byte 63. Dropped; + `leaf.sv` absent. +- `qa_final_d_an_open_buffers_span_off_a_utf8_boundary_is_dropped_without_a_panic` + — rung (d): line 1 becomes ` // 🙂🙂` so byte 64 is the last byte of the + first emoji (`!is_char_boundary(64)` asserted), declaration renamed away + below. No panic (`str::get`), `leaf.sv` absent. +- `qa_final_g_include_declaration_false_emits_no_declaration_on_the_closed_rungs` + — rung (g) over (e) and (f), before and after the `LEAF_MOVED` disk edit: + `sig` → `[2]` / `[4, 5]` with, `[5]` without; `clk_i` → `[2]` / `[0]` + with, `[]` without. The open rungs are pinned by the control and rung (b). +- Rung (e) "guarded once, not twice": by inspection, `declaration_site`'s + closed branch (`nav.rs:388`) returns `declaring.declaration` or the + index-time span with no check, and the single check is + `closed_locations` (`nav.rs:581–584`); `locations` is unchanged by the + rework. Empirically `qa_finding_2` shows a re-analysed live declaration + emitted where the index-time span would have failed the guard. + +**Observation (not a finding — pinned as +`qa_final_observation_a_different_exact_sig_at_the_old_bytes_is_reported` +for the lead to rule on).** The fallback is a textual claim, on an open +buffer exactly as on a closed file: with the declaration deleted and an +unrelated whole token `sig` (`buf b(sig, clk_i);`, an undeclared gate output) +now sitting at bytes 64..67, `references` reports `(1, 8..11)` as the +declaration. `spells_exactly` is right to accept an exact token; whether it +*is* the declaration is a question the guard was never designed to answer, +and it is the same limit the closed path has had since rework 1. Accepting +it as documented behaviour seems right; recording it so it is chosen, not +overlooked. + +**3. `nav.rs` production read, whole file.** 433 production lines (non-blank, +non-comment, before `mod tests` at line 721; matches the dev's count). +No `unwrap`/`expect`/`panic!`/`unreachable!` in production. Function sizes: +`indexed_references` **71** (over 50, under 80 — the collection loop with +its comment block; report, not a finding), `definition` **52** (pre-existing, +untouched by this lane — no hunk in 19–70), every other function 3–35 +(`declaration_site` 19, `declaring_file_uses` 29, `locations` 35, +`closed_locations` 22). Doc comments say what/why throughout; +`declaration_site`'s names the finding it closes. + +**4. Gates**, verbatim, all through `tools/guard.sh`, no kill: + +``` +$ tools/guard.sh -m 8 -t 900 -- cargo fmt --all -- --check +(exit 0 after one `cargo fmt --all` reflow of a single new-test assert_eq!) + +$ tools/guard.sh -m 10 -t 1200 -- cargo clippy --all-targets + Finished `dev` profile [unoptimized + debuginfo] target(s) in 4.10s +(exit 0; 0 warnings) + +$ tools/guard.sh -m 10 -t 1800 -- cargo test --workspace + Doc-tests vlog_semantic +running 0 tests +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s +(exit 0; 60 `test result: ok` lines, summed: 4459 passed, 0 failed) +``` + +Test counts: 4454 (dev's rework-2 count) → **4459** (+5 `qa_final_*`); +`nav.rs`'s `mod tests` 80 `#[test]` items. + +**opentitan, read-only**, a trimmed two-row driver over +`tools/perf/lspclient.py` (`didOpen` + `references` only) against a +release binary built from this tree (0-based lines): + +| row | includeDeclaration | answer | +|---|---|---| +| `entropy_masking_req` from `aes.sv` | true | `aes.sv [88 136 139 202]`, `aes_bind.sv [44 53]` | +| | false | `aes.sv [136 139 202]`, `aes_bind.sv [44 53]` | +| `state_q` from `entropy_src_main_sm.sv` | true | `entropy_src_core.sv [3091]`, `entropy_src_main_sm.sv [41 45 48 59]` | +| | false | `entropy_src_core.sv [3091]`, `entropy_src_main_sm.sv [45 48 59]` | + +Identical to the dev's 1-based table; `false` drops exactly the declaration +line. `git -C /Users/guoliangchen/repo/opentitan status --short` before and +after: the same three pre-existing dirty files (`hw/ip/aes/dv/tb/tb.sv`, +`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`), +`diff` empty. + +**Verdict: pass.** Finding 4 is closed by `declaration_site`; every rung of +the declaration-site ladder behaves as specified and is pinned; no new +finding. One observation for the lead above. + + +## Review + +**Lead review, 2026-09-12 — accepted.** The diagnosis is the right one and +the fix is the smallest true one: both index questions in `nav.rs` now ask +the surface a *use* can reach a declaration by, and because the hierarchical +read returns the connection records first and whole, nothing the gate +admitted before is judged differently — the harness controls and the +opentitan census bear that out. The consequential gap the lead raised (no +`Local` posting for a hierarchical-only member, so a closed declaring file's +own uses were nobody's to supply) is served the way the rename already +serves it, by one parse of exactly that file on exactly that request shape, +and `hierarchical_only` asks the index's own table rather than restating +`surface_of` in the protocol layer. Two QA rounds earned their keep: the +first found that the closed-file path read a cached text and rendered +against a fresh one — this lane's own defect — and a pre-existing class of +unguarded index-time spans that §64.1 multiplied the reach of; the second, +after the one-read-per-file rule and the `spells_exactly` guard, found the +same class on the open-buffer declaration fallback. All four are closed by +one principle the README now states: a stale index may omit a location, +never point at a wrong one. Accepted as-is, with the reason written down: +the +25 % on a local-net `references` in a 40 000-line buffer (1.22 → 1.54 +ms; the gate still saves the walk for names the index holds nowhere), and +QA's final observation that the guard is textual — a *different* exact +`sig` token at the old bytes of a deleted declaration is reported as the +declaration. That is the same limit `hover-declarations` has carried since +2026-08-27, it needs an external edit the client's file watcher would have +announced, and the alternative (drop the index-time fallback for an open +buffer altogether) would lose the one honest case QA also pinned, a +declaration whose kind changed in place. `spells_exactly` made `pub(crate)` +rather than copied is the right call. Handshake request recorded (a +`Def`-keyed `hierarchical_only` on the index) and left for the next lane in +`index.rs`. Ships in 0.55.0. diff --git a/docs/features/references-nav/README.md b/docs/features/references-nav/README.md index 17aaa40..13eadb0 100644 --- a/docs/features/references-nav/README.md +++ b/docs/features/references-nav/README.md @@ -22,13 +22,35 @@ predicate, and three handlers. - **The workspace index is the authority on what can be named from another file.** `nav::leaves_this_file` decides whether a references request walks - the workspace by asking `WorkspaceIndex::units` / `::member` about the name - under the cursor — not by re-deriving `is_unit`/`is_exported`, which are - private to `vlog_semantic` and would be language knowledge in the protocol - layer. Consequence: a declaration the index has not seen yet (a buffer - edited but not saved, when the file is new) is answered in-file until the - next rebuild. That is the same staleness window every other cross-file - answer already has, documented in `docs/features/lucisv-server/README.md`. + the workspace by asking `WorkspaceIndex::units` / `::member_in(…, + Surface::Hierarchical)` about the name under the cursor — not by re-deriving + `is_unit`/`is_exported`, which are private to `vlog_semantic` and would be + language knowledge in the protocol layer. **The surface matters** (amended + 2026-09-12, §64.1): the question is which declarations a *use* in another + file can reach, and a hierarchical path may name anything a module declares + (IEEE 1800 §23.6) where a connection list may name only its ports and + parameters (§23.3). Asking `::member` — the connection surface — was what + made `assign w = u_x.sig;` in another file invisible to `references` while + a rename was already editing it. The connection answer is the first, whole + part of the hierarchical one, so nothing else moved; see + `docs/features/references-hierarchical-surface/README.md`. Consequence: a + declaration the index has not seen yet (a buffer edited but not saved, when + the file is new) is answered in-file until the next rebuild. That is the + same staleness window every other cross-file answer already has, documented + in `docs/features/lucisv-server/README.md`. +- **A stale index can omit a location; it can never point at a wrong one** + (added 2026-09-12, §64.1 rework, QA findings 1–3). Until then this feature's + staleness story stopped at the sentence above, which undersold it: a span + recorded at index time and rendered against a **closed** file's current + bytes — a `references_to` posting, or the `include_declaration` fallback — + had no agreement check, so an external edit to that file (another tool, + `git checkout`, a build step: none of the five events that drop a cached + view) could put a true-looking `Location` on a line that no longer holds the + name. `nav::closed_locations` now applies `hover::spells_exactly` to every + closed-file span before emitting it and drops the ones that no longer spell + the target's name — the same guarantee `hover-declarations` gives a snippet. + Open buffers are not guarded and pay nothing: their spans come from the very + text they are rendered against. - **A references answer is an indexed lookup.** Each `FileFacts` record stores compact facts for references to externally reachable declarations. The finished `WorkspaceIndex` resolves those facts once into declaration-to-use @@ -230,6 +252,33 @@ decision. ## Work log +### 2026-09-12 — dev (TODO §64.1: the gate asks the hierarchical surface) + +`leaves_this_file` and `indexed_def_in_file` — this feature's two index +questions — asked `WorkspaceIndex::member`, the **connection** surface. Since +`hierarchical-tail` (0.45.0) a module's net, variable and instance live on the +**hierarchical** surface only, so both functions judged such a declaration +unable to leave its file: `references` from the declaration fell to the +single-file answer and never saw a cross-file `u_x.sig` tail or a `bind` +connection expression, and a request that *did* go cross-file could not +re-identify the declaring buffer's own in-file uses. Both now ask +`member_in(owner, name, Surface::Hierarchical)`. Every connection-surface +answer is byte-identical (the connection records come first and whole from +that read); the `nav` harness rows are unchanged in count and within noise in +time. The closed-declaring-file half of the completeness problem, the new +`nav::declaring_file_uses`, the fixture sweep and the attack cases are all +written up in `docs/features/references-hierarchical-surface/README.md`, which +is this change's feature README. `documentHighlight`'s "a document answer even +for a cross-file name" assumption was untouched and is now pinned from both +ends (`definition_and_document_highlight_over_a_hierarchical_tail_are_unchanged`). + +**Rework the same day**, on QA's findings 1–3: the closed-file path reads each +closed file exactly once per request, with `text_of` rather than the +`file_view` cache, and every index-time span about a closed file is guarded by +`hover::spells_exactly` before it is rendered. That is the new Assumptions +bullet above; the derivation and the flipped QA tests are in +`docs/features/references-hierarchical-surface/README.md`. + ### 2026-08-28 — documentHighlight answered nothing on a cross-file name **The report.** `performance.md` §7: `documentHighlight` returned 0 results at diff --git a/docs/perf/README.md b/docs/perf/README.md index 47171c6..557e355 100644 --- a/docs/perf/README.md +++ b/docs/perf/README.md @@ -1390,3 +1390,36 @@ is read for comments), `analyze` (9.4 ms), `resolve_external` (4.7 ms), and ~6 ms dropping the previous revision's products on the request path. `docs/features/perf-first-after-edit/README.md`; evidence `~/.cache/lucisv-perf/63-2/`. +### 2026-09-12 — loop 3, round 2 (TODO §64) + +**§64.1 is a correctness lane, not a performance one**, recorded here +because it moves one harness row on purpose. `textDocument/references` +now judges a declaration's cross-file reach on the **hierarchical** +surface (`nav::leaves_this_file` / `indexed_def_in_file` ask +`member_in(…, Surface::Hierarchical)` instead of `member`), so a module's +net, variable or instance — which a `bind` connection or a `u_x.sig` +tail names from another file — is answered workspace-wide instead of +silently in-file. Two costs, both measured on the real opentitan tree: + +- **A local net's `references` in a 40 267-line open buffer** now walks + the indexed path (two map probes plus the name-prefiltered pass over + open buffers) instead of returning the in-file answer directly: + **1.22 → 1.54 ms median** (QA, throwaway worktree at 9d1eb16 for the + before). Accepted: the gate still saves the walk for every name the + index holds nowhere. +- **A cross-file request into a *closed* declaring file** (the shape that + used to answer incompletely) parses exactly that file once, fresh from + disk: 0.1–0.2 ms → **0.4–1.5 ms** on `state_q` from + `entropy_src_core.sv` with `entropy_src_main_sm.sv` shut — the price + of the in-file uses that answer used to omit. The index deliberately + posts no `Local` reference for a hierarchical-only member (the §49 + ruling: a reference table sized by every RTL body for a rarely-asked + answer), so the one-file re-analysis is the same trade the rename + already makes. + +Every connection-surface row of the `nav` harness is unchanged in result +count and within noise in time (`aes` 14 locations / 9 files, `.clk_i` +12 / 9). Every closed-file span is now guarded by `hover::spells_exactly` +before it is rendered — one slice compare per location, unmeasurable — +so a stale index can omit a location but never point at a wrong line +(QA findings 1–4). `docs/features/references-hierarchical-surface/README.md`. diff --git a/docs/topo.md b/docs/topo.md index 46824a7..c9905ce 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -628,7 +628,7 @@ engine-lane features are listed above; this table is the server-internal web. | `on-type-formatting ──▶ range-formatting, editor-scopes` | depends | `;` goes through `format::range_formatting` unchanged; `\n` answers indent only, computed from `pairs.rs`'s own keyword tables (three items widened to `pub(crate)`) — one reader's answer for "what opens a scope". | | `interactive-latency ──▶ change-debounce, editor-scopes, selection-range, on-type-formatting, completion-core, inline-templates` | depends | Round 2 of the perf work (`docs/perf/README.md`). It measures the flush change-debounce coalesces and the round trip it defers, and it replaces one token *sweep* with one token *binary search* in `selection.rs`, `on_type.rs`, `completion.rs` and `inline.rs`. No answer moved — each swap is pinned against the sweep it replaced at every byte — so none of those five features' contracts changed; what they now share is `state.rs`'s two search primitives and the ordering property of `tokenize`'s output they rest on. | | `interactive-latency ◀──▶ lucisv-server` | handshake | Two free functions, `first_token_reaching` and `first_token_from`, are published from `state.rs` beside `Document::token_at`; that is where the monotonicity argument every caller depends on is written down, and `state::tests::the_token_stream_rises_and_never_overlaps` is the test that fails first if `vlog_parser` ever breaks it. `tests/e2e.rs`'s `Live::finish` now returns its publish count (existing callers ignore it), and `perf::generated_module` has a copy in `tests/e2e.rs` — a binary crate's modules are unreachable from an integration test — which must stay the same shape as the original. | -| `references-nav ──▶ workspace-index / hover-line-index` | depends | Cross-file references resolve an indexed target first and consume declaration postings directly; same-file local references stay on `Semantics`. Locations use the shared `FileView`. `documentHighlight` now also follows the document's external overlay for names declared elsewhere, fixing the old “references works, highlight is empty” split without widening highlights beyond the current file. | +| `references-nav ──▶ workspace-index / hover-line-index` | depends | Cross-file references resolve an indexed target first and consume declaration postings directly; same-file local references stay on `Semantics`. Since §64.1 (2026-09-12) the two index questions (`leaves_this_file`, `indexed_def_in_file`) ask `member_in(…, Surface::Hierarchical)`, so a module's net/variable/instance named by a `bind` connection or a `u_x.sig` tail is answered workspace-wide; a hierarchical-only declaration in a *closed* file has no `Local` postings, so `nav::declaring_file_uses` parses exactly that file once per request. Every closed-file span and the open-buffer declaration fallback are guarded by `hover::spells_exactly` (now `pub(crate)`): a stale index may omit a location, never mislocate one. Locations for closed files are rendered from one `text_of` read per file per request (not the `FileView` cache, whose entry could differ from the same request's re-analysis). `documentHighlight` now also follows the document's external overlay for names declared elsewhere, fixing the old “references works, highlight is empty” split without widening highlights beyond the current file. | | `selection-range / linked-editing ──▶ spans, name-spans` | depends | Pure arrangements of existing ranges; linked-editing's table documents exactly which constructs carry both spans (and which verbatim ones can't — `program`, property/sequence, covergroup). | | `type-definition ──▶ nav / overlay-promotion / ansi-first-port` | depends + 2 delivered handshakes | Now literally `nav::definition` at the type name's offset; both of its filed requests landed (§2.2, §2.5). | | `hierarchy ◀──▶ inlay-hints` | handshake (shared walk) | The instantiation walk was lifted out of `inlay.rs` into a shared module (now `vlog_semantic::instantiations`) rather than copied — the two answers cannot drift; inlay's 34 tests are the regression net. |