Files
lucisv/crates/vlog_semantic/tests/member_access.rs
T
lucioandClaude Opus 5.5 7794d3938b TODO §65.1: rename and references through a generate block label; rename warnings and mentions scoped to the renamed declaration
A path segment naming a block (bare, indexed, nested, cross-file) is now a
reference to its label: vlog_semantic declares a `for` block's label in the
enclosing scope, makes `generate … endgenerate` no scope, gives a block a
member scope, walks an index in a path, and files blocks on a module's
hierarchical surface under `module.label` (FACTS_FORMAT 21). The LSP, CLI
and MCP rename/references get it through the engine; lucisv-mcp's `block`
refusal is lifted. No verifier normalization (attacks in
check/qa_block_paths.rs, qa_block_attacks.rs).

Reworks after QA: unresolved path segments warned in every file of the set;
sibling-arm members warned; a label beside a net is a duplicate-declaration;
function-local block keys never collide; file names path-qualified when base
names collide; rename warnings and lucisv-mcp mentions scoped to the
declaration's home set (rename/home.rs, scoped.rs), falling back to unscoped
on any doubt. TODO §65.4 and §65.6 filed.

docs/features/generate-label-rename. Workspace lib/bins/tests: 79 suites,
5 064 passed, 0 failed, 51 ignored (guard exit 0).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 01:01:23 -07:00

1238 lines
45 KiB
Rust

//! `handle.member` through a class-typed variable: the tail reference, the
//! `extends` chase in-file and across files, and the shapes that deliberately
//! record nothing. The rules live in
//! `docs/features/class-member-access/README.md`.
use std::path::PathBuf;
use vlog_parser::parse_source;
use vlog_semantic::{
analyze, resolve_external, Def, ExternalTarget, Resolution, Semantics, Surface, SymbolKind,
WorkspaceIndex,
};
// ----------------------------------------------------------------------
// helpers
// ----------------------------------------------------------------------
/// The owner's three classes, as the lead's scratch files write them.
const BASE: &str = "class u1;\n rand bit [7:0] base_field;\nendclass\n";
const C1: &str = "class c1 extends u1;\n rand bit user_id;\n rand bit feature1;\nendclass\n";
const CLASS2: &str = "class class2;\n bit address;\n bit address2;\n bit [7:0] address3;\n extern task update(c1 in_item);\nendclass\n\ntask class2::update(c1 in_item);\n address = in_item.user_id;\n address2 = in_item.feature1;\n address3 = in_item.base_field;\nendtask\n";
fn sem(src: &str) -> Semantics {
let file = parse_source(src).expect("fixture must parse");
analyze(&file, src)
}
/// Offset of the `n`th (0-based) occurrence of `needle`.
fn nth(src: &str, needle: &str, n: usize) -> u32 {
src.match_indices(needle).nth(n).expect("occurrence must exist").0 as u32
}
/// The offset of the member half of the `n`th `head.member` written as
/// `needle` — the tail, which is what this feature records.
fn tail(src: &str, needle: &str, n: usize) -> u32 {
let at = nth(src, needle, n);
at + needle.rfind('.').expect("a member access") as u32 + 1
}
fn resolution_at(s: &Semantics, offset: u32) -> Resolution {
s.reference_at(offset).unwrap_or_else(|| panic!("no reference at {offset}")).resolution.clone()
}
fn symbol_named(s: &Semantics, name: &str) -> vlog_semantic::SymbolId {
let (i, _) = s
.symbols()
.iter()
.enumerate()
.find(|(_, sym)| sym.name == name)
.unwrap_or_else(|| panic!("no symbol {name}"));
vlog_semantic::SymbolId(i as u32)
}
fn index(files: &[(&str, &str)]) -> WorkspaceIndex {
WorkspaceIndex::build(files.iter().map(|(name, src)| (PathBuf::from(name), *src)))
}
/// The workspace's answer for the use at `offset` in `src`, resolved against
/// `ws`.
fn overlay_def(ws: &WorkspaceIndex, src: &str, offset: u32) -> Option<Def> {
let s = sem(src);
let id = s.reference_id_at(offset)?;
resolve_external(&s, ws).get(id).and_then(ExternalTarget::best).cloned()
}
fn file_name(ws: &WorkspaceIndex, def: &Def) -> String {
ws.path(def.file)
.and_then(|p| p.file_name())
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default()
}
// ----------------------------------------------------------------------
// one file
// ----------------------------------------------------------------------
/// The owner's shape, all three classes in one file: the tail of
/// `in_item.user_id` resolves to `c1`'s property, and `in_item.base_field`
/// to `u1`'s through the in-file `extends` chase.
#[test]
fn the_owners_example_resolves_every_member_in_one_file() {
let src = format!("{BASE}{C1}{CLASS2}");
let s = sem(&src);
assert_eq!(
resolution_at(&s, tail(&src, "in_item.user_id", 0)),
Resolution::Resolved(symbol_named(&s, "user_id"))
);
assert_eq!(
resolution_at(&s, tail(&src, "in_item.feature1", 0)),
Resolution::Resolved(symbol_named(&s, "feature1"))
);
assert_eq!(
resolution_at(&s, tail(&src, "in_item.base_field", 0)),
Resolution::Resolved(symbol_named(&s, "base_field"))
);
// The head is still a reference of its own — the argument, not the class.
let head = s.reference_at(nth(&src, "in_item.user_id", 0)).expect("the head");
assert_eq!(
s.symbol(head.resolved().expect("resolved")).map(|sym| sym.kind),
Some(SymbolKind::TfArg)
);
// And the left-hand sides resolve in the class the method belongs to.
for name in ["address", "address2", "address3"] {
let at = nth(&src, &format!("{name} = in_item"), 0);
assert_eq!(
resolution_at(&s, at),
Resolution::Resolved(symbol_named(&s, name)),
"{name} is class2's property"
);
}
}
/// The declared type is recorded on the declarations that have one, and on
/// nothing else.
#[test]
fn type_names_are_recorded_where_a_type_is_written() {
let src = "\
module m #(parameter my_t P = 0) (input wire clk, output some_t q);
my_t v;
logic [3:0] plain;
wire w;
sub u ();
function void f(other_t arg);
int local_i;
endfunction
endmodule
";
let s = sem(src);
let typed = |name: &str| s.symbol(symbol_named(&s, name)).and_then(|sym| sym.type_name.clone());
assert_eq!(typed("v"), Some("my_t".to_string()));
assert_eq!(typed("q"), Some("some_t".to_string()));
assert_eq!(typed("arg"), Some("other_t".to_string()));
assert_eq!(typed("P"), Some("my_t".to_string()));
// Built-in types name no declaration to look members up in.
assert_eq!(typed("clk"), None);
assert_eq!(typed("plain"), None);
assert_eq!(typed("w"), None);
assert_eq!(typed("local_i"), None);
// An instance's type is the module it instantiates (round 2), which is
// what makes `u.port` and `u.internal_sig` resolve.
assert_eq!(typed("u"), Some("sub".to_string()));
// Neither do the declarations that have no type at all.
assert_eq!(typed("m"), None);
assert_eq!(typed("f"), None);
}
/// An **array** of instances is not typed, on the same rule an unpacked
/// declarator follows: `bank[0].port` is reached through an index, which is
/// not a head this crate types.
#[test]
fn an_instance_array_carries_no_type() {
let src = "module m;\n sub bank[3:0] ();\n sub one ();\nendmodule\n";
let s = sem(src);
let typed = |name: &str| s.symbol(symbol_named(&s, name)).and_then(|sym| sym.type_name.clone());
assert_eq!(typed("bank"), None);
assert_eq!(typed("one"), Some("sub".to_string()), "the premise: a plain instance is typed");
}
/// A non-ANSI port is named in the header and typed in the body; the type
/// lands on the header symbol, the way its detail span does.
#[test]
fn a_non_ansi_ports_type_is_recorded_from_its_body_declaration() {
let src = "module m(bus);\n input my_if bus;\nendmodule\n";
let s = sem(src);
assert_eq!(
s.symbol(symbol_named(&s, "bus")).and_then(|sym| sym.type_name.clone()),
Some("my_if".to_string())
);
}
/// The shapes that must go on recording nothing: a built-in type, a head this
/// file does not declare, a block label, and a member a fully-known class
/// simply does not have. (A module instance head was one of these until round
/// 2 typed it — see `an_instance_head_reaches_its_modules_signals`.)
#[test]
fn a_head_this_crate_cannot_type_records_no_tail_at_all() {
let src = "\
class c1;
int known;
endclass
module m;
logic [3:0] x;
c1 h;
if (1) begin : blk
wire inner;
end
initial begin
y = x.bit_field;
y = stranger.thing;
y = blk.inner;
y = h.absent;
y = h.known;
end
endmodule
";
let s = sem(src);
for (spelling, why) in [
("x.bit_field", "a built-in type names no declaration"),
("stranger.thing", "the head is not declared here"),
("h.absent", "the class is known whole and has no such member"),
] {
assert!(s.reference_at(tail(src, spelling, 0)).is_none(), "{spelling}: {why}");
}
// The one that does resolve, so the test is not vacuous.
assert_eq!(
resolution_at(&s, tail(src, "h.known", 0)),
Resolution::Resolved(symbol_named(&s, "known"))
);
// A generate block label was on the list above until TODO §65.1: a named
// block opens a scope a path may select from (IEEE 1800 §23.6), so its
// member resolves (`docs/features/generate-label-rename/README.md`).
assert_eq!(
resolution_at(&s, tail(src, "blk.inner", 0)),
Resolution::Resolved(symbol_named(&s, "inner"))
);
}
/// `this.x` walks the `extends` chain as far as this file declares it.
#[test]
fn this_reaches_an_inherited_member_declared_in_this_file() {
let src = "\
class u1;
bit base_field;
endclass
class c1 extends u1;
function void f();
this.base_field = 1;
endfunction
endclass
";
let s = sem(src);
assert_eq!(
resolution_at(&s, tail(src, "this.base_field", 0)),
Resolution::Resolved(symbol_named(&s, "base_field"))
);
}
/// Two hops up, in one file, and a cycle in `extends` terminates.
#[test]
fn the_in_file_chase_climbs_two_hops_and_survives_a_cycle() {
let src = "\
class grand;
bit deep;
endclass
class mid extends grand;
endclass
class leaf extends mid;
endclass
class ring_a extends ring_b;
endclass
class ring_b extends ring_a;
endclass
module m;
leaf h;
ring_a r;
initial begin
y = h.deep;
y = r.nothing;
end
endmodule
";
let s = sem(src);
assert_eq!(
resolution_at(&s, tail(src, "h.deep", 0)),
Resolution::Resolved(symbol_named(&s, "deep"))
);
// The cycle is walked once per class and then given up on — no reference,
// and above all no hang.
assert!(s.reference_at(tail(src, "r.nothing", 0)).is_none());
}
/// A type this file does not declare is the workspace's business, and the
/// path is spelled the way `follow_one` reads it — the unit's last `::`
/// segment, then the member.
#[test]
fn a_type_declared_elsewhere_becomes_an_external_candidate() {
let src = "\
module m;
c1 h;
pkg::c2 q;
initial begin
y = h.user_id;
y = q.other;
end
endmodule
";
let s = sem(src);
assert_eq!(
resolution_at(&s, tail(src, "h.user_id", 0)),
Resolution::ExternalCandidate {
paths: vec!["c1::user_id".to_string()],
surface: Surface::Connection,
}
);
assert_eq!(
resolution_at(&s, tail(src, "q.other", 0)),
Resolution::ExternalCandidate {
paths: vec!["c2::other".to_string()],
surface: Surface::Connection,
}
);
}
// ----------------------------------------------------------------------
// a type this file declares as something with no members
//
// QA finding 1, 2026-09-01 (REWORK): the first cut asked the workspace about
// *any* type name it could not turn into a scope, including one this file
// declares as a typedef — so an unrelated same-named class in another file
// answered `s.field`. A wrong answer, where recording nothing is a missing
// one. The four tests below are the QA repros, folded in as permanent pins.
//
// **Amended 2026-09-01 by struct-members** (`docs/features/struct-members/
// README.md`): a struct typedef *is* something with members now, so the two
// struct-shaped pins here assert the in-file answer instead of silence. The
// rule they were written for is untouched and is exactly what the
// stranger-class pin below still measures: this file's own declaration
// answers, and no same-named unit elsewhere ever gets asked.
// ----------------------------------------------------------------------
/// A struct typedef declared in this file: the file has said what the type is,
/// and since struct-members that answer has fields to look in.
#[test]
fn a_struct_typedef_typed_head_resolves_its_own_field() {
let src = "\
typedef struct packed { bit field; } s_t;
module m;
s_t s;
initial y = s.field;
endmodule
";
let s = sem(src);
assert_eq!(
resolution_at(&s, tail(src, "s.field", 0)),
Resolution::Resolved(symbol_named(&s, "field"))
);
// A field the struct does not have is still nothing at all: the body is
// written here whole, so no other file can supply it.
let absent = "\
typedef struct packed { bit field; } s_t;
module m;
s_t s;
initial y = s.missing;
endmodule
";
let s = sem(absent);
assert!(s.reference_at(tail(absent, "s.missing", 0)).is_none());
}
/// The same for a plain alias and for an enum typedef — the rule is about the
/// *kind* the file declares, not about structs.
#[test]
fn an_alias_or_enum_typedef_typed_head_records_nothing() {
let src = "\
typedef int alias_t;
typedef enum { IDLE, RUN } state_e;
module m;
alias_t v;
state_e st;
initial begin
y = v.whatever;
y = st.whatever;
end
endmodule
";
let s = sem(src);
assert!(s.reference_at(tail(src, "v.whatever", 0)).is_none());
assert!(s.reference_at(tail(src, "st.whatever", 0)).is_none());
}
/// The wrong answer this rule exists to prevent, end to end: file A declares
/// `bus_t` as a struct, file B declares an unrelated **class** `bus_t` with a
/// member of the same name. `s.field` in A must not land in B.
#[test]
fn a_local_typedef_is_never_looked_up_in_a_same_named_class_elsewhere() {
const A: &str = "\
typedef struct packed { bit field; } bus_t;
module m;
bus_t s;
initial y = s.field;
endmodule
";
const B: &str = "class bus_t;\n bit field;\nendclass\n";
let ws = index(&[("a.sv", A), ("b.sv", B)]);
assert!(
overlay_def(&ws, A, tail(A, "s.field", 0)).is_none(),
"the struct's field is not the stranger class's property"
);
// The premise: B really does export a `field` the sweep would have found —
// and since struct-members so does A's own struct, which is exactly why
// the reference above is answered in this file and never handed over.
assert_eq!(ws.member("bus_t", "field").len(), 2, "two same-named exports, one right answer");
let s = sem(A);
assert_eq!(
resolution_at(&s, tail(A, "s.field", 0)),
Resolution::Resolved(symbol_named(&s, "field")),
"answered in this file, by this file's own struct"
);
}
/// A `typedef` that really is a class alias — `typedef c1 my_t;` — is
/// **followed** to the class (round 2); a `typedef class c1;` forward
/// declaration still records nothing.
///
/// The difference is what the file says: an alias names a type this file can
/// look up, and following the name it wrote is not the guess round 1 refused
/// (that one invented a class from a *struct* typedef's name). A forward
/// declaration names no type at all — it is a `Typedef` with nothing to
/// follow — so it stays exactly what it was.
#[test]
fn a_typedef_alias_of_a_class_is_followed_and_a_forward_declaration_is_not() {
let alias = "\
class c1;
bit user_id;
endclass
typedef c1 my_t;
typedef my_t your_t;
module m;
my_t h;
your_t g;
initial begin
y = h.user_id;
y = g.user_id;
end
endmodule
";
let s = sem(alias);
// One hop, and two.
assert_eq!(
resolution_at(&s, tail(alias, "h.user_id", 0)),
Resolution::Resolved(symbol_named(&s, "user_id"))
);
assert_eq!(
resolution_at(&s, tail(alias, "g.user_id", 0)),
Resolution::Resolved(symbol_named(&s, "user_id"))
);
// The forward-declaration spelling, cross-file, where the workspace does
// hold the class: still nothing, because the typedef names no type.
const FWD: &str = "\
typedef class c1;
module m;
c1 h;
initial y = h.user_id;
endmodule
";
let ws = index(&[("c1.sv", C1), ("u1.sv", BASE), ("fwd.sv", FWD)]);
assert!(overlay_def(&ws, FWD, tail(FWD, "h.user_id", 0)).is_none());
// The premise: without the forward declaration the same use resolves, so
// this test is about the typedef and nothing else.
const PLAIN: &str = "module m;\n c1 h;\n initial y = h.user_id;\nendmodule\n";
assert!(overlay_def(&ws, PLAIN, tail(PLAIN, "h.user_id", 0)).is_some());
}
/// An alias that aliases itself, and a pair that alias each other: the walk
/// terminates and records nothing, rather than looping.
#[test]
fn an_alias_cycle_terminates() {
let src = "\
typedef b_t a_t;
typedef a_t b_t;
module m;
a_t h;
initial y = h.anything;
endmodule
";
let s = sem(src);
assert!(s.reference_at(tail(src, "h.anything", 0)).is_none());
}
/// An alias of a struct is followed to the struct, exactly as an alias of a
/// class is followed to the class — the round-2 rule, now that the far end of
/// the hop has members (struct-members, 2026-09-01).
#[test]
fn an_alias_of_a_struct_is_followed_to_its_fields() {
let src = "\
typedef struct packed { bit field; } s_t;
typedef s_t alias_t;
module m;
alias_t s;
initial y = s.field;
endmodule
";
let s = sem(src);
assert_eq!(
resolution_at(&s, tail(src, "s.field", 0)),
Resolution::Resolved(symbol_named(&s, "field"))
);
}
/// A qualified type name whose *package* is in this file but whose tail is a
/// typedef in it: the package is fully known here, so the answer is the same
/// "nothing" — never a sweep of the workspace for the bare tail.
#[test]
fn a_qualified_type_inside_an_in_file_package_records_nothing_unless_it_is_a_class() {
let src = "\
package p;
typedef int alias_t;
endpackage
module m;
p::alias_t v;
p::missing_t w;
initial begin
y = v.whatever;
y = w.whatever;
end
endmodule
";
let s = sem(src);
assert!(
s.reference_at(tail(src, "v.whatever", 0)).is_none(),
"a typedef in an in-file package"
);
assert!(
s.reference_at(tail(src, "w.whatever", 0)).is_none(),
"a name the in-file package does not declare is not the workspace's to answer either"
);
}
/// But a qualified type whose *package* this file does not declare is exactly
/// what the workspace can answer, and still is.
#[test]
fn a_qualified_type_from_a_package_elsewhere_still_reaches_the_workspace() {
let src = "module m;\n pkg::c1 h;\n initial y = h.user_id;\nendmodule\n";
let s = sem(src);
assert_eq!(
resolution_at(&s, tail(src, "h.user_id", 0)),
Resolution::ExternalCandidate {
paths: vec!["c1::user_id".to_string()],
surface: Surface::Connection,
}
);
}
/// A qualified type name is descended segment by segment: the package is
/// walked *through*, and the class at the end is what the member is looked up
/// in.
#[test]
fn a_package_qualified_type_resolves_through_the_package() {
let src = "\
package p;
class c1;
bit user_id;
endclass
endpackage
module m;
p::c1 h;
initial y = h.user_id;
endmodule
";
let s = sem(src);
assert_eq!(
resolution_at(&s, tail(src, "h.user_id", 0)),
Resolution::Resolved(symbol_named(&s, "user_id"))
);
}
/// A member of a base the file does not hold records the base, plus the path
/// that answers it one hop up.
#[test]
fn a_member_missing_from_an_in_file_class_with_an_outside_base_is_inherited() {
let src = "\
class c1 extends uvm_sequence_item;
bit own;
endclass
module m;
c1 h;
initial y = h.borrowed;
endmodule
";
let s = sem(src);
assert_eq!(
resolution_at(&s, tail(src, "h.borrowed", 0)),
Resolution::InheritedCandidate {
base: "uvm_sequence_item".to_string(),
paths: vec!["uvm_sequence_item::borrowed".to_string()],
}
);
}
/// An out-of-class body whose class is declared elsewhere still sees that
/// class: the miss is recorded against it for the index to finish.
#[test]
fn an_out_of_class_body_for_a_class_elsewhere_records_its_class() {
let src = "task class2::update(int v);\n address = v;\nendtask\n";
let s = sem(src);
assert_eq!(
resolution_at(&s, nth(src, "address", 0)),
Resolution::InheritedCandidate { base: "class2".to_string(), paths: Vec::new() }
);
}
// ----------------------------------------------------------------------
// across files
// ----------------------------------------------------------------------
/// The owner's three files, split: every member answers through the index,
/// including the inherited one, which is two lookups up the chain.
#[test]
fn the_owners_example_resolves_across_three_files() {
let ws = index(&[("base.sv", BASE), ("c1.sv", C1), ("class2.sv", CLASS2)]);
for (spelling, expected, file) in [
("in_item.user_id", "user_id", "c1.sv"),
("in_item.feature1", "feature1", "c1.sv"),
("in_item.base_field", "base_field", "base.sv"),
] {
let def = overlay_def(&ws, CLASS2, tail(CLASS2, spelling, 0))
.unwrap_or_else(|| panic!("{spelling} is unanswered"));
assert_eq!(file_name(&ws, &def), file, "{spelling}");
assert_eq!(def.kind, SymbolKind::Var);
let src = if file == "c1.sv" { C1 } else { BASE };
assert_eq!(
&src[def.name_span.as_range()],
expected,
"{spelling} lands on the declared name"
);
}
}
/// The same, with `class2` itself in another file: the left-hand sides of the
/// out-of-class body resolve through the index too.
#[test]
fn an_out_of_class_body_reaches_its_class_across_files() {
const DECL: &str = "class class2;\n bit address;\nendclass\n";
const BODY: &str = "task class2::update(int v);\n address = v;\nendtask\n";
let ws = index(&[("decl.sv", DECL), ("body.sv", BODY)]);
let def = overlay_def(&ws, BODY, nth(BODY, "address", 0)).expect("the property");
assert_eq!(file_name(&ws, &def), "decl.sv");
assert_eq!(&DECL[def.name_span.as_range()], "address");
}
/// The chase climbs the workspace's `extends` edges, two hops, and stops at a
/// base nothing declares — with no answer and no panic.
#[test]
fn the_index_chase_climbs_two_hops_and_gives_up_on_an_unknown_base() {
const GRAND: &str = "class grand;\n bit deep;\nendclass\n";
const MID: &str = "class mid extends grand;\nendclass\n";
const LEAF: &str = "class leaf extends mid;\nendclass\n";
const USE: &str = "module m;\n leaf h;\n initial y = h.deep;\nendmodule\n";
let ws = index(&[("grand.sv", GRAND), ("mid.sv", MID), ("leaf.sv", LEAF)]);
let def = overlay_def(&ws, USE, tail(USE, "h.deep", 0)).expect("two hops up");
assert_eq!(file_name(&ws, &def), "grand.sv");
// The same use against a workspace that stops at `mid`: nothing to find,
// and nothing recorded.
let short = index(&[("mid.sv", MID), ("leaf.sv", LEAF)]);
assert!(overlay_def(&short, USE, tail(USE, "h.deep", 0)).is_none());
}
/// A cycle written across files terminates the chase — the visited set, not
/// the workspace, is what bounds it.
#[test]
fn a_cross_file_extends_cycle_terminates() {
const A: &str = "class a extends b;\n bit only_a;\nendclass\n";
const B: &str = "class b extends a;\n bit only_b;\nendclass\n";
const USE: &str = "module m;\n a h;\n initial y = h.absent;\nendmodule\n";
let ws = index(&[("a.sv", A), ("b.sv", B)]);
assert_eq!(ws.base_of("a"), Some("b"));
assert_eq!(ws.base_of("b"), Some("a"));
assert!(overlay_def(&ws, USE, tail(USE, "h.absent", 0)).is_none());
// And a member that *is* on the cycle is found, one hop around.
const USE_B: &str = "module m;\n a h;\n initial y = h.only_b;\nendmodule\n";
let def = overlay_def(&ws, USE_B, tail(USE_B, "h.only_b", 0)).expect("one hop around");
assert_eq!(file_name(&ws, &def), "b.sv");
}
/// `this.x` and `super.x` misses reach an inherited member across files —
/// topo §2.9-9, delivered by the same chase.
#[test]
fn this_and_super_reach_inherited_members_across_files() {
const BASE_C: &str = "class base_c;\n bit held;\nendclass\n";
const CHILD: &str = "class child extends base_c;\n function void f();\n this.held = 1;\n super.held = 2;\n endfunction\nendclass\n";
let ws = index(&[("base_c.sv", BASE_C), ("child.sv", CHILD)]);
for spelling in ["this.held", "super.held"] {
let def = overlay_def(&ws, CHILD, tail(CHILD, spelling, 0))
.unwrap_or_else(|| panic!("{spelling} is unanswered"));
assert_eq!(file_name(&ws, &def), "base_c.sv", "{spelling}");
}
}
/// A base the workspace does not hold at all — the UVM shape, where
/// `uvm_sequence_item` is vendored somewhere outside the index — answers
/// nothing, quietly.
#[test]
fn a_base_outside_the_workspace_answers_nothing() {
const ITEM: &str = "class my_item extends uvm_sequence_item;\n bit own;\nendclass\n";
const USE: &str = "module m;\n my_item h;\n initial y = h.get_name;\nendmodule\n";
let ws = index(&[("item.sv", ITEM)]);
assert_eq!(ws.base_of("my_item"), Some("uvm_sequence_item"));
assert!(overlay_def(&ws, USE, tail(USE, "h.get_name", 0)).is_none());
// The class's own member still answers.
const OWN: &str = "module m;\n my_item h;\n initial y = h.own;\nendmodule\n";
assert!(overlay_def(&ws, OWN, tail(OWN, "h.own", 0)).is_some());
}
// ----------------------------------------------------------------------
// the reverse edge table
// ----------------------------------------------------------------------
/// `base_of` is maintained through every mutation the index offers, and each
/// one leaves the table a fresh build would have produced.
#[test]
fn base_of_survives_every_index_mutation() {
const A: &str = "class a extends grand;\nendclass\n";
const B: &str = "class b extends a;\nendclass\n";
const C: &str = "class c extends b;\nendclass\n";
let all = [("a.sv", A), ("b.sv", B), ("c.sv", C)];
let built = index(&all);
assert_eq!(built.base_of("a"), Some("grand"));
assert_eq!(built.base_of("b"), Some("a"));
assert_eq!(built.base_of("c"), Some("b"));
assert_eq!(built.base_of("grand"), None, "a class nothing extends has no base");
// update_file over an existing file
let mut updated = index(&all);
updated.update_file(PathBuf::from("b.sv"), "class b extends grand;\nendclass\n");
let fresh = index(&[("a.sv", A), ("b.sv", "class b extends grand;\nendclass\n"), ("c.sv", C)]);
assert_eq!(updated.base_of("b"), Some("grand"));
assert_eq!(updated.fingerprint(), fresh.fingerprint());
// update_file adding a file
let mut added = index(&[("a.sv", A), ("b.sv", B)]);
added.update_file(PathBuf::from("c.sv"), C);
assert_eq!(added.base_of("c"), Some("b"));
assert_eq!(added.fingerprint(), index(&all).fingerprint());
// remove_file
let mut removed = index(&all);
assert!(removed.remove_file(std::path::Path::new("b.sv")));
assert_eq!(removed.base_of("b"), None);
assert_eq!(removed.base_of("c"), Some("b"), "c still says what it extends");
assert_eq!(removed.fingerprint(), index(&[("a.sv", A), ("c.sv", C)]).fingerprint());
// absorb, adding and dropping in one merge
let mut absorbed = index(&[("a.sv", A), ("b.sv", B)]);
absorbed.absorb(
vec![vlog_semantic::FileFacts::of(PathBuf::from("c.sv"), C)],
&[PathBuf::from("a.sv")],
);
assert_eq!(absorbed.base_of("a"), None);
assert_eq!(absorbed.base_of("c"), Some("b"));
assert_eq!(absorbed.fingerprint(), index(&[("b.sv", B), ("c.sv", C)]).fingerprint());
}
/// Two classes of the same name extending different bases: the first in
/// disambiguation order wins, which is the policy the unit table applies.
#[test]
fn a_duplicated_class_name_takes_the_first_base_in_path_order() {
let ws = index(&[
("zzz.sv", "class dup extends late;\nendclass\n"),
("aaa.sv", "class dup extends early;\nendclass\n"),
]);
assert_eq!(ws.base_of("dup"), Some("early"));
}
// ----------------------------------------------------------------------
// round 2: chains, instance heads
// ----------------------------------------------------------------------
/// The chain fixtures, split so the same three classes can be one file or
/// three. `driver` reads `item.hdr.addr` — two links past the head.
const HDR: &str = "class hdr_t;\n bit [7:0] addr;\nendclass\n";
const ITEM: &str = "class item_t;\n hdr_t hdr;\nendclass\n";
const DRIVER: &str =
"class driver;\n item_t item;\n task go();\n x = item.hdr.addr;\n endtask\nendclass\n";
/// Offset of the `n`th middle link of `head.mid.tail`, spelled as `needle`.
fn mid(src: &str, needle: &str, n: usize) -> u32 {
let at = nth(src, needle, n);
at + needle.find('.').expect("a member access") as u32 + 1
}
/// `a.b.c` in one file: each link is a reference of its own, and the tail is
/// looked up in the type of the link before it.
#[test]
fn a_chain_resolves_link_by_link_in_one_file() {
let src = format!("{HDR}{ITEM}{DRIVER}");
let s = sem(&src);
let head = s.reference_at(nth(&src, "item.hdr.addr", 0)).expect("the head");
assert_eq!(head.resolved(), Some(symbol_named(&s, "item")));
assert_eq!(
resolution_at(&s, mid(&src, "item.hdr.addr", 0)),
Resolution::Resolved(symbol_named(&s, "hdr"))
);
assert_eq!(
resolution_at(&s, tail(&src, "item.hdr.addr", 0)),
Resolution::Resolved(symbol_named(&s, "addr"))
);
}
/// The same chain with each type in a different file, and the index built in
/// both orders: the tail is one composed path (`item_t::hdr::addr`) the
/// workspace walks member by member.
#[test]
fn a_chain_resolves_across_three_files() {
assert_eq!(
resolution_at(&sem(DRIVER), tail(DRIVER, "item.hdr.addr", 0)),
Resolution::ExternalCandidate {
paths: vec!["item_t::hdr::addr".to_string()],
surface: Surface::Connection,
},
"the single-file layer composes the path and stops"
);
for order in [
[("a_hdr.sv", HDR), ("b_item.sv", ITEM), ("c_driver.sv", DRIVER)],
[("z_driver.sv", DRIVER), ("y_item.sv", ITEM), ("x_hdr.sv", HDR)],
] {
let ws = index(&order);
let tail_def =
overlay_def(&ws, DRIVER, tail(DRIVER, "item.hdr.addr", 0)).expect("the tail");
assert_eq!(tail_def.kind, SymbolKind::Var);
assert!(file_name(&ws, &tail_def).contains("hdr"), "{:?}", file_name(&ws, &tail_def));
// And the middle link is answered in its own file.
let mid_def = overlay_def(&ws, DRIVER, mid(DRIVER, "item.hdr.addr", 0)).expect("the mid");
assert!(file_name(&ws, &mid_def).contains("item"), "{:?}", file_name(&ws, &mid_def));
}
}
/// A link whose type is a **struct** used to stop the chain; since
/// struct-members it carries it on, in this file, to the struct's own field.
///
/// The cross-file half is the pin that has not moved and must not: with an
/// unrelated *class* `hdr_t` in another file, the workspace declares the name
/// twice and `member_type` refuses the hop rather than picking one. Two
/// declarations are two answers; the struct's field is not the stranger's
/// property, and a guess between them is the one forbidden outcome.
#[test]
fn a_chain_continues_through_a_struct_link() {
const STRUCT_HDR: &str = "typedef struct packed { bit [7:0] addr; } hdr_t;\n";
let src = format!("{STRUCT_HDR}{ITEM}{DRIVER}");
let s = sem(&src);
assert_eq!(
resolution_at(&s, mid(&src, "item.hdr.addr", 0)),
Resolution::Resolved(symbol_named(&s, "hdr")),
"the premise: the link before resolves"
);
assert_eq!(
resolution_at(&s, tail(&src, "item.hdr.addr", 0)),
Resolution::Resolved(symbol_named(&s, "addr")),
"and the chain now walks into the struct"
);
// Across files, where a class named `hdr_t` also exists somewhere else:
// the composed path must not reach it — and must not reach the struct's
// own `addr` either, because nothing here can tell which `hdr_t` was meant.
let ws = index(&[
("hdr.sv", STRUCT_HDR),
("item.sv", ITEM),
("driver.sv", DRIVER),
("stranger.sv", "class hdr_t;\n bit [7:0] addr;\nendclass\n"),
]);
assert_eq!(ws.units("hdr_t").len(), 2, "the premise: the workspace declares it twice");
assert!(
overlay_def(&ws, DRIVER, tail(DRIVER, "item.hdr.addr", 0)).is_none(),
"a struct's field is not a stranger class's property"
);
// Without the stranger, the same chain lands on the struct's field.
let ws = index(&[("hdr.sv", STRUCT_HDR), ("item.sv", ITEM), ("driver.sv", DRIVER)]);
let def = overlay_def(&ws, DRIVER, tail(DRIVER, "item.hdr.addr", 0)).expect("the tail");
assert_eq!(def.kind, SymbolKind::StructMember);
assert!(file_name(&ws, &def).contains("hdr"), "{:?}", file_name(&ws, &def));
}
/// A chain through a member the head's class **inherits**: the middle link is
/// found up the `extends` chain, and its type carries the chain on.
#[test]
fn a_chain_walks_through_an_inherited_member() {
let src = "\
class inner;
bit x;
endclass
class base;
inner base_member;
endclass
class kid extends base;
endclass
module m;
kid h;
initial y = h.base_member.x;
endmodule
";
let s = sem(src);
assert_eq!(
resolution_at(&s, mid(src, "h.base_member.x", 0)),
Resolution::Resolved(symbol_named(&s, "base_member"))
);
assert_eq!(
resolution_at(&s, tail(src, "h.base_member.x", 0)),
Resolution::Resolved(symbol_named(&s, "x"))
);
}
// ----------------------------------------------------------------------
// instance heads
// ----------------------------------------------------------------------
/// An instance's type is the module it instantiates, so both a port and an
/// internal signal of that module resolve when the module is in this file.
#[test]
fn an_instance_head_reaches_its_modules_signals() {
let src = "\
module sub (input wire clk_i);
wire internal;
endmodule
module m;
sub u ();
initial begin
y = u.clk_i;
y = u.internal;
y = u.absent;
end
endmodule
";
let s = sem(src);
assert_eq!(
resolution_at(&s, tail(src, "u.clk_i", 0)),
Resolution::Resolved(symbol_named(&s, "clk_i"))
);
assert_eq!(
resolution_at(&s, tail(src, "u.internal", 0)),
Resolution::Resolved(symbol_named(&s, "internal"))
);
assert!(
s.reference_at(tail(src, "u.absent", 0)).is_none(),
"a module known whole has no such signal, and a module extends nothing"
);
}
/// Across files, an instance head reaches what the index holds for the module
/// on its **hierarchical** surface: its ports and parameters, and — since
/// 2026-09-05 — its internal nets and variables too, because `u.internal` is
/// a hierarchical path and IEEE 1800 §23.6 says a hierarchical path may name
/// any of them (`docs/features/hierarchical-tail/README.md`). A `.internal(w)`
/// *connection* is still refused: that reads the connection surface.
#[test]
fn an_instance_head_reaches_a_module_in_another_file() {
const SUB: &str =
"module sub #(parameter int W = 8) (input wire clk_i);\n wire internal;\nendmodule\n";
const TOP: &str = "module m;\n sub u ();\n initial begin\n y = u.clk_i;\n y = u.W;\n y = u.internal;\n end\nendmodule\n";
assert_eq!(
resolution_at(&sem(TOP), tail(TOP, "u.clk_i", 0)),
// An instance head is a hierarchical path, and its tail reads the
// module's hierarchical surface — which holds the connection surface
// whole, so a *port* named through one has exactly one answer.
Resolution::ExternalCandidate {
paths: vec!["sub::clk_i".to_string()],
surface: Surface::Hierarchical,
}
);
let ws = index(&[("sub.sv", SUB), ("top.sv", TOP)]);
let port = overlay_def(&ws, TOP, tail(TOP, "u.clk_i", 0)).expect("the port");
assert_eq!(port.kind, SymbolKind::Port);
let param = overlay_def(&ws, TOP, tail(TOP, "u.W", 0)).expect("the parameter");
assert_eq!(param.kind, SymbolKind::Param);
// An internal net is reached hierarchically and nowhere else: the tail
// resolves to `sub`'s own declaration of it...
let net = overlay_def(&ws, TOP, tail(TOP, "u.internal", 0)).expect("the internal net");
assert_eq!(net.kind, SymbolKind::Net);
// ...while the connection surface — what a `.internal(w)` connection and a
// connection list's completion read — still does not hold it.
assert!(ws.member("sub", "internal").is_empty());
assert_eq!(ws.member("sub", "clk_i").len(), 1, "a port is on both surfaces, once");
}
/// The spines a chain is **not** walked from, each still resolving whatever
/// it can of itself: an index, a call, and anything past one member of
/// `this`. Each needs a type this crate does not carry across the construct.
#[test]
fn a_spine_this_crate_cannot_walk_stops_where_it_always_did() {
let src = "\
class hdr_t;
bit [7:0] addr;
endclass
class item_t;
hdr_t hdr;
function item_t make();
endfunction
endclass
class driver;
item_t pool[4];
item_t item;
task go();
x = pool[0].hdr;
x = make().hdr;
x = this.item.hdr;
endtask
endclass
";
let s = sem(src);
for (spelling, why) in [
("pool[0].hdr", "an indexed head names a container, not a value"),
("make().hdr", "a call's result is a type this crate does not evaluate"),
("this.item.hdr", "`this` binds no symbol to take a type from"),
] {
assert!(s.reference_at(tail(src, spelling, 0)).is_none(), "{spelling}: {why}");
}
// The link before the `this` chain's break is still answered, so the stop
// costs exactly one tail and not the reference before it.
assert_eq!(
resolution_at(&s, mid(src, "this.item.hdr", 0)),
Resolution::Resolved(symbol_named(&s, "item"))
);
}
/// A hierarchical path through three instances, rooted at a module name —
/// `tb.dut_i.u_core.sig`, the testbench spelling. Every link is a reference,
/// and the last one lands on the signal.
#[test]
fn a_hierarchical_path_walks_every_link() {
let src = "\
module core (input wire sig);
wire deep;
endmodule
module dut;
core u_core ();
endmodule
module tb;
dut dut_i ();
endmodule
module probe;
initial y = tb.dut_i.u_core.sig;
endmodule
";
let s = sem(src);
let head = s.reference_at(nth(src, "tb.dut_i.u_core.sig", 0)).expect("the head");
assert_eq!(head.resolved(), Some(symbol_named(&s, "tb")));
assert_eq!(
resolution_at(&s, mid(src, "tb.dut_i.u_core.sig", 0)),
Resolution::Resolved(symbol_named(&s, "dut_i"))
);
assert_eq!(
resolution_at(&s, tail(src, "tb.dut_i.u_core.sig", 0)),
Resolution::Resolved(symbol_named(&s, "sig"))
);
}
/// The same path with the leaf module in another file: the chain leaves this
/// file at the last type it knows and arrives as one composed path.
#[test]
fn a_hierarchical_path_crosses_a_file_boundary() {
const CORE: &str = "module core (input wire sig);\nendmodule\n";
const TB: &str = "module dut;\n core u_core ();\nendmodule\n\nmodule tb;\n dut dut_i ();\nendmodule\n\nmodule probe;\n initial y = tb.dut_i.u_core.sig;\nendmodule\n";
assert_eq!(
resolution_at(&sem(TB), tail(TB, "tb.dut_i.u_core.sig", 0)),
Resolution::ExternalCandidate {
paths: vec!["core::sig".to_string()],
surface: Surface::Hierarchical,
}
);
let ws = index(&[("core.sv", CORE), ("tb.sv", TB)]);
let def = overlay_def(&ws, TB, tail(TB, "tb.dut_i.u_core.sig", 0)).expect("the leaf signal");
assert_eq!(def.kind, SymbolKind::Port);
assert_eq!(file_name(&ws, &def), "core.sv");
}
// ----------------------------------------------------------------------
// index postings
// ----------------------------------------------------------------------
/// Round 1's residue, closed: a use whose only handle on its declaration is
/// the recorded **base** — `this.x` inside a class extending another file's —
/// now has an index posting, so find-references from the declaration side
/// lists it.
#[test]
fn a_this_member_of_a_base_elsewhere_is_listed_from_the_declaration() {
const BASE_FILE: &str = "class u1;\n bit base_field;\nendclass\n";
const KID: &str =
"class kid extends u1;\n task go();\n this.base_field = 1;\n endtask\nendclass\n";
let ws = index(&[("base.sv", BASE_FILE), ("kid.sv", KID)]);
let def = ws.member("u1", "base_field").first().expect("the declaration").clone();
let sites = ws.references_to(&def);
assert_eq!(sites.len(), 1, "the cross-file `this.` use is posted: {sites:?}");
assert_eq!(ws.path(sites[0].file).and_then(|p| p.file_name()).unwrap(), "kid.sv");
assert_eq!(&KID[sites[0].name_span.as_range()], "base_field");
// And the overlay says the same thing, which is the property that keeps a
// rename from editing one and not the other.
let overlay = overlay_def(&ws, KID, nth(KID, "base_field = 1", 0)).expect("the overlay answer");
assert_eq!(overlay, def);
}
/// A chain tail posts to the index exactly as it resolves in the overlay, so
/// a rename fanning out from the declaration finds it.
#[test]
fn a_chain_tail_is_posted_to_the_declaration_it_names() {
let ws = index(&[("hdr.sv", HDR), ("item.sv", ITEM), ("driver.sv", DRIVER)]);
let def = ws.member("hdr_t", "addr").first().expect("the declaration").clone();
let sites = ws.references_to(&def);
assert_eq!(sites.len(), 1, "{sites:?}");
assert_eq!(ws.path(sites[0].file).and_then(|p| p.file_name()).unwrap(), "driver.sv");
assert_eq!(&DRIVER[sites[0].name_span.as_range()], "addr");
}
/// The declared type survives the record format, and the chain answers the
/// same through every mutation the index offers — the equalities every table
/// here owes.
#[test]
fn a_chain_survives_the_record_format_and_every_index_mutation() {
let all = [("hdr.sv", HDR), ("item.sv", ITEM), ("driver.sv", DRIVER)];
let built = index(&all);
assert_eq!(
built.member("item_t", "hdr").first().and_then(|d| d.type_name.clone()),
Some("hdr_t".to_string()),
"the index carries the declared type"
);
// Through the record format and back.
let mut builder = vlog_semantic::IndexBuilder::new();
for (name, src) in all {
let facts = vlog_semantic::FileFacts::of(PathBuf::from(name), src);
let encoded = facts.encode().expect("encodes");
builder.add_facts(vlog_semantic::FileFacts::decode(&encoded).expect("decodes"));
}
assert_eq!(builder.finish().fingerprint(), built.fingerprint());
// update_file over an existing file, adding a file, removing one, and an
// absorb: each leaves the index a fresh build would have produced.
let mut updated = index(&all);
updated.update_file(PathBuf::from("item.sv"), ITEM);
assert_eq!(updated.fingerprint(), built.fingerprint());
let mut added = index(&[("hdr.sv", HDR), ("item.sv", ITEM)]);
added.update_file(PathBuf::from("driver.sv"), DRIVER);
assert_eq!(added.fingerprint(), built.fingerprint());
assert!(overlay_def(&added, DRIVER, tail(DRIVER, "item.hdr.addr", 0)).is_some());
let mut removed = index(&all);
assert!(removed.remove_file(std::path::Path::new("hdr.sv")));
assert_eq!(
removed.fingerprint(),
index(&[("item.sv", ITEM), ("driver.sv", DRIVER)]).fingerprint()
);
assert!(
overlay_def(&removed, DRIVER, tail(DRIVER, "item.hdr.addr", 0)).is_none(),
"the chain's last hop is gone with the file that typed it"
);
let mut absorbed = index(&[("item.sv", ITEM), ("driver.sv", DRIVER)]);
absorbed.absorb(vec![vlog_semantic::FileFacts::of(PathBuf::from("hdr.sv"), HDR)], &[]);
assert_eq!(absorbed.fingerprint(), built.fingerprint());
}
/// Two declarations of the middle link's type name are two answers, and this
/// layer picks between candidates nowhere: the chain stops rather than
/// guessing which `hdr_t` was meant.
#[test]
fn an_ambiguous_hop_answers_nothing() {
let ws =
index(&[("hdr.sv", HDR), ("hdr_too.sv", HDR), ("item.sv", ITEM), ("driver.sv", DRIVER)]);
assert_eq!(ws.units("hdr_t").len(), 2, "the premise: the workspace declares it twice");
let def = overlay_def(&ws, DRIVER, tail(DRIVER, "item.hdr.addr", 0));
assert!(def.is_none() || ws.member("hdr_t", "addr").len() == 2);
}
// ----------------------------------------------------------------------
// measurement
// ----------------------------------------------------------------------
/// What this round costs the index, over the real corpus: how many references
/// a file's record holds, how many bytes the record is, and how long a whole
/// build takes.
///
/// `#[ignore]`d, asserting nothing — the house shape for a measurement probe
/// (`crates/lucisv_server/src/perf.rs`). It reads only pre-existing public
/// API, so the same file can be dropped into a checkout of an older revision
/// to produce the "before" column. Run with
/// `cargo test -p vlog_semantic --test member_access -- --ignored --nocapture`.
#[test]
#[ignore = "measurement over corpus/, printed rather than asserted"]
fn what_the_tail_references_cost_the_index() {
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 files = Vec::new();
collect(&root, &mut files);
files.sort();
let start = std::time::Instant::now();
let mut bytes = 0usize;
let mut records = 0usize;
let mut builder = vlog_semantic::IndexBuilder::new();
for path in &files {
let Ok(src) = std::fs::read_to_string(path) else {
continue;
};
let facts = vlog_semantic::FileFacts::of(path.clone(), &src);
bytes += facts.encode().map_or(0, |line| line.len() + 1);
records += 1;
builder.add_facts(facts);
}
let elapsed = start.elapsed();
println!("corpus: {records} records, {bytes} store bytes, {:?} to read them all", elapsed);
// What the store is *made of*, so a byte delta can be attributed rather
// than guessed at: every unit and every member carries one type-name field.
let counts = builder.finish().counts();
println!("corpus: {counts:?}");
}
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);
}
}
}