prepareRename answered F2 by reading every in-scope file (1.6-3.0 s on opentitan, blocking the loop); it now answers from the open buffer and the index in 139 ns, with a refusal-by-refusal parity table (7 reproduced, 4 deferred to rename, none lost). rename computes over rename_sources — declarers, reference postings, open buffers, and, after QA's HIGH finding gated the round, rung 6: files_spelling over the index's reference facts (resolved or not, FACTS_FORMAT untouched), restoring the dangling-new-name capture refusal the first five rungs lost; the old name needs no rung and the argument is written and pinned, QA's shadowing hunt included. 3.47 s -> 105 ms at a 7-file fan-out, rung cost 852 us worst-case, byte-parity swept at four real cursors and 564 offsets, ambiguity escaping to the whole scope. willRenameFiles rides IncludeGraph::includers(): 249 ms -> 14 ms over 331 includers of 3 976 files. Accepted residue, documented: files whose only mention of the name is inside opaque macro tokens lose one warning flavour; the FileFacts macro census is filed as the real fix. Dev Opus + QA Sonnet (REWORK-gate, fix, SHIP on re-verify) in a dedicated worktree. Lead-reviewed and merged. Co-Authored-By: Claude Fable 5 <[email protected]>
2122 lines
91 KiB
Rust
2122 lines
91 KiB
Rust
//! Behavior of the workspace index: cross-file definitions, duplicate names,
|
||
//! package members, and the corpus acceptance run.
|
||
|
||
use std::path::{Path, PathBuf};
|
||
use vlog_parser::defines::{collect_defines, DefineTable};
|
||
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize};
|
||
use vlog_semantic::{
|
||
analyze, resolve_external, Def, Definition, ExternalTarget, FileFacts, FileId, Resolution,
|
||
Semantics, SymbolKind, WorkspaceIndex,
|
||
};
|
||
|
||
/// Build an index from `(path, source)` literals, as a server would from disk.
|
||
fn index(files: &[(&str, &str)]) -> WorkspaceIndex {
|
||
WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(*p), *s)))
|
||
}
|
||
|
||
fn semantics(src: &str) -> Semantics {
|
||
let (file, _) = parse_source_tolerant(src);
|
||
analyze(&file, src)
|
||
}
|
||
|
||
/// The workspace declarations go-to-definition offers for `needle` — the
|
||
/// composed query, so a local hit deliberately yields no external defs.
|
||
fn external_defs(sem: &Semantics, ws: &WorkspaceIndex, src: &str, needle: &str) -> Vec<Def> {
|
||
let offset = src.find(needle).expect("needle is in the source") as u32;
|
||
let overlay = resolve_external(sem, ws);
|
||
match overlay.definition_of(sem, offset) {
|
||
Some(Definition::External(defs)) => defs.to_vec(),
|
||
_ => Vec::new(),
|
||
}
|
||
}
|
||
|
||
/// The name a `Def` points at, read back out of the file it names.
|
||
fn slice<'a>(ws: &WorkspaceIndex, sources: &[(&str, &'a str)], def: &Def) -> &'a str {
|
||
let path = ws.path(def.file).expect("file id is in the index");
|
||
let src = sources
|
||
.iter()
|
||
.find(|(p, _)| std::path::Path::new(*p) == path)
|
||
.expect("indexed path came from the sources")
|
||
.1;
|
||
&src[def.name_span.as_range()]
|
||
}
|
||
|
||
// ----------------------------------------------------------------------
|
||
// Cross-file definitions
|
||
// ----------------------------------------------------------------------
|
||
|
||
#[test]
|
||
fn an_instantiation_resolves_to_the_module_in_another_file() {
|
||
let sources = [
|
||
("a.sv", "module top; sub u_sub (.clk_i(w)); wire w; endmodule\n"),
|
||
("b.sv", "module sub (input clk_i); endmodule\n"),
|
||
];
|
||
let ws = index(&sources);
|
||
let sem = semantics(sources[0].1);
|
||
|
||
let defs = external_defs(&sem, &ws, sources[0].1, "sub u_sub");
|
||
assert_eq!(defs.len(), 1);
|
||
assert_eq!(defs[0].kind, SymbolKind::Module);
|
||
assert_eq!(ws.path(defs[0].file).unwrap(), PathBuf::from("b.sv"));
|
||
assert_eq!(slice(&ws, &sources, &defs[0]), "sub");
|
||
}
|
||
|
||
#[test]
|
||
fn a_named_connection_resolves_to_the_port_in_the_other_file() {
|
||
let sources = [
|
||
("a.sv", "module top; sub u_sub (.clk_i(w)); wire w; endmodule\n"),
|
||
("b.sv", "module sub (input clk_i); endmodule\n"),
|
||
];
|
||
let ws = index(&sources);
|
||
let sem = semantics(sources[0].1);
|
||
|
||
let defs = external_defs(&sem, &ws, sources[0].1, "clk_i(w)");
|
||
assert_eq!(defs.len(), 1, "the port of an external module resolves");
|
||
assert_eq!(defs[0].kind, SymbolKind::Port);
|
||
assert_eq!(slice(&ws, &sources, &defs[0]), "clk_i");
|
||
}
|
||
|
||
#[test]
|
||
fn an_internal_net_of_another_module_is_not_reachable() {
|
||
let sources = [
|
||
("a.sv", "module top; sub u (.secret(w)); wire w; endmodule\n"),
|
||
("b.sv", "module sub (input clk_i); wire secret; endmodule\n"),
|
||
];
|
||
let ws = index(&sources);
|
||
let sem = semantics(sources[0].1);
|
||
assert!(external_defs(&sem, &ws, sources[0].1, "secret(w)").is_empty());
|
||
}
|
||
|
||
#[test]
|
||
fn a_wildcard_import_reaches_into_the_packages_file() {
|
||
let sources = [
|
||
("defs.sv", "package cfg_pkg;\n localparam int WIDTH = 8;\n typedef logic [1:0] mode_e;\nendpackage\n"),
|
||
("use.sv", "import cfg_pkg::*;\nmodule m;\n wire [WIDTH-1:0] bus;\n mode_e mode;\nendmodule\n"),
|
||
];
|
||
let ws = index(&sources);
|
||
let sem = semantics(sources[1].1);
|
||
|
||
let width = external_defs(&sem, &ws, sources[1].1, "WIDTH-1");
|
||
assert_eq!(width.len(), 1);
|
||
assert_eq!(width[0].kind, SymbolKind::Param);
|
||
assert_eq!(slice(&ws, &sources, &width[0]), "WIDTH");
|
||
|
||
let mode = external_defs(&sem, &ws, sources[1].1, "mode_e mode");
|
||
assert_eq!(mode.len(), 1);
|
||
assert_eq!(mode[0].kind, SymbolKind::Typedef);
|
||
}
|
||
|
||
#[test]
|
||
fn an_explicit_import_reaches_only_the_name_it_names() {
|
||
let sources = [
|
||
("defs.sv", "package cfg_pkg;\n localparam int WIDTH = 8;\n localparam int DEPTH = 4;\nendpackage\n"),
|
||
("use.sv", "import cfg_pkg::WIDTH;\nmodule m;\n wire [WIDTH-1:0] a;\n wire [DEPTH-1:0] b;\nendmodule\n"),
|
||
];
|
||
let ws = index(&sources);
|
||
let sem = semantics(sources[1].1);
|
||
|
||
assert_eq!(external_defs(&sem, &ws, sources[1].1, "WIDTH-1").len(), 1);
|
||
assert!(
|
||
external_defs(&sem, &ws, sources[1].1, "DEPTH-1").is_empty(),
|
||
"an explicit import does not drag the rest of the package in"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn a_package_scoped_name_resolves_across_files() {
|
||
let sources = [
|
||
("defs.sv", "package cfg_pkg;\n localparam int WIDTH = 8;\n function int f(); return 1; endfunction\nendpackage\n"),
|
||
("use.sv", "module m;\n wire [cfg_pkg::WIDTH-1:0] bus;\n initial x = cfg_pkg::f();\nendmodule\n"),
|
||
];
|
||
let ws = index(&sources);
|
||
let sem = semantics(sources[1].1);
|
||
|
||
let head = external_defs(&sem, &ws, sources[1].1, "cfg_pkg::WIDTH");
|
||
assert_eq!(head.len(), 1, "the package head resolves to the package");
|
||
assert_eq!(head[0].kind, SymbolKind::Package);
|
||
|
||
let tail = external_defs(&sem, &ws, sources[1].1, "WIDTH-1");
|
||
assert_eq!(tail.len(), 1);
|
||
assert_eq!(tail[0].kind, SymbolKind::Param);
|
||
assert_eq!(slice(&ws, &sources, &tail[0]), "WIDTH");
|
||
|
||
let func = external_defs(&sem, &ws, sources[1].1, "f()");
|
||
assert_eq!(func.len(), 1);
|
||
assert_eq!(func[0].kind, SymbolKind::Function);
|
||
}
|
||
|
||
#[test]
|
||
fn an_enum_variant_declared_in_a_package_is_a_member_of_it() {
|
||
let sources = [
|
||
("defs.sv", "package st_pkg;\n typedef enum logic { IDLE, BUSY } state_e;\nendpackage\n"),
|
||
("use.sv", "import st_pkg::*;\nmodule m;\n assign s = BUSY;\nendmodule\n"),
|
||
];
|
||
let ws = index(&sources);
|
||
let sem = semantics(sources[1].1);
|
||
|
||
let defs = external_defs(&sem, &ws, sources[1].1, "BUSY;");
|
||
assert_eq!(defs.len(), 1);
|
||
assert_eq!(defs[0].kind, SymbolKind::EnumVariant);
|
||
assert_eq!(slice(&ws, &sources, &defs[0]), "BUSY");
|
||
}
|
||
|
||
#[test]
|
||
fn a_name_the_workspace_does_not_declare_stays_unresolved() {
|
||
let sources = [(
|
||
"use.sv",
|
||
"import nowhere_pkg::*;\nmodule m;\n wire [W-1:0] a;\n absent_mod u ();\nendmodule\n",
|
||
)];
|
||
let ws = index(&sources);
|
||
let sem = semantics(sources[0].1);
|
||
let overlay = resolve_external(&sem, &ws);
|
||
|
||
assert!(external_defs(&sem, &ws, sources[0].1, "W-1").is_empty());
|
||
assert!(external_defs(&sem, &ws, sources[0].1, "absent_mod u").is_empty());
|
||
let (answered, total) = overlay.counts();
|
||
assert_eq!(answered, 0);
|
||
assert!(total > 0, "the file does have external candidates");
|
||
assert!(overlay.iter().all(|(_, t)| matches!(t, ExternalTarget::StillUnresolved)));
|
||
}
|
||
|
||
// ----------------------------------------------------------------------
|
||
// Duplicates and ordering
|
||
// ----------------------------------------------------------------------
|
||
|
||
#[test]
|
||
fn a_module_declared_in_two_files_is_ambiguous_in_path_order() {
|
||
let sources = [
|
||
("z_late.sv", "module dup (input a); endmodule\n"),
|
||
("a_early.sv", "module dup (input b); endmodule\n"),
|
||
("use.sv", "module top; dup u (); endmodule\n"),
|
||
];
|
||
let ws = index(&sources);
|
||
let sem = semantics(sources[2].1);
|
||
let overlay = resolve_external(&sem, &ws);
|
||
|
||
let offset = sources[2].1.find("dup u").unwrap() as u32;
|
||
let id = sem.reference_id_at(offset).unwrap();
|
||
let target = overlay.get(id).unwrap();
|
||
match target {
|
||
ExternalTarget::Ambiguous(defs) => {
|
||
assert_eq!(defs.len(), 2);
|
||
assert_eq!(ws.path(defs[0].file).unwrap(), PathBuf::from("a_early.sv"));
|
||
assert_eq!(ws.path(defs[1].file).unwrap(), PathBuf::from("z_late.sv"));
|
||
}
|
||
other => panic!("expected Ambiguous, got {other:?}"),
|
||
}
|
||
assert_eq!(target.best().unwrap().file, FileId(0), "the first path sorts first");
|
||
// Both are still offered to the editor, and both really name `dup`.
|
||
for def in target.defs() {
|
||
assert_eq!(slice(&ws, &sources, def), "dup");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn file_ids_follow_the_sorted_paths_whatever_order_they_arrive_in() {
|
||
let forward = index(&[("a.sv", "module a; endmodule\n"), ("b.sv", "module b; endmodule\n")]);
|
||
let backward = index(&[("b.sv", "module b; endmodule\n"), ("a.sv", "module a; endmodule\n")]);
|
||
assert_eq!(forward.files(), backward.files());
|
||
assert_eq!(forward.units("a"), backward.units("a"));
|
||
assert_eq!(forward.units("a")[0].file, FileId(0));
|
||
assert_eq!(forward.units("b")[0].file, FileId(1));
|
||
}
|
||
|
||
// ----------------------------------------------------------------------
|
||
// Robustness
|
||
// ----------------------------------------------------------------------
|
||
|
||
#[test]
|
||
fn a_broken_file_still_contributes_what_parsed() {
|
||
let sources = [
|
||
("broken.sv", "module good_mod (input clk); endmodule\n@@@ !! not verilog !!\npackage good_pkg; localparam int K = 1; endpackage\n"),
|
||
("use.sv", "module top; good_mod u (); wire [good_pkg::K-1:0] w; endmodule\n"),
|
||
];
|
||
let ws = index(&sources);
|
||
let (_, diags) = parse_source_tolerant(sources[0].1);
|
||
assert!(!diags.is_empty(), "the fixture really does fail to parse");
|
||
|
||
assert_eq!(ws.units("good_mod").len(), 1);
|
||
let sem = semantics(sources[1].1);
|
||
let defs = external_defs(&sem, &ws, sources[1].1, "good_pkg::K");
|
||
assert_eq!(defs.len(), 1, "declarations after the error node still index");
|
||
}
|
||
|
||
#[test]
|
||
fn an_empty_workspace_answers_nothing_and_panics_nowhere() {
|
||
let ws = WorkspaceIndex::build(Vec::<(PathBuf, &str)>::new());
|
||
assert!(ws.files().is_empty());
|
||
assert!(ws.units("anything").is_empty());
|
||
assert!(ws.member("p", "x").is_empty());
|
||
assert!(ws.workspace_symbols("").is_empty());
|
||
assert!(ws.find_define("WIDTH").is_empty());
|
||
assert!(ws.path(FileId(0)).is_none());
|
||
assert!(ws.defines(FileId(7)).is_none());
|
||
|
||
let src = "module m; other u (); endmodule\n";
|
||
let sem = semantics(src);
|
||
let overlay = resolve_external(&sem, &ws);
|
||
assert_eq!(overlay.counts().0, 0);
|
||
let on_the_module_name = src.find("m;").unwrap() as u32;
|
||
assert!(
|
||
overlay.definition_of(&sem, on_the_module_name).is_some(),
|
||
"the local layer still answers with no workspace at all"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn rebuilding_after_an_edit_reflects_the_edit() {
|
||
let before = index(&[("p.sv", "package p; localparam int OLD = 1; endpackage\n")]);
|
||
assert!(!before.member("p", "OLD").is_empty());
|
||
assert!(before.member("p", "NEW").is_empty());
|
||
|
||
let after = index(&[("p.sv", "package p; localparam int NEW = 2; endpackage\n")]);
|
||
assert!(after.member("p", "OLD").is_empty(), "a rebuild forgets the old text");
|
||
assert!(!after.member("p", "NEW").is_empty());
|
||
}
|
||
|
||
#[test]
|
||
fn the_same_path_twice_is_one_file() {
|
||
let src = "module m; endmodule\n";
|
||
let ws =
|
||
WorkspaceIndex::build(vec![(PathBuf::from("m.sv"), src), (PathBuf::from("m.sv"), src)]);
|
||
assert_eq!(ws.files().len(), 1);
|
||
assert_eq!(ws.units("m").len(), 1);
|
||
}
|
||
|
||
#[test]
|
||
fn the_incremental_builder_is_what_build_is_made_of() {
|
||
// `WorkspaceIndex::build` is now `index_order` plus a loop over
|
||
// `IndexBuilder`, so a caller that runs that loop itself — the server,
|
||
// which reports progress between two files — must get the same index down
|
||
// to the file ids. Every other test in this file goes through `build` and
|
||
// is the other half of the proof: if the two ever disagreed, they would
|
||
// all be wrong together.
|
||
let files = [
|
||
("z.sv", "package z;\n localparam K = 1;\nendpackage\n"),
|
||
("a.sv", "module a; endmodule\n"),
|
||
("a.sv", "module never_seen; endmodule\n"),
|
||
("m.sv", "module m; a u (); endmodule\n"),
|
||
];
|
||
let handed: Vec<(PathBuf, &str)> = files.iter().map(|(p, s)| (PathBuf::from(*p), *s)).collect();
|
||
|
||
// The work list, in the order the index is built in: sorted by path, the
|
||
// repeated `a.sv` folded into one — and knowable before any parsing, which
|
||
// is what makes a "37 of 200" progress report honest.
|
||
let ordered = vlog_semantic::index_order(handed.clone());
|
||
let names: Vec<&str> = ordered.iter().filter_map(|(p, _)| p.to_str()).collect();
|
||
assert_eq!(names, ["a.sv", "m.sv", "z.sv"], "sorted, and one entry per path");
|
||
|
||
let mut builder = vlog_semantic::IndexBuilder::new();
|
||
for (path, src) in ordered {
|
||
builder.add_file(path, src);
|
||
}
|
||
let built = builder.finish();
|
||
let whole = WorkspaceIndex::build(handed);
|
||
|
||
assert_eq!(built.files(), whole.files(), "same files, same file ids");
|
||
assert_eq!(built.counts(), whole.counts());
|
||
assert_eq!(built.units("a")[0], whole.units("a")[0], "the first copy of a.sv won, both ways");
|
||
assert!(built.units("never_seen").is_empty(), "and the second copy is gone");
|
||
assert_eq!(built.member("z", "K").len(), 1);
|
||
}
|
||
|
||
/// Everything an index holds, as text — [`WorkspaceIndex::fingerprint`].
|
||
///
|
||
/// Two indexes with the same fingerprint answer every query the same way; an
|
||
/// index whose file ids, whose duplicate-name order or whose edges moved has a
|
||
/// different one. It lives in the crate rather than here because
|
||
/// `lucisv_server` proves the same equivalence against the real corpus, and one
|
||
/// witness that both crates use cannot drift.
|
||
fn fingerprint(index: &WorkspaceIndex) -> String {
|
||
index.fingerprint()
|
||
}
|
||
|
||
/// One index built by adding `files` to an `IndexBuilder` in exactly the order
|
||
/// given — no `index_order` in sight, which is the whole point.
|
||
fn built_in_order(files: &[(&str, &str)]) -> WorkspaceIndex {
|
||
let mut builder = vlog_semantic::IndexBuilder::new();
|
||
for (path, src) in files {
|
||
builder.add_file(PathBuf::from(*path), src);
|
||
}
|
||
builder.finish()
|
||
}
|
||
|
||
#[test]
|
||
fn no_insertion_order_can_change_what_the_builder_produces() {
|
||
// The attack QA landed on the previous round (indexing-ux QA log,
|
||
// 2026-08-27, MEDIUM): `IndexBuilder` handed out `FileId`s in *call* order,
|
||
// so a caller that skipped `index_order` got a different index — different
|
||
// ids, and a different winner for a name two files declare. Both callers in
|
||
// the tree happened to be correct, which is exactly what makes it a footgun
|
||
// rather than a bug. It is closed by construction now: `finish` sorts, so
|
||
// this test is the permanent re-attack.
|
||
let files = [
|
||
("z_late.sv", "module dup (input a); endmodule\n"),
|
||
("a_early.sv", "module dup (input b); endmodule\n"),
|
||
("pkg/m_mid.sv", "package p;\n localparam K = 1;\n typedef int t;\nendpackage\n"),
|
||
("defs.svh", "`define W 8\n`define D 4\n"),
|
||
("cls.sv", "package q;\n class c;\n int x;\n endclass\nendpackage\n"),
|
||
];
|
||
let sorted = built_in_order(&files);
|
||
|
||
// Reversed, rotated, and the exact pair QA proved flipped the ids.
|
||
let mut reversed = files;
|
||
reversed.reverse();
|
||
let mut rotated = files;
|
||
rotated.rotate_left(3);
|
||
for (label, order) in [("reversed", reversed), ("rotated", rotated)] {
|
||
assert_eq!(
|
||
fingerprint(&built_in_order(&order)),
|
||
fingerprint(&sorted),
|
||
"{label}: the insertion order must not reach the result"
|
||
);
|
||
}
|
||
|
||
// And the same index `build` produces, since that is what every other test
|
||
// in this file exercises.
|
||
assert_eq!(fingerprint(&index(&files)), fingerprint(&sorted), "and `build` agrees");
|
||
|
||
// Named explicitly, because a fingerprint match is only as good as what it
|
||
// covers: the ids and the duplicate-name winner are the two things that
|
||
// moved before.
|
||
let winner = |ws: &WorkspaceIndex| ws.path(ws.units("dup")[0].file).map(Path::to_path_buf);
|
||
assert_eq!(winner(&sorted), Some(PathBuf::from("a_early.sv")), "sorted, not first-added");
|
||
assert_eq!(sorted.files()[0], PathBuf::from("a_early.sv"), "and FileId(0) with it");
|
||
}
|
||
|
||
#[test]
|
||
fn a_path_added_twice_is_one_file_whichever_end_the_duplicate_is_at() {
|
||
// `index_order`'s other half — one entry per path, the first copy wins —
|
||
// has to survive being applied inside `finish` instead of before the loop,
|
||
// including when the duplicate is *not* adjacent to the copy that wins.
|
||
let files = [
|
||
("a.sv", "module a; endmodule\n"),
|
||
("z.sv", "module z; endmodule\n"),
|
||
("a.sv", "module never_seen; endmodule\n"),
|
||
];
|
||
let ws = built_in_order(&files);
|
||
assert_eq!(ws.files(), [PathBuf::from("a.sv"), PathBuf::from("z.sv")], "two files, not three");
|
||
assert_eq!(ws.units("a").len(), 1, "the first copy won");
|
||
assert!(ws.units("never_seen").is_empty(), "the second is gone, not appended");
|
||
assert_eq!(fingerprint(&ws), fingerprint(&index(&files)), "exactly what `build` gives");
|
||
}
|
||
|
||
// ----------------------------------------------------------------------
|
||
// Queries
|
||
// ----------------------------------------------------------------------
|
||
|
||
#[test]
|
||
fn definition_of_prefers_the_in_file_declaration() {
|
||
let sources = [
|
||
("far.sv", "module sub (input clk_i); endmodule\n"),
|
||
("near.sv", "module sub (input clk_i); endmodule\nmodule top; sub u (); endmodule\n"),
|
||
];
|
||
let ws = index(&sources);
|
||
let sem = semantics(sources[1].1);
|
||
let overlay = resolve_external(&sem, &ws);
|
||
|
||
let offset = sources[1].1.find("sub u").unwrap() as u32;
|
||
match overlay.definition_of(&sem, offset) {
|
||
Some(Definition::Local(sym)) => {
|
||
assert_eq!(sym.name, "sub");
|
||
assert_eq!(sym.kind, SymbolKind::Module);
|
||
}
|
||
other => panic!("expected the local declaration, got {other:?}"),
|
||
}
|
||
assert!(
|
||
resolve_external(&sem, &ws).get(sem.reference_id_at(offset).unwrap()).is_none(),
|
||
"a locally resolved reference is not in the overlay at all"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn workspace_symbols_matches_names_case_insensitively() {
|
||
let ws = index(&[
|
||
("a.sv", "module prim_fifo_sync (input clk_i); endmodule\n"),
|
||
("b.sv", "package prim_pkg; localparam int FifoDepth = 4; endpackage\n"),
|
||
]);
|
||
|
||
let hits = ws.workspace_symbols("fifo");
|
||
let names: Vec<_> = hits.iter().map(|h| (h.name, h.container)).collect();
|
||
assert!(names.contains(&("prim_fifo_sync", None)));
|
||
assert!(names.contains(&("FifoDepth", Some("prim_pkg"))));
|
||
|
||
assert!(ws.workspace_symbols("zzz").is_empty());
|
||
assert!(ws.workspace_symbols("").len() >= 4, "an empty query matches everything");
|
||
// Sorted and stable.
|
||
let again = ws.workspace_symbols("fifo");
|
||
assert_eq!(names, again.iter().map(|h| (h.name, h.container)).collect::<Vec<_>>());
|
||
}
|
||
|
||
#[test]
|
||
fn members_of_lists_a_packages_exports() {
|
||
let ws = index(&[("p.sv", "package p;\n localparam int A = 1;\n typedef logic t;\n function int f(); return 1; endfunction\nendpackage\n")]);
|
||
let names: Vec<&str> = ws.members_of("p").map(|(n, _)| n).collect();
|
||
assert_eq!(names, vec!["A", "f", "t"], "sorted by name");
|
||
assert!(ws.members_of("nope").next().is_none());
|
||
}
|
||
|
||
#[test]
|
||
fn defines_are_indexed_per_file_and_findable_workspace_wide() {
|
||
let ws = index(&[
|
||
("defs.svh", "`define WIDTH 8\n`define MAX(a, b) ((a) > (b) ? (a) : (b))\n"),
|
||
("other.svh", "`define WIDTH 16\n"),
|
||
]);
|
||
|
||
let per_file = ws.defines(FileId(0)).expect("file 0 has a define table");
|
||
assert_eq!(per_file.latest("WIDTH").map(|d| d.body.as_str()), Some("8"));
|
||
assert_eq!(
|
||
per_file.latest("MAX").and_then(|d| d.params.clone()),
|
||
Some(vec!["a".into(), "b".into()])
|
||
);
|
||
|
||
// Both definitions are offered; no include graph exists to rank them.
|
||
let all = ws.find_define("WIDTH");
|
||
assert_eq!(all.len(), 2);
|
||
assert_eq!(all[0].0, FileId(0));
|
||
assert_eq!(all[1].0, FileId(1));
|
||
assert!(ws.find_define("NOPE").is_empty());
|
||
}
|
||
|
||
#[test]
|
||
fn counts_report_what_was_indexed() {
|
||
let counts = index(&[
|
||
("a.sv", "module m; endmodule\ntypedef logic [7:0] byte_t;\n"),
|
||
("b.sv", "`define D 1\npackage p; localparam int K = 1; endpackage\n"),
|
||
])
|
||
.counts();
|
||
assert_eq!(counts.files, 2);
|
||
assert_eq!(counts.modules, 1);
|
||
assert_eq!(counts.packages, 1);
|
||
assert_eq!(counts.typedefs, 1);
|
||
assert_eq!(counts.members, 1);
|
||
assert_eq!(counts.defines, 1);
|
||
}
|
||
|
||
// ----------------------------------------------------------------------
|
||
// Overlay promotion: unqualified misses reach the unit table
|
||
// (docs/features/overlay-promotion/README.md)
|
||
// ----------------------------------------------------------------------
|
||
|
||
/// The resolution the single-file layer gave the reference at `needle`.
|
||
fn resolution(sem: &Semantics, src: &str, needle: &str) -> Resolution {
|
||
let offset = src.find(needle).expect("needle is in the source") as u32;
|
||
sem.reference_at(offset).expect("a reference is written here").resolution.clone()
|
||
}
|
||
|
||
/// Whether the overlay holds any entry at all for the reference at `needle`.
|
||
fn in_overlay(sem: &Semantics, ws: &WorkspaceIndex, src: &str, needle: &str) -> bool {
|
||
let offset = src.find(needle).expect("needle is in the source") as u32;
|
||
let id = sem.reference_id_at(offset).expect("a reference is written here");
|
||
resolve_external(sem, ws).get(id).is_some()
|
||
}
|
||
|
||
#[test]
|
||
fn an_unqualified_type_miss_carries_its_own_name_to_the_unit_table() {
|
||
// An `interface` lives at file scope, never in a package, so nothing in
|
||
// the using file can bind its name and no import path can carry it. The
|
||
// bare name is the whole handshake.
|
||
let sources = [
|
||
("bus_if.sv", "interface bus_if;\nendinterface\n"),
|
||
("top.sv", "module top;\n bus_if bus;\nendmodule\n"),
|
||
];
|
||
let ws = index(&sources);
|
||
let sem = semantics(sources[1].1);
|
||
|
||
assert_eq!(
|
||
resolution(&sem, sources[1].1, "bus_if bus"),
|
||
Resolution::ExternalCandidate { paths: vec!["bus_if".to_string()] }
|
||
);
|
||
let defs = external_defs(&sem, &ws, sources[1].1, "bus_if bus");
|
||
assert_eq!(defs.len(), 1, "{defs:?}");
|
||
assert_eq!(slice(&ws, &sources, &defs[0]), "bus_if");
|
||
assert_eq!(defs[0].kind, SymbolKind::Module, "an interface is a Module symbol");
|
||
}
|
||
|
||
#[test]
|
||
fn a_package_less_class_and_a_file_scope_typedef_are_reached_the_same_way() {
|
||
let sources = [
|
||
("cls.sv", "class my_cls;\nendclass\n"),
|
||
("types.sv", "typedef logic [3:0] nib_t;\n"),
|
||
("top.sv", "module top;\n my_cls h;\n nib_t n;\nendmodule\n"),
|
||
];
|
||
let ws = index(&sources);
|
||
let sem = semantics(sources[2].1);
|
||
|
||
let cls = external_defs(&sem, &ws, sources[2].1, "my_cls h");
|
||
assert_eq!(cls.len(), 1, "{cls:?}");
|
||
assert_eq!(cls[0].kind, SymbolKind::Class);
|
||
let nib = external_defs(&sem, &ws, sources[2].1, "nib_t n");
|
||
assert_eq!(nib.len(), 1, "{nib:?}");
|
||
assert_eq!(nib[0].kind, SymbolKind::Typedef);
|
||
}
|
||
|
||
#[test]
|
||
fn a_miss_inside_an_extending_class_is_answered_without_losing_its_base() {
|
||
// The UVM shape: almost every class extends something, so almost every
|
||
// miss inside one is an `InheritedCandidate`. It stays one — `base` is
|
||
// still there for a consumer to read — and the overlay answers it from
|
||
// the paths it now carries.
|
||
let sources = [
|
||
("clk_rst_if.sv", "interface clk_rst_if;\nendinterface\n"),
|
||
("env.sv", "class env extends uvm_object;\n virtual clk_rst_if vif;\nendclass\n"),
|
||
];
|
||
let ws = index(&sources);
|
||
let sem = semantics(sources[1].1);
|
||
|
||
assert_eq!(
|
||
resolution(&sem, sources[1].1, "clk_rst_if vif"),
|
||
Resolution::InheritedCandidate {
|
||
base: "uvm_object".to_string(),
|
||
paths: vec!["clk_rst_if".to_string()],
|
||
},
|
||
"the inherited semantics other consumers read are untouched"
|
||
);
|
||
let defs = external_defs(&sem, &ws, sources[1].1, "clk_rst_if vif");
|
||
assert_eq!(defs.len(), 1, "{defs:?}");
|
||
assert_eq!(slice(&ws, &sources, &defs[0]), "clk_rst_if");
|
||
}
|
||
|
||
#[test]
|
||
fn a_direction_less_first_ansi_port_binds_its_interface_type_cross_file() {
|
||
// `docs/features/ansi-first-port/README.md`: the header spelling every
|
||
// interface port is really written in. `bind_module`'s ANSI arm sees an
|
||
// ordinary `AnsiPort` with no direction, so the type window is the one it
|
||
// always was and the name reaches the unit table like any other type miss.
|
||
// The modport spelling is the same reference: the parser glues `.mp` onto
|
||
// the type name and `bind_data_type` binds the interface half of it.
|
||
let sources = [
|
||
("bus_if.sv", "interface bus_if;\n modport mp (input a);\nendinterface\n"),
|
||
("top.sv", "module top (bus_if bus, input logic clk);\nendmodule\n"),
|
||
("sub.sv", "module sub (bus_if.mp bus);\nendmodule\n"),
|
||
];
|
||
let ws = index(&sources);
|
||
|
||
for (src, needle) in [(sources[1].1, "bus_if bus"), (sources[2].1, "bus_if.mp")] {
|
||
let sem = semantics(src);
|
||
assert_eq!(
|
||
resolution(&sem, src, needle),
|
||
Resolution::ExternalCandidate { paths: vec!["bus_if".to_string()] },
|
||
"{needle}"
|
||
);
|
||
let defs = external_defs(&sem, &ws, src, needle);
|
||
assert_eq!(defs.len(), 1, "{needle}: {defs:?}");
|
||
assert_eq!(slice(&ws, &sources, &defs[0]), "bus_if");
|
||
assert_eq!(defs[0].kind, SymbolKind::Module, "an interface is a Module symbol");
|
||
}
|
||
|
||
// The port itself is still declared, and `clk` beside it too: the shared
|
||
// type window never swallowed the declarator.
|
||
let sem = semantics(sources[1].1);
|
||
let ports: Vec<&str> = sem
|
||
.symbols()
|
||
.iter()
|
||
.filter(|s| s.kind == SymbolKind::Port)
|
||
.map(|s| s.name.as_str())
|
||
.collect();
|
||
assert_eq!(ports, ["bus", "clk"]);
|
||
}
|
||
|
||
#[test]
|
||
fn an_inherited_member_the_unit_table_cannot_hold_stays_exactly_what_it_was() {
|
||
// The other half of the same shape: an ordinary member miss. The sweep is
|
||
// a *unit* lookup, and a property or a method is not a unit, so nothing
|
||
// answers and the reference keeps its base and no overlay entry.
|
||
let sources = [
|
||
("base.sv", "class base;\n int held;\nendclass\n"),
|
||
(
|
||
"child.sv",
|
||
"class child extends base;\n function void f();\n held = 1;\n endfunction\nendclass\n",
|
||
),
|
||
];
|
||
let ws = index(&sources);
|
||
let sem = semantics(sources[1].1);
|
||
|
||
assert!(matches!(
|
||
resolution(&sem, sources[1].1, "held = 1"),
|
||
Resolution::InheritedCandidate { .. }
|
||
));
|
||
assert!(!in_overlay(&sem, &ws, sources[1].1, "held = 1"));
|
||
}
|
||
|
||
#[test]
|
||
fn a_qualified_miss_is_never_promoted_in_either_spelling() {
|
||
// `unit::member` names something *inside* `unit`; sweeping the bare tail
|
||
// would discard the qualifier and jump somewhere the source never
|
||
// pointed. `resolve.rs`'s `unit_member` never adds the bare name, in
|
||
// either of the two spellings its misses take.
|
||
let decoy = ("missing_t.sv", "module missing_t;\nendmodule\n");
|
||
let from_package =
|
||
[decoy, ("top.sv", "package p;\nendpackage\nmodule top;\n p::missing_t s;\nendmodule\n")];
|
||
let ws = index(&from_package);
|
||
let sem = semantics(from_package[1].1);
|
||
assert_eq!(resolution(&sem, from_package[1].1, "missing_t s"), Resolution::NotFound);
|
||
assert!(!in_overlay(&sem, &ws, from_package[1].1, "missing_t s"));
|
||
assert!(external_defs(&sem, &ws, from_package[1].1, "missing_t s").is_empty());
|
||
|
||
let from_class = [
|
||
decoy,
|
||
(
|
||
"top.sv",
|
||
"class base;\nendclass\nclass top extends base;\nendclass\nmodule m;\n top::missing_t s;\nendmodule\n",
|
||
),
|
||
];
|
||
let ws = index(&from_class);
|
||
let sem = semantics(from_class[1].1);
|
||
assert_eq!(
|
||
resolution(&sem, from_class[1].1, "missing_t s"),
|
||
Resolution::InheritedCandidate { base: "base".to_string(), paths: Vec::new() },
|
||
"no paths at all: nothing for the overlay to try"
|
||
);
|
||
assert!(!in_overlay(&sem, &ws, from_class[1].1, "missing_t s"));
|
||
assert!(external_defs(&sem, &ws, from_class[1].1, "missing_t s").is_empty());
|
||
}
|
||
|
||
#[test]
|
||
fn a_value_position_miss_is_never_promoted_even_onto_a_same_named_unit() {
|
||
// The twin of `an_unqualified_type_miss_carries_its_own_name_to_the_unit
|
||
// _table`, and the fence the fix round exists for. The same word, the same
|
||
// workspace, the only difference being where it is written: a type window
|
||
// is a claim about a declaration somewhere, a bare expression identifier
|
||
// is not. So this one keeps its pre-promotion spelling, the overlay is
|
||
// never asked, and `rename` goes on refusing it (QA finding 1, 2026-08-26).
|
||
let sources = [
|
||
("typo_name.sv", "module typo_name;\nendmodule\n"),
|
||
("top.sv", "module top;\n assign typo_name = 1'b1;\nendmodule\n"),
|
||
];
|
||
let ws = index(&sources);
|
||
let sem = semantics(sources[1].1);
|
||
|
||
assert_eq!(resolution(&sem, sources[1].1, "typo_name = 1"), Resolution::NotFound);
|
||
assert!(!in_overlay(&sem, &ws, sources[1].1, "typo_name = 1"));
|
||
assert!(external_defs(&sem, &ws, sources[1].1, "typo_name = 1").is_empty());
|
||
}
|
||
|
||
#[test]
|
||
fn a_value_position_miss_inside_an_extending_class_gains_no_path_either() {
|
||
// The twin of `a_miss_inside_an_extending_class_is_answered_without
|
||
// _losing_its_base`. An inherited candidate from a *value* position is
|
||
// exactly what it was before the promotion: its base and nothing else, so
|
||
// the sweep has nothing to try and the overlay records nothing — even
|
||
// though the workspace does declare a unit of that name.
|
||
let sources = [
|
||
("held.sv", "interface held;\nendinterface\n"),
|
||
(
|
||
"env.sv",
|
||
"class env extends uvm_object;\n function void f();\n held = 1;\n endfunction\nendclass\n",
|
||
),
|
||
];
|
||
let ws = index(&sources);
|
||
let sem = semantics(sources[1].1);
|
||
|
||
assert_eq!(
|
||
resolution(&sem, sources[1].1, "held = 1"),
|
||
Resolution::InheritedCandidate { base: "uvm_object".to_string(), paths: Vec::new() },
|
||
"no paths: a value position is offered nothing to sweep"
|
||
);
|
||
assert!(!in_overlay(&sem, &ws, sources[1].1, "held = 1"));
|
||
}
|
||
|
||
#[test]
|
||
fn a_local_declaration_of_a_promoted_name_still_wins() {
|
||
// The promotion happens only after the lexical walk gives up, so a name
|
||
// this file declares never reaches the workspace at all.
|
||
let sources = [
|
||
("bus_if.sv", "interface bus_if;\nendinterface\n"),
|
||
("top.sv", "module top;\n typedef logic bus_if;\n bus_if bus;\nendmodule\n"),
|
||
];
|
||
let ws = index(&sources);
|
||
let sem = semantics(sources[1].1);
|
||
|
||
assert!(matches!(resolution(&sem, sources[1].1, "bus_if bus"), Resolution::Resolved(_)));
|
||
assert!(!in_overlay(&sem, &ws, sources[1].1, "bus_if bus"));
|
||
match resolve_external(&sem, &ws)
|
||
.definition_of(&sem, sources[1].1.find("bus_if bus").expect("needle") as u32)
|
||
{
|
||
Some(Definition::Local(sym)) => assert_eq!(sym.kind, SymbolKind::Typedef),
|
||
other => panic!("expected the local typedef, got {other:?}"),
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn an_import_that_can_supply_the_name_still_wins_over_a_same_named_unit() {
|
||
// Order matters: the bare name goes last, so a package member reached
|
||
// through an import is preferred over a workspace unit that happens to
|
||
// share the name. That is the pre-promotion answer, kept.
|
||
let sources = [
|
||
("pkg.sv", "package tdp;\n typedef logic [1:0] state_t;\nendpackage\n"),
|
||
("decoy.sv", "module state_t;\nendmodule\n"),
|
||
("top.sv", "module top;\n import tdp::*;\n state_t s;\nendmodule\n"),
|
||
];
|
||
let ws = index(&sources);
|
||
let sem = semantics(sources[2].1);
|
||
|
||
assert_eq!(
|
||
resolution(&sem, sources[2].1, "state_t s"),
|
||
Resolution::ExternalCandidate { paths: vec!["tdp::*".to_string(), "state_t".to_string()] }
|
||
);
|
||
let defs = external_defs(&sem, &ws, sources[2].1, "state_t s");
|
||
assert_eq!(defs.len(), 1, "{defs:?}");
|
||
assert_eq!(defs[0].kind, SymbolKind::Typedef, "the package's typedef, not the decoy module");
|
||
}
|
||
|
||
// ----------------------------------------------------------------------
|
||
// Indexed reference postings
|
||
// ----------------------------------------------------------------------
|
||
|
||
#[test]
|
||
fn reference_postings_point_from_a_declaration_to_every_cross_file_use() {
|
||
let sources = [
|
||
("a.sv", "module top; sub u0 (); sub u1 (); endmodule\n"),
|
||
("b.sv", "module other; sub u2 (); endmodule\n"),
|
||
("sub.sv", "module sub; endmodule\n"),
|
||
];
|
||
let ws = index(&sources);
|
||
let [definition] = ws.units("sub") else { panic!("one sub declaration") };
|
||
let sites: Vec<(&Path, &str)> = ws
|
||
.references_to(definition)
|
||
.iter()
|
||
.map(|site| {
|
||
let path = ws.path(site.file).expect("site file");
|
||
let source = sources.iter().find(|(held, _)| Path::new(held) == path).unwrap().1;
|
||
(path, &source[site.name_span.as_range()])
|
||
})
|
||
.collect();
|
||
|
||
assert_eq!(
|
||
sites,
|
||
vec![(Path::new("a.sv"), "sub"), (Path::new("a.sv"), "sub"), (Path::new("b.sv"), "sub")]
|
||
);
|
||
assert!(!ws.references_are_ambiguous(definition));
|
||
}
|
||
|
||
/// `files_spelling` is the postings table asked the other question: not "who
|
||
/// refers to this declaration" but "who would notice if this name started
|
||
/// meaning something". The difference is a use that resolved to **nothing**,
|
||
/// which no posting can be keyed by — and which is exactly what a rename onto
|
||
/// that name would give a meaning.
|
||
#[test]
|
||
fn files_spelling_finds_the_uses_no_posting_can_be_keyed_by() {
|
||
let sources = [
|
||
("dangling.sv", "module strayer;\n import absent_pkg::*;\nendmodule\n"),
|
||
("resolved.sv", "module holder;\n sub u0 ();\nendmodule\n"),
|
||
("quiet.sv", "module quiet;\n wire absent_pkg;\n assign absent_pkg = 1'b0;\nendmodule\n"),
|
||
("sub.sv", "module sub; endmodule\n"),
|
||
];
|
||
let ws = index(&sources);
|
||
let named = |name: &str| -> Vec<&Path> {
|
||
ws.files_spelling(name).filter_map(|file| ws.path(file)).collect()
|
||
};
|
||
|
||
// Nothing declares `absent_pkg`, so it is in no posting at all …
|
||
assert!(ws.units("absent_pkg").is_empty());
|
||
// … but the file importing it is found, and the file that merely declares
|
||
// a local wire of the same name is not: a local declaration resolves
|
||
// inside its own file and the workspace was never asked about it.
|
||
assert_eq!(named("absent_pkg"), vec![Path::new("dangling.sv")]);
|
||
|
||
// A use that *did* resolve is here too — a name that already means
|
||
// something can equally start meaning something else.
|
||
assert_eq!(named("sub"), vec![Path::new("resolved.sv")]);
|
||
assert!(named("nobody_spells_this").is_empty());
|
||
}
|
||
|
||
#[test]
|
||
fn replacing_one_file_rebuilds_reference_postings_without_reparsing_the_others() {
|
||
let declaration = "module sub; endmodule\n";
|
||
let old_top = "module top; sub u0 (); sub u1 (); endmodule\n";
|
||
let new_top = "module top; sub u0 (); endmodule\n";
|
||
let mut incremental = index(&[("sub.sv", declaration), ("top.sv", old_top)]);
|
||
|
||
incremental.update_file(PathBuf::from("top.sv"), new_top);
|
||
let rebuilt = index(&[("sub.sv", declaration), ("top.sv", new_top)]);
|
||
|
||
assert_eq!(incremental.fingerprint(), rebuilt.fingerprint());
|
||
let [definition] = incremental.units("sub") else { panic!("one sub declaration") };
|
||
assert_eq!(incremental.references_to(definition).len(), 1);
|
||
}
|
||
|
||
#[test]
|
||
fn an_ambiguous_external_use_marks_every_possible_declaration() {
|
||
let ws = index(&[
|
||
("a.sv", "module dup; endmodule\n"),
|
||
("b.sv", "module dup; endmodule\n"),
|
||
("top.sv", "module top; dup u (); endmodule\n"),
|
||
]);
|
||
assert_eq!(ws.units("dup").len(), 2);
|
||
assert!(ws.units("dup").iter().all(|def| ws.references_are_ambiguous(def)));
|
||
}
|
||
|
||
// ----------------------------------------------------------------------
|
||
// Corpus acceptance
|
||
// ----------------------------------------------------------------------
|
||
|
||
/// Build one index over the whole corpus, then re-resolve every file against
|
||
/// it. Reports the headline the feature exists for — how many of the
|
||
/// single-file layer's external candidates the workspace layer finishes — and
|
||
/// asserts the properties behind it: no panic, a deterministic index, and
|
||
/// every answer really pointing at the name it claims.
|
||
#[test]
|
||
fn the_corpus_index_finishes_most_external_references() {
|
||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||
if !root.is_dir() {
|
||
eprintln!("corpus/ not checked out — skipping");
|
||
return;
|
||
}
|
||
let mut paths = Vec::new();
|
||
collect(&root, &mut paths);
|
||
paths.sort();
|
||
let sources: Vec<(PathBuf, String)> = paths
|
||
.iter()
|
||
.filter_map(|p| std::fs::read_to_string(p).ok().map(|s| (p.clone(), s)))
|
||
.collect();
|
||
assert!(!sources.is_empty(), "corpus/ exists but holds no Verilog");
|
||
|
||
let start = std::time::Instant::now();
|
||
let ws = WorkspaceIndex::build(sources.iter().map(|(p, s)| (p.clone(), s.as_str())));
|
||
let build = start.elapsed();
|
||
let counts = ws.counts();
|
||
println!(
|
||
"workspace index: {} files in {:.2}s — {} modules, {} packages, {} file-scope typedefs, \
|
||
{} classes, {} exported members, {} define directives",
|
||
counts.files,
|
||
build.as_secs_f64(),
|
||
counts.modules,
|
||
counts.packages,
|
||
counts.typedefs,
|
||
counts.classes,
|
||
counts.members,
|
||
counts.defines,
|
||
);
|
||
|
||
// Deterministic: the same sources build the same index, every time.
|
||
let again = WorkspaceIndex::build(sources.iter().map(|(p, s)| (p.clone(), s.as_str())));
|
||
assert_eq!(ws.files(), again.files(), "file ids must not depend on the run");
|
||
assert_eq!(counts, again.counts());
|
||
let fingerprint = |w: &WorkspaceIndex| -> Vec<(String, Option<String>, u32, u32)> {
|
||
w.workspace_symbols("")
|
||
.iter()
|
||
.map(|s| {
|
||
(
|
||
s.name.to_string(),
|
||
s.container.map(str::to_string),
|
||
s.def.file.0,
|
||
s.def.name_span.start,
|
||
)
|
||
})
|
||
.collect()
|
||
};
|
||
assert_eq!(fingerprint(&ws), fingerprint(&again), "the index is not deterministic");
|
||
|
||
let mut all = Tally::default();
|
||
let mut clean = Tally::default();
|
||
for (path, src) in &sources {
|
||
let (tree, diags) = parse_source_tolerant(src);
|
||
let sem = analyze(&tree, src);
|
||
let overlay = resolve_external(&sem, &ws);
|
||
let (in_file, references) = sem.resolution_counts();
|
||
let mut file_tally = Tally { references, in_file, ..Tally::default() };
|
||
for (id, target) in overlay.iter() {
|
||
let reference = sem.reference(id).expect("id came from the overlay");
|
||
let name = &reference.name;
|
||
file_tally.count(target, reference);
|
||
// Every answer must really be the name the use spells.
|
||
for def in target.defs() {
|
||
let target_path = ws.path(def.file).expect("def names an indexed file");
|
||
let target_src = &sources
|
||
.iter()
|
||
.find(|(p, _)| p == target_path)
|
||
.expect("indexed path came from the sources")
|
||
.1;
|
||
assert_eq!(
|
||
&target_src[def.name_span.as_range()],
|
||
name,
|
||
"{}: workspace answer for {name} points at other bytes in {}",
|
||
path.display(),
|
||
target_path.display(),
|
||
);
|
||
}
|
||
}
|
||
all.merge(&file_tally);
|
||
if diags.is_empty() {
|
||
clean.merge(&file_tally);
|
||
}
|
||
}
|
||
|
||
all.report("corpus (every file)");
|
||
clean.report("corpus (files that parse cleanly)");
|
||
|
||
assert!(build.as_secs_f64() < 5.0, "index build took {:.2}s", build.as_secs_f64());
|
||
assert!(
|
||
2 * clean.answered() > clean.total,
|
||
"the workspace should finish most external candidates: {} of {}",
|
||
clean.answered(),
|
||
clean.total
|
||
);
|
||
}
|
||
|
||
#[derive(Default)]
|
||
struct Tally {
|
||
/// Every reference the single-file layer recorded, external or not — the
|
||
/// denominator the vlog-semantic baseline reports percentages against.
|
||
references: usize,
|
||
/// The ones it resolved on its own, which the workspace layer never sees.
|
||
in_file: usize,
|
||
total: usize,
|
||
resolved: usize,
|
||
ambiguous: usize,
|
||
unresolved: usize,
|
||
/// Answers for references the single-file layer left as
|
||
/// `InheritedCandidate` — the bucket overlay-promotion added. Counted
|
||
/// separately because they are a *bonus*: an inherited candidate is not
|
||
/// an external one and only appears here when the sweep landed.
|
||
inherited: usize,
|
||
/// Unresolved import path → how many uses it left open, and one example
|
||
/// name each: the honest-gaps report.
|
||
misses: std::collections::BTreeMap<String, (usize, String)>,
|
||
}
|
||
|
||
impl Tally {
|
||
fn count(&mut self, target: &ExternalTarget, reference: &vlog_semantic::Reference) {
|
||
self.total += 1;
|
||
self.inherited += usize::from(reference.is_inherited_candidate());
|
||
match target {
|
||
ExternalTarget::Resolved(_) => self.resolved += 1,
|
||
ExternalTarget::Ambiguous(_) => self.ambiguous += 1,
|
||
ExternalTarget::StillUnresolved => {
|
||
self.unresolved += 1;
|
||
let paths = match &reference.resolution {
|
||
Resolution::ExternalCandidate { paths } => paths.join(" | "),
|
||
_ => String::new(),
|
||
};
|
||
let entry = self.misses.entry(paths).or_insert((0, reference.name.clone()));
|
||
entry.0 += 1;
|
||
}
|
||
}
|
||
}
|
||
|
||
fn merge(&mut self, other: &Tally) {
|
||
self.references += other.references;
|
||
self.in_file += other.in_file;
|
||
self.total += other.total;
|
||
self.resolved += other.resolved;
|
||
self.ambiguous += other.ambiguous;
|
||
self.unresolved += other.unresolved;
|
||
self.inherited += other.inherited;
|
||
for (path, (n, example)) in &other.misses {
|
||
let entry = self.misses.entry(path.clone()).or_insert((0, example.clone()));
|
||
entry.0 += n;
|
||
}
|
||
}
|
||
|
||
fn answered(&self) -> usize {
|
||
self.resolved + self.ambiguous
|
||
}
|
||
|
||
/// References with nowhere at all to jump: neither layer answered them.
|
||
/// The one number that must never rise — the buckets above it move
|
||
/// between themselves whenever a miss changes its spelling.
|
||
fn nowhere(&self) -> usize {
|
||
self.references - self.in_file - self.answered()
|
||
}
|
||
|
||
fn report(&self, label: &str) {
|
||
let pct = |n: usize, of: usize| 100.0 * n as f64 / of.max(1) as f64;
|
||
println!(
|
||
"{label}: {} references, {} handed to the workspace layer ({:.1}%, of which {} \
|
||
inherited candidates) — it answers {:.1}% of them ({:.1}% one target, {:.1}% \
|
||
ambiguous), {:.1}% still unresolved. Nowhere to jump after both layers: \
|
||
{} references, {:.1}% of all.",
|
||
self.references,
|
||
self.total,
|
||
pct(self.total, self.references),
|
||
self.inherited,
|
||
pct(self.answered(), self.total),
|
||
pct(self.resolved, self.total),
|
||
pct(self.ambiguous, self.total),
|
||
pct(self.unresolved, self.total),
|
||
self.nowhere(),
|
||
pct(self.nowhere(), self.references),
|
||
);
|
||
let mut top: Vec<(&String, &(usize, String))> = self.misses.iter().collect();
|
||
top.sort_by(|a, b| b.1 .0.cmp(&a.1 .0).then(a.0.cmp(b.0)));
|
||
for (path, (n, example)) in top.iter().take(5) {
|
||
println!(" still unresolved: {path} — {n} uses (e.g. {example})");
|
||
}
|
||
}
|
||
}
|
||
|
||
fn collect(dir: &std::path::Path, out: &mut Vec<PathBuf>) {
|
||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||
return;
|
||
};
|
||
for entry in entries.flatten() {
|
||
let path = entry.path();
|
||
if path.is_dir() {
|
||
collect(&path, out);
|
||
} else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "v" | "svh")) {
|
||
out.push(path);
|
||
}
|
||
}
|
||
}
|
||
|
||
// ----------------------------------------------------------------------
|
||
// incremental updates (incremental-index, 2026-08-27)
|
||
// ----------------------------------------------------------------------
|
||
|
||
/// The one invariant everything else in this section is an attack on: an index
|
||
/// arrived at by updating one file is the index a whole build over the same
|
||
/// files would have produced — ids, disambiguation order, member tables, edges
|
||
/// and defines alike.
|
||
///
|
||
/// Asserted by building both and comparing fingerprints, and returning the
|
||
/// incremental one so a caller can go on asking it questions.
|
||
fn updated(whole: &[(&str, &str)], changed: &str, text: &str) -> WorkspaceIndex {
|
||
let without: Vec<(&str, &str)> = whole.iter().copied().filter(|(p, _)| *p != changed).collect();
|
||
let mut incremental = index(&without);
|
||
incremental.update_file(PathBuf::from(changed), text);
|
||
let mut expected: Vec<(&str, &str)> = without;
|
||
expected.push((changed, text));
|
||
assert_eq!(
|
||
incremental.fingerprint(),
|
||
index(&expected).fingerprint(),
|
||
"updating `{changed}` must give the index a whole build would have"
|
||
);
|
||
incremental
|
||
}
|
||
|
||
#[test]
|
||
fn adding_a_file_gives_the_index_a_whole_build_would_have() {
|
||
// The hardest direction: the new file sorts *first*, so every file id after
|
||
// it moves and every table that named one has to move with it.
|
||
let held = [
|
||
("m.sv", "module m;\n sub u1 ();\nendmodule\n"),
|
||
("z.sv", "package z;\n localparam K = 1;\nendpackage\n"),
|
||
];
|
||
let ws = updated(&held, "a.sv", "module sub;\nendmodule\nclass leaf extends base;\nendclass\n");
|
||
assert_eq!(ws.files()[0], PathBuf::from("a.sv"), "the new file took FileId(0)");
|
||
assert_eq!(ws.units("z")[0].file, FileId(2), "and z.sv moved from 1 to 2");
|
||
assert_eq!(ws.instantiations_of("sub")[0].file, FileId(1), "m.sv's edge moved with it");
|
||
assert_eq!(ws.subclasses_of("base").len(), 1);
|
||
}
|
||
|
||
#[test]
|
||
fn replacing_a_file_touches_only_what_that_file_said() {
|
||
let held = [
|
||
("a.sv", "module a;\n sub u1 ();\nendmodule\n"),
|
||
("b.sv", "module b;\n sub u2 ();\nendmodule\n"),
|
||
("sub.sv", "module sub;\nendmodule\n"),
|
||
];
|
||
// `a.sv` stops instantiating `sub` and declares a package instead.
|
||
let ws = updated(&held, "a.sv", "package a;\n localparam K = 1;\nendpackage\n");
|
||
assert_eq!(ws.instantiations_of("sub").len(), 1, "only b.sv's site is left");
|
||
assert_eq!(ws.instantiations_of("sub")[0].owner.name, "b");
|
||
assert_eq!(ws.member("a", "K").len(), 1, "and the new package's member is there");
|
||
assert_eq!(ws.units("a")[0].kind, SymbolKind::Package, "the module is gone, not shadowed");
|
||
assert_eq!(ws.files().len(), 3, "no file came or went");
|
||
}
|
||
|
||
#[test]
|
||
fn removing_a_file_gives_the_index_a_whole_build_would_have() {
|
||
let held =
|
||
[("a.sv", "module dup;\n sub u1 ();\nendmodule\n"), ("z.sv", "module dup;\nendmodule\n")];
|
||
let mut ws = index(&held);
|
||
assert_eq!(ws.units("dup").len(), 2, "premise: the name is declared twice");
|
||
assert!(ws.remove_file(Path::new("a.sv")), "the file was there");
|
||
assert_eq!(
|
||
ws.fingerprint(),
|
||
index(&held[1..]).fingerprint(),
|
||
"what is left is the index of what is left"
|
||
);
|
||
assert_eq!(ws.units("dup").len(), 1, "and the removed declaration is gone");
|
||
assert_eq!(ws.units("dup")[0].file, FileId(0), "z.sv renumbered down to 0");
|
||
assert!(ws.instantiations_of("sub").is_empty(), "its edges went with it");
|
||
assert!(!ws.remove_file(Path::new("a.sv")), "and removing it again says so");
|
||
}
|
||
|
||
#[test]
|
||
fn absorbing_a_batch_gives_the_index_a_whole_build_would_have() {
|
||
// The batch form the interleaved scan feeds
|
||
// (`docs/features/scan-interleave/README.md`), against the same witness
|
||
// every other incremental path is held to. Every shape at once: a file
|
||
// replaced, two files added — one of which sorts *first*, so every id
|
||
// moves — and one dropped.
|
||
let held = [
|
||
("m.sv", "module m;\n sub u1 ();\nendmodule\n"),
|
||
("z.sv", "package z;\n localparam K = 1;\nendpackage\n"),
|
||
("gone.sv", "module gone;\nendmodule\n"),
|
||
];
|
||
let mut ws = index(&held);
|
||
assert_eq!(ws.files().len(), 3, "premise");
|
||
|
||
let batch = [
|
||
("a.sv", "module sub;\nendmodule\n"),
|
||
("m.sv", "module m;\n sub u1 ();\n sub u2 ();\nendmodule\n"),
|
||
("zz.sv", "class leaf extends base;\nendclass\n"),
|
||
];
|
||
ws.absorb(
|
||
batch.iter().map(|(p, s)| FileFacts::of(PathBuf::from(*p), s)).collect(),
|
||
&[PathBuf::from("gone.sv")],
|
||
);
|
||
|
||
let mut expected: Vec<(&str, &str)> = vec![("z.sv", held[1].1)];
|
||
expected.extend(batch);
|
||
assert_eq!(
|
||
ws.fingerprint(),
|
||
index(&expected).fingerprint(),
|
||
"a batch folded in is the index a whole build over what is left would have"
|
||
);
|
||
assert_eq!(ws.files()[0], PathBuf::from("a.sv"), "the added file took FileId(0)");
|
||
assert!(ws.units("gone").is_empty(), "and the dropped one is gone");
|
||
assert_eq!(ws.instantiations_of("sub").len(), 2, "the replaced file's new edges are in");
|
||
assert_eq!(ws.subclasses_of("base").len(), 1);
|
||
}
|
||
|
||
#[test]
|
||
fn absorbing_one_batch_and_absorbing_it_in_pieces_are_the_same_index() {
|
||
// What makes a *publish* free of consequence: the scan folds records in
|
||
// whenever it happens to be asked a question, so how the same records are
|
||
// grouped into batches must not reach the result.
|
||
let records = |files: &[(&str, &str)]| -> Vec<FileFacts> {
|
||
files.iter().map(|(p, s)| FileFacts::of(PathBuf::from(*p), s)).collect()
|
||
};
|
||
let files = [
|
||
("a.sv", "module sub;\nendmodule\n"),
|
||
("m.sv", "module m;\n sub u1 ();\nendmodule\n"),
|
||
("z.sv", "package z;\n localparam K = 1;\nendpackage\n"),
|
||
("dup.sv", "module m;\nendmodule\n"),
|
||
];
|
||
let mut whole = WorkspaceIndex::default();
|
||
whole.absorb(records(&files), &[]);
|
||
|
||
let mut piecemeal = WorkspaceIndex::default();
|
||
for one in &files {
|
||
piecemeal.absorb(records(std::slice::from_ref(one)), &[]);
|
||
}
|
||
assert_eq!(whole.fingerprint(), piecemeal.fingerprint());
|
||
assert_eq!(whole.fingerprint(), index(&files).fingerprint(), "and both are a whole build");
|
||
assert_eq!(piecemeal.units("m").len(), 2, "the duplicate name is still disambiguated");
|
||
}
|
||
|
||
#[test]
|
||
fn absorbing_a_batch_with_a_duplicate_path_diverges_from_a_build_over_the_same_records() {
|
||
// QA attack (`docs/features/scan-interleave/README.md`, absorb attacks):
|
||
// a duplicate path inside one batch. Not constructible through the scan
|
||
// that actually feeds `absorb` — `Scan::work` is built from `index_order`,
|
||
// which already dedupes by path — but `absorb` is a public entry point on
|
||
// `WorkspaceIndex`, and its doc comment claims "what comes out is the
|
||
// index a full build over the records it now holds would have produced."
|
||
// `WorkspaceIndex::build` goes through `index_order`, which keeps the
|
||
// *first* of a duplicate path (`Vec::dedup_by`'s contract). `absorb`'s own
|
||
// loop walks `records` left to right and overwrites on a hit, keeping the
|
||
// *last*. So handed the exact same two records for one path, the two
|
||
// entry points disagree — the claimed equivalence does not hold for a
|
||
// batch with a duplicate path. Filed as a finding, not fixed here: which
|
||
// one should win is a design call, not a QA fix.
|
||
let files = [
|
||
("a.sv", "module first_shape;\nendmodule\n"),
|
||
("a.sv", "package second_shape;\nendpackage\n"),
|
||
];
|
||
let built = WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(*p), *s)));
|
||
|
||
let mut absorbed = WorkspaceIndex::default();
|
||
absorbed.absorb(files.iter().map(|(p, s)| FileFacts::of(PathBuf::from(*p), s)).collect(), &[]);
|
||
|
||
assert_eq!(absorbed.files().len(), 1, "one file survives either way");
|
||
assert_ne!(
|
||
built.fingerprint(),
|
||
absorbed.fingerprint(),
|
||
"build (first-wins) and absorb (last-wins) disagree on a duplicate path in one batch"
|
||
);
|
||
// Naming what absorb actually did, so a fix that changes this is a
|
||
// deliberate, visible diff rather than a silent behavior change.
|
||
assert_eq!(
|
||
absorbed.fingerprint(),
|
||
index(&[("a.sv", files[1].1)]).fingerprint(),
|
||
"absorb kept the second (last) record for the duplicate path"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn absorbing_nothing_changes_nothing() {
|
||
// A publish with nothing staged and a finish with nothing left are both
|
||
// this call, and neither may disturb an index that is already right.
|
||
let files = [("a.sv", "module a;\nendmodule\n")];
|
||
let mut ws = index(&files);
|
||
let before = ws.fingerprint();
|
||
ws.absorb(Vec::new(), &[]);
|
||
assert_eq!(ws.fingerprint(), before);
|
||
ws.absorb(Vec::new(), &[PathBuf::from("never_held.sv")]);
|
||
assert_eq!(ws.fingerprint(), before, "dropping a file the index never held is harmless");
|
||
}
|
||
|
||
#[test]
|
||
fn removing_a_file_moves_the_disambiguation_winner() {
|
||
// The sharpest thing a removal can do to a *derived* answer: the file that
|
||
// won a duplicate name is the file that goes.
|
||
let held = [
|
||
("a_early.sv", "module dup (input a);\nendmodule\n"),
|
||
("z_late.sv", "module dup (input b);\nendmodule\n"),
|
||
];
|
||
let mut ws = index(&held);
|
||
assert_eq!(ws.path(ws.units("dup")[0].file), Some(Path::new("a_early.sv")), "premise");
|
||
assert!(ws.remove_file(Path::new("a_early.sv")));
|
||
assert_eq!(
|
||
ws.path(ws.units("dup")[0].file),
|
||
Some(Path::new("z_late.sv")),
|
||
"the loser became the winner, and the member table with it"
|
||
);
|
||
assert_eq!(ws.member("dup", "b").len(), 1);
|
||
assert!(ws.member("dup", "a").is_empty());
|
||
assert_eq!(ws.fingerprint(), index(&held[1..]).fingerprint());
|
||
}
|
||
|
||
#[test]
|
||
fn a_file_that_redefines_a_name_another_file_declares_lands_in_path_order() {
|
||
// The update inserts into a table that already holds the *other* file's
|
||
// declaration, so this is where an insert-at-the-end bug would show.
|
||
let held =
|
||
[("a_early.sv", "module dup;\nendmodule\n"), ("z_late.sv", "package other;\nendpackage\n")];
|
||
let ws = updated(&held, "z_late.sv", "module dup;\nendmodule\n");
|
||
let files: Vec<Option<&Path>> = ws.units("dup").iter().map(|d| ws.path(d.file)).collect();
|
||
assert_eq!(
|
||
files,
|
||
[Some(Path::new("a_early.sv")), Some(Path::new("z_late.sv"))],
|
||
"path order, not update order"
|
||
);
|
||
// And the other way round: the *early* file gains the duplicate.
|
||
let ws = updated(
|
||
&[held[0], ("z_late.sv", "module dup;\nendmodule\n")],
|
||
"a_early.sv",
|
||
"module dup;\nendmodule\n",
|
||
);
|
||
let files: Vec<Option<&Path>> = ws.units("dup").iter().map(|d| ws.path(d.file)).collect();
|
||
assert_eq!(files, [Some(Path::new("a_early.sv")), Some(Path::new("z_late.sv"))]);
|
||
}
|
||
|
||
#[test]
|
||
fn a_rename_is_a_remove_and_an_add_and_lands_where_a_build_would_put_it() {
|
||
let held = [
|
||
("mid.sv", "module m;\n sub u1 ();\nendmodule\n"),
|
||
("sub.sv", "module sub;\nendmodule\n"),
|
||
];
|
||
let mut ws = index(&held);
|
||
assert!(ws.remove_file(Path::new("mid.sv")));
|
||
ws.update_file(PathBuf::from("aaa.sv"), "module m;\n sub u1 ();\nendmodule\n");
|
||
let renamed = [("aaa.sv", "module m;\n sub u1 ();\nendmodule\n"), held[1]];
|
||
assert_eq!(ws.fingerprint(), index(&renamed).fingerprint(), "a rename is the two of them");
|
||
assert_eq!(ws.instantiations_of("sub")[0].file, FileId(0), "and the edge followed the file");
|
||
}
|
||
|
||
#[test]
|
||
fn an_update_survives_every_degenerate_file_there_is() {
|
||
let held = [("a.sv", "module a;\nendmodule\n"), ("b.sv", "module b;\nendmodule\n")];
|
||
for (label, text) in [
|
||
("empty", ""),
|
||
("whitespace", "\n\n \n"),
|
||
("not verilog", "@@@ !!! not verilog at all\n"),
|
||
("does not lex", "module a;\n string s = \"unterminated\n"),
|
||
("comment only", "// nothing here\n"),
|
||
] {
|
||
let ws = updated(&held, "a.sv", text);
|
||
assert_eq!(ws.files().len(), 2, "{label}: the file is still a file");
|
||
assert_eq!(ws.units("b").len(), 1, "{label}: and the other file is untouched");
|
||
}
|
||
// An empty index is not a special case either.
|
||
let mut empty = WorkspaceIndex::default();
|
||
assert!(!empty.remove_file(Path::new("nothing.sv")));
|
||
empty.update_file(PathBuf::from("only.sv"), "module only;\nendmodule\n");
|
||
assert_eq!(
|
||
empty.fingerprint(),
|
||
index(&[("only.sv", "module only;\nendmodule\n")]).fingerprint()
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn a_full_build_and_a_build_minus_one_plus_that_one_are_the_same_index() {
|
||
// The round's headline invariant, over a fixture with something of every
|
||
// kind in it and with **every** file taken out and put back in turn.
|
||
let files = [
|
||
("a_early.sv", "module dup (input a);\n sub u1 (), u2 ();\nendmodule\n"),
|
||
("cls.sv", "class leaf extends mid;\nendclass\nclass mid extends base;\nendclass\n"),
|
||
("defs.svh", "`define W 8\n`define D 4\n"),
|
||
(
|
||
"pkg.sv",
|
||
"package p;\n localparam K = 1;\n class base;\n int x;\n endclass\nendpackage\n",
|
||
),
|
||
("sub.sv", "module sub;\nendmodule\n"),
|
||
("z_late.sv", "module dup (input b);\n sub u3 ();\nendmodule\n"),
|
||
];
|
||
let whole = index(&files);
|
||
for (path, text) in files {
|
||
let rebuilt = updated(&files, path, text);
|
||
assert_eq!(
|
||
rebuilt.fingerprint(),
|
||
whole.fingerprint(),
|
||
"taking `{path}` out and putting it back must change nothing at all"
|
||
);
|
||
}
|
||
}
|
||
|
||
// ----------------------------------------------------------------------
|
||
// the edge tables (incremental-index, 2026-08-27)
|
||
// ----------------------------------------------------------------------
|
||
|
||
#[test]
|
||
fn the_instantiation_table_records_the_census_the_hierarchy_counts() {
|
||
// Every policy `lens.rs`'s QA tests pin, stated once here at the source of
|
||
// the numbers: one edge per written statement however many instances it
|
||
// declares, a `generate for` body counted once, both arms of an `` `ifdef``
|
||
// counted, a module that instantiates itself counted, a `bind`'s
|
||
// instantiation an ordinary edge, a gate primitive not an edge at all, and
|
||
// an instantiation at file scope not an edge because nothing calls it.
|
||
let files = [
|
||
(
|
||
"top.sv",
|
||
"\
|
||
module top;
|
||
sub u1 (), u2 ();
|
||
generate
|
||
for (genvar i = 0; i < 4; i++) begin : g
|
||
sub u3 ();
|
||
end
|
||
endgenerate
|
||
`ifdef FOO
|
||
sub u4 ();
|
||
`else
|
||
sub u5 ();
|
||
`endif
|
||
top u6 ();
|
||
and u7 (q, a, b);
|
||
bind top sub u8 ();
|
||
endmodule
|
||
",
|
||
),
|
||
("loose.sv", "sub u_loose ();\n"),
|
||
];
|
||
let ws = index(&files);
|
||
let sites = ws.instantiations_of("sub");
|
||
assert_eq!(
|
||
sites.len(),
|
||
5,
|
||
"one multi-instance statement, one generate body, both ifdef arms, one bind: {sites:#?}"
|
||
);
|
||
assert!(sites.iter().all(|edge| edge.owner.name == "top"), "all inside `top`: {sites:#?}");
|
||
assert!(sites.iter().all(|edge| edge.file == FileId(1)), "and all in top.sv");
|
||
assert_eq!(ws.instantiations_of("top").len(), 1, "a module instantiates itself");
|
||
assert!(ws.instantiations_of("and").is_empty(), "a gate primitive names no module");
|
||
assert!(
|
||
!sites.iter().any(|edge| edge.owner.name == "loose"),
|
||
"an instantiation at file scope has no caller and is not an edge"
|
||
);
|
||
// The spans are the ones a hierarchy item is built from: the site names the
|
||
// module, the owner's name span names the caller.
|
||
let text = files[0].1;
|
||
assert_eq!(&text[sites[0].site_span.as_range()], "sub");
|
||
assert_eq!(&text[sites[0].owner.name_span.as_range()], "top");
|
||
assert!(sites[0].owner.span.start <= sites[0].owner.name_span.start);
|
||
assert!(sites[0].owner.name_span.end <= sites[0].owner.span.end);
|
||
}
|
||
|
||
#[test]
|
||
fn the_inheritance_table_records_every_class_that_names_a_base() {
|
||
let files = [
|
||
("a.sv", "class leaf extends mid;\nendclass\n"),
|
||
("b.sv", "package p;\n class mid extends base;\n endclass\n class loner;\n endclass\nendpackage\n"),
|
||
("c.sv", "module m;\n class inner extends mid #(8);\n endclass\nendmodule\n"),
|
||
];
|
||
let ws = index(&files);
|
||
let mids: Vec<&str> =
|
||
ws.subclasses_of("mid").iter().map(|e| e.subclass.name.as_str()).collect();
|
||
assert_eq!(mids, ["leaf", "inner"], "file order; a parameterized base is the bare name");
|
||
assert_eq!(ws.subclasses_of("base").len(), 1, "a class inside a package is an edge too");
|
||
assert!(ws.subclasses_of("loner").is_empty(), "and a class nothing extends has none");
|
||
assert_eq!(ws.counts().inheritances, 3);
|
||
assert_eq!(ws.counts().instantiations, 0);
|
||
}
|
||
|
||
#[test]
|
||
fn the_edge_tables_are_empty_for_a_workspace_with_no_edges() {
|
||
let ws = index(&[("a.sv", "module a;\nendmodule\n")]);
|
||
assert!(ws.instantiations_of("a").is_empty());
|
||
assert!(ws.subclasses_of("a").is_empty());
|
||
assert_eq!(ws.instantiations().count(), 0);
|
||
assert_eq!(ws.subclasses().count(), 0);
|
||
assert_eq!(WorkspaceIndex::default().instantiations_of("anything").len(), 0);
|
||
}
|
||
|
||
// ----------------------------------------------------------------------
|
||
// QA (incremental-index, 2026-08-27): adversarial sequences the dev's own
|
||
// tests do not reach — each checked against a fresh build, not just asserted
|
||
// on its own terms.
|
||
// ----------------------------------------------------------------------
|
||
|
||
#[test]
|
||
fn a_long_interleaved_sequence_matches_a_fresh_build_at_every_step() {
|
||
// update A, update B, remove A, re-add A, update B again — the exact
|
||
// sequence the round's equivalence claim has to survive, checked after
|
||
// *every* step rather than only at the end (a bug that only shows up two
|
||
// steps later, e.g. a stale `Affected` set, would pass an end-only check).
|
||
let a1 = "module a;\n sub u1 ();\nendmodule\n";
|
||
let b1 = "package b;\n localparam K = 1;\nendpackage\n";
|
||
let mut incremental = index(&[("a.sv", a1), ("b.sv", b1)]);
|
||
|
||
let a2 = "module a;\n sub u1 (), u2 ();\nendmodule\nclass leaf extends base;\nendclass\n";
|
||
incremental.update_file(PathBuf::from("a.sv"), a2);
|
||
assert_eq!(
|
||
incremental.fingerprint(),
|
||
index(&[("a.sv", a2), ("b.sv", b1)]).fingerprint(),
|
||
"step 1: update a"
|
||
);
|
||
|
||
let b2 = "package b;\n localparam K = 2;\n class base;\n endclass\nendpackage\n";
|
||
incremental.update_file(PathBuf::from("b.sv"), b2);
|
||
assert_eq!(
|
||
incremental.fingerprint(),
|
||
index(&[("a.sv", a2), ("b.sv", b2)]).fingerprint(),
|
||
"step 2: update b"
|
||
);
|
||
|
||
assert!(incremental.remove_file(Path::new("a.sv")), "step 3: remove a");
|
||
assert_eq!(
|
||
incremental.fingerprint(),
|
||
index(&[("b.sv", b2)]).fingerprint(),
|
||
"step 3: what a full build over what is left would have"
|
||
);
|
||
|
||
let a3 = "module a;\n sub u3 ();\nendmodule\n";
|
||
incremental.update_file(PathBuf::from("a.sv"), a3);
|
||
assert_eq!(
|
||
incremental.fingerprint(),
|
||
index(&[("a.sv", a3), ("b.sv", b2)]).fingerprint(),
|
||
"step 4: re-add a"
|
||
);
|
||
|
||
let b3 = "package b;\n localparam K = 3;\nendpackage\n";
|
||
incremental.update_file(PathBuf::from("b.sv"), b3);
|
||
assert_eq!(
|
||
incremental.fingerprint(),
|
||
index(&[("a.sv", a3), ("b.sv", b3)]).fingerprint(),
|
||
"step 5: update b again"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn a_name_only_one_file_declared_leaves_no_ghost_when_that_file_stops_declaring_it() {
|
||
// The ghost hunt: `Affected` for an update is the old record's names
|
||
// *and* the new record's names (checked by reading `WorkspaceIndex::
|
||
// update_file`'s `Ok(at)` arm), so a name that only the changed file used
|
||
// to declare must come back with nothing at all — not a stale one-entry
|
||
// `Vec` from before the update, and not silently dropped from the merge's
|
||
// `.remove()` and never refilled either.
|
||
let held = [("a.sv", "module solo;\nendmodule\n"), ("b.sv", "package other;\nendpackage\n")];
|
||
let mut ws = index(&held);
|
||
assert_eq!(ws.units("solo").len(), 1, "premise: only a.sv declares it");
|
||
|
||
ws.update_file(PathBuf::from("a.sv"), "package a;\nendpackage\n");
|
||
assert!(ws.units("solo").is_empty(), "the ghost must not survive");
|
||
assert_eq!(
|
||
ws.fingerprint(),
|
||
index(&[("a.sv", "package a;\nendpackage\n"), held[1]]).fingerprint()
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn adding_a_new_file_that_duplicates_an_existing_name_lands_by_path_order_either_direction() {
|
||
// `a_file_that_redefines_a_name_another_file_declares_lands_in_path_order`
|
||
// covers this for a file the index already holds (the restricted-merge
|
||
// `Ok(at)` arm); this is the same attack against the `Err(at)` arm, where
|
||
// every id renumbers rather than one record being replaced in place.
|
||
let held = [("z_late.sv", "module dup;\nendmodule\n")];
|
||
let mut ws = index(&held);
|
||
ws.update_file(PathBuf::from("a_early.sv"), "module dup;\nendmodule\n");
|
||
let files: Vec<&Path> = ws.units("dup").iter().map(|d| ws.path(d.file).unwrap()).collect();
|
||
assert_eq!(
|
||
files,
|
||
[Path::new("a_early.sv"), Path::new("z_late.sv")],
|
||
"the new, earlier-sorting file wins the disambiguation"
|
||
);
|
||
assert_eq!(
|
||
ws.fingerprint(),
|
||
index(&[("a_early.sv", "module dup;\nendmodule\n"), held[0]]).fingerprint()
|
||
);
|
||
|
||
let held = [("a_early.sv", "module dup;\nendmodule\n")];
|
||
let mut ws = index(&held);
|
||
ws.update_file(PathBuf::from("z_late.sv"), "module dup;\nendmodule\n");
|
||
let files: Vec<&Path> = ws.units("dup").iter().map(|d| ws.path(d.file).unwrap()).collect();
|
||
assert_eq!(
|
||
files,
|
||
[Path::new("a_early.sv"), Path::new("z_late.sv")],
|
||
"and the other way round, the existing file keeps the disambiguation win"
|
||
);
|
||
assert_eq!(
|
||
ws.fingerprint(),
|
||
index(&[held[0], ("z_late.sv", "module dup;\nendmodule\n")]).fingerprint()
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn find_define_answers_in_current_file_id_order_after_cross_file_updates() {
|
||
// Defines are per-file (`WorkspaceIndex::defines`) and are not part of
|
||
// `Affected` at all — `find_define` just walks `self.facts` in current id
|
||
// order. The attack is renumbering: adding a file that sorts *before*
|
||
// both existing ones must move every entry's `FileId` and keep the answer
|
||
// in the new file order, `` `undef``s excluded either way.
|
||
let held = [("a.sv", "`define W 8\n"), ("b.sv", "`define W 16\n`undef W\n`define W 32\n")];
|
||
let mut ws = index(&held);
|
||
let bodies = |ws: &WorkspaceIndex| -> Vec<(u32, String)> {
|
||
ws.find_define("W").iter().map(|(f, d)| (f.0, d.body.clone())).collect()
|
||
};
|
||
assert_eq!(
|
||
bodies(&ws),
|
||
[(0, "8".to_string()), (1, "16".to_string()), (1, "32".to_string())],
|
||
"premise: file order, every definition (not just the latest), undef excluded"
|
||
);
|
||
|
||
ws.update_file(PathBuf::from("a.sv"), "`define W 9\n");
|
||
assert_eq!(
|
||
bodies(&ws),
|
||
[(0, "9".to_string()), (1, "16".to_string()), (1, "32".to_string())],
|
||
"the update landed and the order held"
|
||
);
|
||
|
||
ws.update_file(PathBuf::from("0_early.sv"), "`define W 1\n");
|
||
assert_eq!(ws.path(FileId(0)), Some(Path::new("0_early.sv")), "premise: it renumbered");
|
||
assert_eq!(
|
||
bodies(&ws),
|
||
[(0, "1".to_string()), (1, "9".to_string()), (2, "16".to_string()), (2, "32".to_string())],
|
||
"find_define's ids moved with the renumbering and the order is still file order"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn updating_a_file_to_empty_text_differs_from_removing_it() {
|
||
// Explicitly not the same operation, and not pinned as such anywhere else:
|
||
// an emptied file keeps its `FileId` slot (it is still a file the index
|
||
// holds, contributing nothing), while a removed file's slot is gone and
|
||
// every later id shifts down. Two different fingerprints, on purpose.
|
||
let held = [("a.sv", "module a;\nendmodule\n"), ("z.sv", "module z;\nendmodule\n")];
|
||
let mut emptied = index(&held);
|
||
emptied.update_file(PathBuf::from("a.sv"), "");
|
||
let mut removed = index(&held);
|
||
assert!(removed.remove_file(Path::new("a.sv")));
|
||
|
||
assert_ne!(
|
||
emptied.fingerprint(),
|
||
removed.fingerprint(),
|
||
"an emptied file is still a file; a removed one is not the same index at all"
|
||
);
|
||
assert_eq!(emptied.files().len(), 2, "the empty file still occupies a slot");
|
||
assert_eq!(removed.files().len(), 1, "the removed file's slot is gone");
|
||
assert_eq!(emptied.path(FileId(1)), Some(Path::new("z.sv")), "z.sv did not renumber");
|
||
assert_eq!(removed.path(FileId(0)), Some(Path::new("z.sv")), "z.sv renumbered down to 0");
|
||
}
|
||
|
||
#[test]
|
||
fn same_named_files_in_different_directories_updated_alternately_stay_correct() {
|
||
// Two files that share a *filename* but not a path are ordinary distinct
|
||
// entries to `WorkspaceIndex` (paths, not filenames, are the sort key and
|
||
// the identity `binary_search_by` uses) — attacked here by updating first
|
||
// one, then the other, then the first again, checking the full
|
||
// equivalence at each step so a bug keying off the filename rather than
|
||
// the path would show.
|
||
let held = [
|
||
("dir_a/defs.sv", "module defs_mod;\n sub u1 ();\nendmodule\n"),
|
||
("dir_b/defs.sv", "module defs_mod;\n sub u2 ();\nendmodule\n"),
|
||
];
|
||
let mut ws = index(&held);
|
||
assert_eq!(ws.units("defs_mod").len(), 2, "premise: both declare the same name");
|
||
|
||
// Two separate statements, not one comma-joined one — the census counts
|
||
// one edge per `Instantiation` node, so this really is two sites.
|
||
let dir_a_v2 = "module defs_mod;\n sub u3 ();\n sub u4 ();\nendmodule\n";
|
||
ws.update_file(PathBuf::from("dir_a/defs.sv"), dir_a_v2);
|
||
assert_eq!(ws.instantiations_of("sub").len(), 3, "dir_a now has two sites, dir_b still one");
|
||
assert_eq!(
|
||
ws.fingerprint(),
|
||
index(&[("dir_a/defs.sv", dir_a_v2), held[1]]).fingerprint(),
|
||
"after updating dir_a alone"
|
||
);
|
||
|
||
let dir_b_v2 = "package other;\nendpackage\n";
|
||
ws.update_file(PathBuf::from("dir_b/defs.sv"), dir_b_v2);
|
||
assert_eq!(ws.units("defs_mod").len(), 1, "only dir_a's module is left");
|
||
assert_eq!(ws.path(ws.units("defs_mod")[0].file), Some(Path::new("dir_a/defs.sv")));
|
||
assert_eq!(ws.instantiations_of("sub").len(), 2, "dir_b's site went with it");
|
||
assert_eq!(
|
||
ws.fingerprint(),
|
||
index(&[("dir_a/defs.sv", dir_a_v2), ("dir_b/defs.sv", dir_b_v2)]).fingerprint(),
|
||
"after updating dir_b too"
|
||
);
|
||
|
||
let dir_a_v3 = "module defs_mod;\nendmodule\n";
|
||
ws.update_file(PathBuf::from("dir_a/defs.sv"), dir_a_v3);
|
||
assert!(ws.instantiations_of("sub").is_empty(), "back to dir_a, and its sites go too");
|
||
assert_eq!(
|
||
ws.fingerprint(),
|
||
index(&[("dir_a/defs.sv", dir_a_v3), ("dir_b/defs.sv", dir_b_v2)]).fingerprint(),
|
||
"alternating back to the first file"
|
||
);
|
||
}
|
||
|
||
// ----------------------------------------------------------------------
|
||
// FileFacts as a record: the persistent index cache's format
|
||
// ----------------------------------------------------------------------
|
||
|
||
/// A fixture that exercises every field of a record at once: file-scope
|
||
/// units of three kinds, members (including a class nested in a package,
|
||
/// which is registered twice), instantiation edges, an inheritance edge,
|
||
/// and a `` `define`` table with both an object-like and a function-like
|
||
/// macro, an `` `undef``, and a body carrying the characters the format has
|
||
/// to escape.
|
||
const EVERY_FIELD: &str = concat!(
|
||
"`define PLAIN 8\n",
|
||
"`define ARGS(a, b = 8) {a, b}\t// a tab and a \\ backslash\n",
|
||
"`undef PLAIN\n",
|
||
"package p;\n",
|
||
" typedef logic [7:0] byte_t;\n",
|
||
" class base; endclass\n",
|
||
" class derived extends base;\n",
|
||
" function void f(); endfunction\n",
|
||
" endclass\n",
|
||
"endpackage\n",
|
||
"typedef int top_t;\n",
|
||
"module top;\n",
|
||
" sub u_sub ();\n",
|
||
" other u_other ();\n",
|
||
"endmodule\n",
|
||
);
|
||
|
||
#[test]
|
||
fn a_records_every_field_survives_the_round_trip() {
|
||
let facts = FileFacts::of(PathBuf::from("/w/every.sv"), EVERY_FIELD);
|
||
let line = facts.encode().expect("an ordinary path encodes");
|
||
assert!(!line.contains('\n'), "a record is one line: {line}");
|
||
let back = FileFacts::decode(&line).expect("what was written reads back");
|
||
// `FileFacts` compares every field it holds — path, defines (kind, name,
|
||
// params, body, both spans), units, members, instantiation edges,
|
||
// inheritance edges — so this is the whole record, not a summary of it.
|
||
assert_eq!(back, facts);
|
||
assert_eq!(back.encode(), Some(line), "and re-encodes byte for byte");
|
||
}
|
||
|
||
/// Every indexed declaration carries the line it is written on, so a caller
|
||
/// printing `file:line` never has to read the file
|
||
/// (`docs/features/hover-line-index/README.md`). The awkward offsets are the
|
||
/// point: line 1 has no newline before it, the last line has none after it,
|
||
/// and both are where an off-by-one lives.
|
||
#[test]
|
||
fn every_declared_names_line_is_recorded_when_the_file_is_indexed() {
|
||
// No trailing newline, so `last_t` really is on the file's last line.
|
||
let src = "module first;\nendmodule\n\n// a comment\npackage p;\n localparam W = 8;\n\
|
||
endpackage\ntypedef int last_t;";
|
||
let index = index(&[("/w/m.sv", src)]);
|
||
let line_of = |name: &str| index.units(name).first().expect(name).lines.name;
|
||
assert_eq!(line_of("first"), 1, "a declaration on line 1");
|
||
assert_eq!(line_of("p"), 5);
|
||
assert_eq!(line_of("last_t"), 8, "the last line, with no newline after it");
|
||
assert_eq!(index.member("p", "W").first().expect("W").lines.name, 6, "members too");
|
||
|
||
// The line really is the line the text says it is: every recorded line's
|
||
// range, sliced out of the source, contains the name it was recorded for.
|
||
for (name, line) in [("first", 1), ("p", 5), ("last_t", 8)] {
|
||
let text = src.lines().nth(line as usize - 1).expect("that many lines");
|
||
assert!(text.contains(name), "line {line} is {text:?}, which does not declare {name}");
|
||
}
|
||
}
|
||
|
||
/// A `\r\n` file and multi-byte text before a declaration do not shift its
|
||
/// line: lines are counted in newlines, not in bytes or in characters.
|
||
#[test]
|
||
fn crlf_and_multibyte_text_do_not_shift_a_declarations_line() {
|
||
let crlf = "// one\r\n// two\r\nmodule m;\r\nendmodule\r\n";
|
||
assert_eq!(index(&[("/w/c.sv", crlf)]).units("m").first().expect("m").lines.name, 3);
|
||
|
||
// Three-byte characters and a four-byte emoji ahead of the declaration:
|
||
// the byte offset of `m` is far past 3, its line is not.
|
||
let wide = "// héllo ✓ 🎉\n// ünïcödé\nmodule m;\nendmodule\n";
|
||
assert!(wide.find("module m").expect("a module") > 20, "premise: the bytes are wide");
|
||
assert_eq!(index(&[("/w/w.sv", wide)]).units("m").first().expect("m").lines.name, 3);
|
||
}
|
||
|
||
/// A non-ANSI port is named in the header and finished in the body, and the
|
||
/// carrier holds a line for each — the extension the shape was chosen for:
|
||
/// richer per-declaration position data is another field on `DeclLines`, not
|
||
/// another table.
|
||
#[test]
|
||
fn a_split_ports_two_lines_ride_the_same_carrier() {
|
||
let src = "module m (\n clk\n);\n input wire clk;\nendmodule\n";
|
||
let split = index(&[("/w/s.sv", src)]);
|
||
let def = split.member("m", "clk").first().expect("the port");
|
||
assert!(def.detail_span.is_some(), "premise: this port is split");
|
||
assert_eq!(def.lines.name, 2, "the header names it on line 2");
|
||
assert_eq!(def.lines.detail, Some(4), "and the body finishes it on line 4");
|
||
|
||
// An ANSI port is complete where it is named, and says so in both fields.
|
||
let ansi = index(&[("/w/a.sv", "module m (\n input wire clk\n);\nendmodule\n")]);
|
||
let def = ansi.member("m", "clk").first().expect("the port");
|
||
assert_eq!(def.detail_span, None);
|
||
assert_eq!((def.lines.name, def.lines.detail), (2, None));
|
||
}
|
||
|
||
/// The lines survive the record format, which is what makes them free on a
|
||
/// cached scan rather than only on a parsed one.
|
||
#[test]
|
||
fn a_declarations_lines_survive_the_record_round_trip() {
|
||
let src = "module m (\n clk\n);\n input wire clk;\nendmodule\n";
|
||
let facts = FileFacts::of(PathBuf::from("/w/s.sv"), src);
|
||
let line = facts.encode().expect("encodes");
|
||
let back = FileFacts::decode(&line).expect("decodes");
|
||
assert_eq!(back, facts, "every field, lines included");
|
||
|
||
let mut builder = vlog_semantic::IndexBuilder::new();
|
||
builder.add_facts(back);
|
||
let restored = builder.finish();
|
||
let def = restored.member("m", "clk").first().expect("the port");
|
||
assert_eq!((def.lines.name, def.lines.detail), (2, Some(4)));
|
||
}
|
||
|
||
/// QA (2026-08-28): the single-decl fixture `index_cache`'s own format-bump
|
||
/// test strips is not the only shape a genuine format-3 record could take —
|
||
/// a file declaring *two* units is the shape where a field-shift attack would
|
||
/// actually have somewhere plausible to land: if stripping the first decl's
|
||
/// two line fields shifted every read two fields early, the fields it would
|
||
/// then misread as `(name_line, detail_line)` are the *second* decl's own
|
||
/// `name` and `kind` strings. Both are always non-numeric — a Verilog
|
||
/// identifier cannot start with a digit and `kind_name` writes only letters —
|
||
/// so `Reader::num` fails on them and `decode` returns `None` rather than
|
||
/// quietly building a `Decl` out of someone else's fields. Proved directly
|
||
/// here, generalizing `index_cache`'s stripper to more than one declaration,
|
||
/// rather than only argued.
|
||
#[test]
|
||
fn a_format_3_record_with_two_declarations_is_rejected_not_misread() {
|
||
let src = "module a; endmodule\nmodule b; endmodule\n";
|
||
let facts = FileFacts::of(PathBuf::from("/w/two.sv"), src);
|
||
let encoded = facts.encode().expect("encodes");
|
||
let format_3 = strip_every_decls_line_fields(&encoded, 2, 0);
|
||
assert_ne!(format_3, encoded, "premise: fields were actually removed");
|
||
assert!(
|
||
FileFacts::decode(&format_3).is_none(),
|
||
"a two-unit format-3 record decoded as a format-4 one: {format_3}"
|
||
);
|
||
|
||
// The mixed case: one unit with a member that has a real detail span (a
|
||
// split port), so the decls being stripped are not even the same width
|
||
// of *content* — only of field count, which is what the format promises.
|
||
let split = "module m (\n clk\n);\n input wire clk;\nendmodule\n\
|
||
module other; endmodule\n";
|
||
let facts = FileFacts::of(PathBuf::from("/w/mixed.sv"), split);
|
||
let encoded = facts.encode().expect("encodes");
|
||
let format_3 = strip_every_decls_line_fields(&encoded, 2, 1);
|
||
assert_ne!(format_3, encoded, "premise: fields were actually removed");
|
||
assert!(
|
||
FileFacts::decode(&format_3).is_none(),
|
||
"a mixed unit+member format-3 record decoded as a format-4 one: {format_3}"
|
||
);
|
||
}
|
||
|
||
/// The generalization of `index_cache`'s `strip_the_line_fields`: remove the
|
||
/// two trailing (`name_line`, `detail_line`) fields from every one of
|
||
/// `units` unit-decls and `members` member-decls in an encoded record —
|
||
/// i.e. what `FACTS_FORMAT` 3 wrote for the same file. Assumes `D0` (no
|
||
/// `` `define``s), which every fixture here satisfies, so the `U` tag's
|
||
/// field index is fixed and decl positions can be computed directly rather
|
||
/// than parsed.
|
||
fn strip_every_decls_line_fields(encoded: &str, units: usize, members: usize) -> String {
|
||
let mut fields: Vec<&str> = encoded.split('\t').collect();
|
||
let units_at = fields.iter().position(|f| *f == "U").expect("a U tag");
|
||
assert_eq!(fields[units_at + 1], units.to_string(), "premise: unit count");
|
||
// decl = name, kind, name_span×2, detail_span×2, line×2 — 8 fields.
|
||
let unit_decls_end = units_at + 2 + units * 8;
|
||
let members_at = unit_decls_end;
|
||
assert_eq!(fields[members_at], "M", "premise: members tag follows the units");
|
||
assert_eq!(fields[members_at + 1], members.to_string(), "premise: member count");
|
||
// A member entry is the owning unit's name (one text field) plus a decl.
|
||
let member_decl_starts: Vec<usize> = (0..members).map(|m| members_at + 2 + m * 9 + 1).collect();
|
||
let unit_decl_starts: Vec<usize> = (0..units).map(|u| units_at + 2 + u * 8).collect();
|
||
// Highest index first, so removing one strip does not move the others.
|
||
let mut starts: Vec<usize> = unit_decl_starts.into_iter().chain(member_decl_starts).collect();
|
||
starts.sort_unstable_by(|a, b| b.cmp(a));
|
||
for start in starts {
|
||
fields.drain(start + 6..start + 8);
|
||
}
|
||
fields.join("\t")
|
||
}
|
||
|
||
#[test]
|
||
fn an_index_built_from_records_is_the_index_the_parse_would_have_given() {
|
||
// The claim the cache rests on: facts through the record format and back
|
||
// give the same index as the files themselves. Checked over a workspace
|
||
// with duplicate names and cross-file edges, by fingerprint — ids,
|
||
// disambiguation order, member tables, both edge tables, define counts.
|
||
let sources = [
|
||
("/w/a.sv", EVERY_FIELD),
|
||
("/w/b.sv", "module sub; endmodule\nmodule dup; endmodule\n"),
|
||
("/w/c.sv", "`define X 1\nmodule dup;\n sub u ();\nendmodule\n"),
|
||
("/w/d.sv", "class late extends base; endclass\n"),
|
||
];
|
||
let fresh = index(&sources);
|
||
|
||
let mut builder = vlog_semantic::IndexBuilder::new();
|
||
for (path, src) in sources {
|
||
let line = FileFacts::of(PathBuf::from(path), src).encode().expect("encodes");
|
||
builder.add_facts(FileFacts::decode(&line).expect("decodes"));
|
||
}
|
||
let restored = builder.finish();
|
||
|
||
assert_eq!(restored.fingerprint(), fresh.fingerprint());
|
||
assert_eq!(restored.counts(), fresh.counts());
|
||
}
|
||
|
||
#[test]
|
||
fn a_record_that_is_not_exactly_a_record_decodes_to_nothing() {
|
||
let facts = FileFacts::of(PathBuf::from("/w/every.sv"), EVERY_FIELD);
|
||
let line = facts.encode().expect("encodes");
|
||
let fields: Vec<&str> = line.split('\t').collect();
|
||
|
||
// Truncation at *every* length, not just at one: a torn write can stop
|
||
// anywhere, and every stopping point must be a dropped record rather
|
||
// than a plausible one.
|
||
for cut in 0..fields.len() {
|
||
let truncated = fields[..cut].join("\t");
|
||
assert_eq!(
|
||
FileFacts::decode(&truncated),
|
||
None,
|
||
"a record cut to {cut} of {} fields is not a record",
|
||
fields.len()
|
||
);
|
||
}
|
||
// And anything left over on the end is not a record either.
|
||
assert_eq!(FileFacts::decode(&format!("{line}\textra")), None, "trailing field");
|
||
|
||
for garbage in [
|
||
"",
|
||
"garbage",
|
||
"\0\0\0",
|
||
"/w/a.sv\tD0\tU0\tM0\tI0", // a list marker missing
|
||
"/w/a.sv\tD0\tU1\tm\tmodule\t0\t1\tM0\tI0\tS0", // a count that outruns the line
|
||
"/w/a.sv\tD0\tU1\tm\tnosuchkind\t0\t1\tM0\tI0\tS0", // a kind no version writes
|
||
"/w/a.sv\tD0\tU1\tm\tmodule\tzero\t1\tM0\tI0\tS0", // a number that is not one
|
||
"/w/a.sv\tX0\tU0\tM0\tI0\tS0", // the wrong marker
|
||
"/w/a\\qb.sv\tD0\tU0\tM0\tI0\tS0", // an escape this format never writes
|
||
"/w/a.sv\tD1\td\tM\t-\tbody\t0\t1\t2\tM0\tI0\tS0", // a define's fields cut short
|
||
] {
|
||
assert_eq!(FileFacts::decode(garbage), None, "{garbage:?} is not a record");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn a_path_with_a_separator_in_it_is_escaped_like_any_other_string() {
|
||
// The path is a string field like the rest, so a tab or a newline in it
|
||
// is escaped rather than fatal — the same treatment a macro body gets,
|
||
// and it needs it (`EVERY_FIELD` has both).
|
||
for path in ["/w/a\tb.sv", "/w/a\nb.sv", "/w/a\\b.sv"] {
|
||
let facts = FileFacts::of(PathBuf::from(path), "module m; endmodule\n");
|
||
let line = facts.encode().expect("encodes");
|
||
assert!(!line.contains('\n'), "still one line: {line}");
|
||
assert_eq!(FileFacts::decode(&line).as_ref(), Some(&facts), "{path:?}");
|
||
}
|
||
}
|
||
|
||
#[cfg(unix)]
|
||
#[test]
|
||
fn a_path_that_is_not_utf_8_is_simply_never_cached() {
|
||
// The one path shape that has no record: it cannot be written as text at
|
||
// all. `None` rather than a lossy spelling — a record whose path is not
|
||
// the file's path would be a record that answers for the wrong file.
|
||
// Same answer `lucisv_core::cache` gives the same shape of path.
|
||
use std::ffi::OsStr;
|
||
use std::os::unix::ffi::OsStrExt;
|
||
let path = PathBuf::from(OsStr::from_bytes(b"/w/\xff\xfe.sv"));
|
||
assert_eq!(FileFacts::of(path, "module m; endmodule\n").encode(), None);
|
||
}
|
||
|
||
#[test]
|
||
fn a_degenerate_file_still_makes_a_record() {
|
||
// The shapes `an_update_survives_every_degenerate_file_there_is` covers,
|
||
// through the record format: an empty file, one that does not lex, one
|
||
// that is not Verilog at all. Each has a record, and each round-trips.
|
||
for src in [
|
||
"",
|
||
" \n\t\n",
|
||
"this is not verilog\n",
|
||
"module m;\n \"unterminated\n",
|
||
"// just a comment\n",
|
||
] {
|
||
let facts = FileFacts::of(PathBuf::from("/w/x.sv"), src);
|
||
let line = facts.encode().expect("encodes");
|
||
assert_eq!(FileFacts::decode(&line).as_ref(), Some(&facts), "{src:?}");
|
||
}
|
||
}
|
||
|
||
// ----------------------------------------------------------------------
|
||
// Facts from an analysis the caller already has (index-scope, 2026-08-28)
|
||
// ----------------------------------------------------------------------
|
||
|
||
/// The analysis a server holds for an open buffer, built exactly the way
|
||
/// `lucisv_server::state::Document::new` builds it — one lex, the tree from a
|
||
/// clone of that token stream, the define table off the same tokens, and the
|
||
/// same all-or-nothing lex-failure branch.
|
||
fn as_a_server_analyzes(
|
||
src: &str,
|
||
) -> (vlog_parser::ast::SourceFile, DefineTable, Semantics, vlog_parser::LineIndex) {
|
||
let (tokens, tree) = match tokenize(src) {
|
||
Ok(tokens) => {
|
||
let (tree, _) = parse_tolerant(tokens.clone(), src);
|
||
(tokens, tree)
|
||
}
|
||
Err(_) => (Vec::new(), parse_source_tolerant(src).0),
|
||
};
|
||
let defines = collect_defines(&tokens);
|
||
let sem = analyze(&tree, src);
|
||
(tree, defines, sem, vlog_parser::LineIndex::new(src))
|
||
}
|
||
|
||
/// `FileFacts::from_analysis` and `FileFacts::of` are one record, not two.
|
||
///
|
||
/// The record format is the comparison — the encoded line is every field the
|
||
/// index and the persistent store ever read — so a byte-equal line is the
|
||
/// whole equivalence. Two paths that could drift here would be a corruption
|
||
/// seed: the index would describe a buffer by facts its own parse disagrees
|
||
/// with.
|
||
#[test]
|
||
fn facts_from_a_finished_analysis_are_byte_identical_to_facts_from_the_text() {
|
||
let crafted = [
|
||
// Nothing at all, and nothing that lexes.
|
||
"",
|
||
" \n\t\n",
|
||
"this is not verilog\n",
|
||
"module m;\n \"unterminated\n",
|
||
"// just a comment\n",
|
||
// The declaration kinds `facts_of` reads off the file scope.
|
||
"package p;\n localparam W = 8;\n typedef logic [W-1:0] word_t;\n\
|
||
\x20 function int f(int a); return a; endfunction\nendpackage\n",
|
||
"module top #(parameter N = 4) (input logic clk, output logic q);\n\
|
||
\x20 sub u_a (.clk(clk));\n sub u_b (.clk(clk));\nendmodule\n",
|
||
// Classes, inheritance, and a class nested in a package.
|
||
"class base; endclass\nclass derived extends base;\n int x;\nendclass\n",
|
||
"package pkg;\n class inner extends outer_base;\n typedef int t;\n endclass\nendpackage\n",
|
||
// `define`s, including a parameterised one and an `undef`.
|
||
"`define WIDTH 8\n`define MAX(a, b) ((a) > (b) ? (a) : (b))\n`undef WIDTH\n\
|
||
module m; logic [`WIDTH-1:0] w; endmodule\n",
|
||
// External candidates: imports, scope resolution, port connections.
|
||
"import other_pkg::*;\nimport third_pkg::thing;\nmodule m;\n\
|
||
\x20 other_pkg::word_t w;\n assign w = thing;\n child u (.port_a(w));\nendmodule\n",
|
||
// An instantiation at file scope — deliberately *not* an edge — and a
|
||
// generate body, which is one site however many instances it makes.
|
||
"sub u_orphan (.clk(clk));\nmodule m;\n generate for (genvar i = 0; i < 4; i++) begin\n\
|
||
\x20 sub u_gen (.clk(clk));\n end endgenerate\nendmodule\n",
|
||
// A tree with error nodes: the tolerant parse still contributes.
|
||
"module broken (input logic clk;\n wire w = ;\nendmodule\nmodule after; endmodule\n",
|
||
];
|
||
for src in crafted {
|
||
let path = PathBuf::from("/w/x.sv");
|
||
let (tree, defines, sem, lines) = as_a_server_analyzes(src);
|
||
let from_text = FileFacts::of(path.clone(), src);
|
||
let from_analysis = FileFacts::from_analysis(path, &tree, &defines, &sem, &lines);
|
||
assert_eq!(from_analysis, from_text, "the records differ for {src:?}");
|
||
assert_eq!(
|
||
from_analysis.encode(),
|
||
from_text.encode(),
|
||
"and so do their encoded forms for {src:?}"
|
||
);
|
||
}
|
||
}
|
||
|
||
/// The same claim over every file of the real corpus, which is where the
|
||
/// constructs nobody thought to craft live.
|
||
#[test]
|
||
fn the_two_ways_to_read_a_files_facts_agree_over_the_whole_corpus() {
|
||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||
if !root.is_dir() {
|
||
eprintln!("corpus/ not checked out — skipping");
|
||
return;
|
||
}
|
||
let mut files = Vec::new();
|
||
corpus_files(&root, &mut files);
|
||
files.sort();
|
||
assert!(!files.is_empty(), "corpus/ exists but holds no Verilog");
|
||
let mut checked = 0usize;
|
||
for path in &files {
|
||
let Ok(src) = std::fs::read_to_string(path) else {
|
||
continue;
|
||
};
|
||
let (tree, defines, sem, lines) = as_a_server_analyzes(&src);
|
||
let from_text = FileFacts::of(path.clone(), &src);
|
||
let from_analysis = FileFacts::from_analysis(path.clone(), &tree, &defines, &sem, &lines);
|
||
assert_eq!(
|
||
from_analysis.encode(),
|
||
from_text.encode(),
|
||
"the records differ for {}",
|
||
path.display()
|
||
);
|
||
checked += 1;
|
||
}
|
||
eprintln!("facts equivalence: {checked} corpus files, every record byte-identical");
|
||
}
|
||
|
||
fn corpus_files(dir: &Path, out: &mut Vec<PathBuf>) {
|
||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||
return;
|
||
};
|
||
for entry in entries.flatten() {
|
||
let path = entry.path();
|
||
if path.is_dir() {
|
||
corpus_files(&path, out);
|
||
} else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "v" | "svh")) {
|
||
out.push(path);
|
||
}
|
||
}
|
||
}
|
||
|
||
/// An index built from records read off analyses is the index the parses
|
||
/// build, byte for byte — the house witness, at index scale rather than at one
|
||
/// file's.
|
||
#[test]
|
||
fn an_index_built_from_finished_analyses_fingerprints_the_same_as_one_built_from_text() {
|
||
let files = [
|
||
("/w/pkg.sv", "package p;\n localparam W = 8;\n class c; int x; endclass\nendpackage\n"),
|
||
("/w/sub.sv", "module sub (input logic clk, input logic [7:0] d);\nendmodule\n"),
|
||
(
|
||
"/w/top.sv",
|
||
"import p::*;\n`define TAG 1\nmodule top;\n logic [W-1:0] w;\n\
|
||
\x20 sub u_a (.clk(w[0]), .d(w));\n sub u_b (.clk(w[0]), .d(w));\nendmodule\n",
|
||
),
|
||
("/w/kid.sv", "class kid extends c;\nendclass\n"),
|
||
("/w/junk.sv", "module broken (;\n"),
|
||
];
|
||
let from_text = WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(*p), *s)));
|
||
|
||
let mut builder = vlog_semantic::IndexBuilder::new();
|
||
// Deliberately not path order: the reuse must not smuggle an ordering in.
|
||
for (path, src) in files.iter().rev() {
|
||
let (tree, defines, sem, lines) = as_a_server_analyzes(src);
|
||
builder.add_facts(FileFacts::from_analysis(
|
||
PathBuf::from(*path),
|
||
&tree,
|
||
&defines,
|
||
&sem,
|
||
&lines,
|
||
));
|
||
}
|
||
let from_analyses = builder.finish();
|
||
assert_eq!(from_analyses.fingerprint(), from_text.fingerprint());
|
||
|
||
// And the same through the incremental door: `update_facts` must leave the
|
||
// index `update_file` would have left.
|
||
let mut updated = from_text.clone();
|
||
let changed = "package p;\n localparam W = 16;\n class c; int y; endclass\nendpackage\n";
|
||
let (tree, defines, sem, lines) = as_a_server_analyzes(changed);
|
||
updated.update_facts(FileFacts::from_analysis(
|
||
PathBuf::from("/w/pkg.sv"),
|
||
&tree,
|
||
&defines,
|
||
&sem,
|
||
&lines,
|
||
));
|
||
let mut parsed = from_text.clone();
|
||
parsed.update_file(PathBuf::from("/w/pkg.sv"), changed);
|
||
assert_eq!(updated.fingerprint(), parsed.fingerprint(), "update_facts == update_file");
|
||
}
|