IEEE 1800 §23.2.2.2 allows an ANSI header's first port to carry no
direction — the normal spelling for interface ports — but
parse_port_list classified any leading identifier as a non-ANSI list
and errored on what followed. One clause fixes it: a leading Ident is
ANSI when the parser's existing type-then-name lookahead
(at_typed_declarator, which already walks pkg:: chains, #() overrides
and packed dims) or the new 4-token modport lookahead (ident.ident
ident) says so; the complement is exactly the old non-ANSI list, and
macro-led lists never enter the clause. bus_if.mp was a second,
independent gap (it parsed in no position before) and is glued into
DataType::name the way pkg::t already was. No AST change — the new
ports are AnsiPort { dir: None }, the shape later ports always had.
Two match-widenings ride along: bind_data_type and type_def's
type_span read the pre-dot half as the type, and the modport half is
bindable by nothing — pinned for rename by QA.
The safety case, established twice (dev, then QA independently via a
worktree build): corpus 813/820 both sides, TSVs byte-identical, and
all 820 formatted outputs SHA-256-identical across the change; zero
snapshot churn; verify.rs untouched. QA's boundary AST-diff harness
(~20 shapes at the classification edge) and a 50-file
direction-stripping fuzz sweep found no misfire. The
previously-blocked fixtures flipped to first-port order; instantiate
now plans interface-typed port lists instead of refusing. The two
remaining unsupported shapes (generic interface ports, virtual
modport declarations) are pinned by a lead-added test so a future
round changes them on purpose.
24 tests added (dev 21 + QA 2 + lead 1).
docs/features/ansi-first-port/README.md
Co-Authored-By: Claude Fable 5 <[email protected]>
856 lines
34 KiB
Rust
856 lines
34 KiB
Rust
//! Behavior of the workspace index: cross-file definitions, duplicate names,
|
|
//! package members, and the corpus acceptance run.
|
|
|
|
use std::path::PathBuf;
|
|
use vlog_parser::parse_source_tolerant;
|
|
use vlog_semantic::{
|
|
analyze, resolve_external, Def, Definition, ExternalTarget, 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);
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// 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);
|
|
}
|
|
}
|
|
}
|