Files
lucisv/crates/vlog_semantic/tests/workspace.rs
T
lucioandClaude Fable 5 e4b1f55c12
ci / checks (push) Failing after 8s
ci / corpus (push) Failing after 5s
Persistent index cache: a half-indexed workarea resumes where it stopped
Owner-requested round. Every parsed file's FileFacts record is written
through to an index-cache store (append per file, atomic compaction at
scan end — a crash loses at most the file in flight), keyed by a
content hash that is the whole key: no mtime fast path, by measured
argument (6 ms of a 181 ms warm scan, and unsound against save-time
write-through). On reopen, hits skip parsing and the resume is
visible — cached: vs indexing: log lines, the bar counting through
hits, and an end message saying how many came from cache. Warm rescan
322 to 179 ms release, 1.5 s to 0.76 s debug; 910 KB store for the
860-file corpus. Location: lucisv.index.cachePath > the extension's
context.storageUri via initializationOptions (the one extension.js
change) > the OS cache dir keyed by workspace identity > nowhere;
lucisv.index.persist (default on) gates both directions immediately.

The cache is a performance artifact, never a correctness input, and
after the fix round that promise is total against everything but
intentional forgery — which the threat model now formally excludes
(same-user disk; a keyed MAC would be theater): a per-record checksum
drops every corrupt-but-parseable line (poisoned and reforged shapes
both pinned so the checksum is never mistaken for a MAC), first-writer
initialization is a create_new claim with structural 100/100 survival,
and a torn multi-byte tail costs exactly the torn record (0 of 583
offsets lose more). Old-format stores discard wholesale. Load==fresh
fingerprint equality swept over the corpus.

45 tests added across the main and fix rounds (dev 33+2, QA 9+3, one
QA test-construction bug self-caught), 2 ignored probes.

docs/features/index-persistence/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-27 16:33:52 -07:00

1605 lines
67 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::parse_source_tolerant;
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");
}
// ----------------------------------------------------------------------
// 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 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");
}
#[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:?}");
}
}