diff --git a/TODO.md b/TODO.md index ca75585..16d096c 100644 --- a/TODO.md +++ b/TODO.md @@ -1904,3 +1904,169 @@ class-member-access}/README.md, TODO.md §16. 32 208 241 bytes); cold scan 3 976 files unchanged at ~3.0s; diagnostics 0→0 on 5 DV files with interfaces. Full table in `docs/features/interface-semantics/README.md`'s QA log. + +## 17. Struct members wave (2026-09-01) — coverage_gaps H1 + topo §2.9-13 + +`typedef struct packed {…} bus_t; bus_t s; s.field` records nothing. +Mapped state: `SymbolKind::StructMember`/`ScopeKind::Struct` exist and +the struct scope already hangs on the Typedef symbol's `child_scope`; +every member declarator has a name span and its own `DataType`; the +`MemberOf` pending use exists. Missing: `resolve.rs::member_scope` +excludes `Typedef` (the whole in-file gap); members are declared with +`declare`, not `declare_typed` (no `type_name`, so no nested hop); +`is_exported` has no `Typedef` arm (no cross-file `Def`s); anonymous +aggregates (`struct {…} s;`, `enum {A,B} x;`, inline nested struct +members — the opentitan register-package shape) produce no symbols +because `ty.name` is empty. Single lane. Files: crates/vlog_semantic/ +src/{bind.rs, resolve.rs, workspace.rs, facts.rs, model.rs if a field +is needed}, crates/vlog_semantic/tests/* (+ new struct_members.rs), +crates/lucisv_server/src/type_def.rs (member-type descent, small), +crates/lucisv_server/tests/e2e.rs, docs/features/struct-members/ +README.md (new), amendments in docs/features/{types-decls, +vlog-semantic, class-member-access}/README.md, TODO.md §17. + +- [x] **In-file**: `member_scope` accepts a `Typedef` whose child scope + is a `Struct` scope (unions included — one node); struct members + declared with `declare_typed` so `s.hdr.addr` hops through a + member's own type; an alias of a struct typedef follows to it; + enum/int-alias typedef heads still record nothing (`.name()` + etc. are built-ins); the in-file struct answers in-file — never + a stranger class of the same name elsewhere (round-1 pin stays). +- [x] **Cross-file**: `is_exported(Typedef, StructMember)`; members of + a struct typedef nested in a package land under the typedef's + bare name like nested classes do (collisions across packages → + the existing ambiguity refusal, documented); `Def::type_name` on + members; `pkg::bus_t s; s.field` from another file. +- [x] **Anonymous forms (§2.9-13)**: `enum {A,B} x;` declares its + variants in the enclosing scope exactly like a typedef enum; an + anonymous `struct {…} s;` gives the declarator a `Struct` child + scope with its members, and `link_type` follows a head symbol's + own child scope when it has no type name; an INLINE nested struct + member (`struct packed { struct packed {…} q; } reg2hw_t;`) gets + a child scope in-file and, cross-file, its inner members exported + under a synthesized key `reg2hw_t::q` carried as the member's + `Def::type_name` — so `reg2hw.ctrl.q` walks + `reg2hw_t` → `ctrl` → `reg2hw_t::ctrl` → `q` without bare-name + collisions (`q`/`d`/`qe` are everywhere in register packages). + Cross-file anonymous *variables* (`pkg::cfg.f`) stay in-file only, + documented. + **Done 2026-09-01, one deviation**: the synthesized key joins with + a **`.`**, not `::` — `member_type` calls `last_segment` on a + `Def::type_name` before using it, so `reg2hw_t::ctrl` would have + collapsed back to the bare `ctrl` the key exists to avoid. A `.` + survives it whole and is unwritable as a type name. Argued in + `docs/features/struct-members/README.md`. +- [x] **`FACTS_FORMAT` 8 → 9**. +- [x] **type_def.rs**: `typeDefinition` on a struct member's type name + inside the body (descend into `TypedefKind::Struct` members). +- [x] **Pins to flip/keep**: `a_struct_typedef_typed_head_records_nothing` + → resolves; `an_alias_of_a_struct_records_nothing` → follows; + `a_chain_broken_by_a_struct_link_records_nothing_past_the_break` + → continues; `a_local_typedef_is_never_looked_up_in_a_same_named_class_elsewhere` + stays (answers the struct's own field); enum/int-alias pins stay; + rename of a struct member rewrites `s.field` uses in-file and + cross-file (the existing declaration-only rename pin grows uses); + corpus: unresolved must fall or hold, store delta reported. + **Done 2026-09-01**: the cross-file half of + `a_chain_broken_by_a_struct_link_...` stays a *refusal* (two `hdr_t` + in the workspace — deviation argued in the feature README); every + other pin landed as briefed. `vlog_refactor`'s existing + declaration-only rename pin keeps passing untouched; the new + cross-file use rename is pinned in this lane's own e2e. Corpus: + unresolved **1 203 → 1 162**, unplaced 0, store **3 216 689 → + 3 179 905 bytes (−1.14 %)** while indexed members grew 12 298 → + 12 642 — the anonymous-enum variants turn external postings into + local ones. `cargo test --workspace`: **2 810 passed, 0 failed, 38 + ignored**; fmt clean, clippy zero warnings, smoke OK. +- [x] **QA on opentitan** (read-only): `reg2hw..q` / + `hw2reg..d` / `.de` in hw/ip/*/rtl/*.sv against the + generated `*_reg_pkg.sv` (cross-file, nested inline structs); + `tl_i.a_address`-style struct-typed ports; DV struct members; + sub-ms hover; store delta (register structs are large); zero + wrong answers. + **Done 2026-09-01, verdict SHIP**: 28 probes across 6 IPs (uart, + spi_device, aes, i2c, usbdev, tlul) plus one DV file — 23 resolved + correctly (three planted sibling-name acid-test pairs hand-verified + against `*_reg_pkg.sv`: i2c `rxfull`:546/`fmtfull`:549, usbdev + `avsetup_rst`:417/`avout_rst`:420, spi_device + `tpm_csb`:481/`csb`:484 — never the wrong sibling), 5 misses all the + same pre-existing documented indexed-mid-chain limitation + (`reg2hw.key_share0[i].q`, unrelated to struct-members — confirmed + by three other AES chains through the same wildcard-imported type + answering correctly with no index). Zero wrong answers. Hover/def + 0.00–0.52 ms (first request pays warm-up, rest sub-ms). Cold scan + 3 976 files: trunk `95f930c` 3 543.79 ms → this tree 3 925.48 ms. + Opentitan on-disk index-cache: 32 208 241 → **33 583 533 bytes + (+4.27 %)** — the predicted-direction gain from real + `*_reg_pkg.sv` files, opposite of the synthetic corpus's −1.14 %. + Diagnostics 0→0 on all 7 opened files. `git -C opentitan status` + unchanged. Full table in `docs/features/struct-members/README.md`'s + QA log. +- Follow-on lane (filed): **member completion after `.`** — no dot + context exists in completion.rs today; with member resolution in + place, `item.` / `reg2hw.` / `vif.` listing members is the natural + next DV/RTL daily driver. + +## 18. Member completion wave (2026-09-01) — the DV/RTL daily driver + +`item.` / `reg2hw.ctrl.` / `vif.` / `vif.cb.` / `pkg::` / `this.` / +`super.` list members. Mapped state: `typed_word` already yields an +empty word with an empty replace range right after `.`/`::`, so today +the cursor after a dot gets the whole-index dump (scope + index + 181 +keywords + every project word, capped at 512, `isIncomplete`) — that +is what this lane replaces; no dot/scope context exists anywhere in +completion.rs; `trigger_characters: None` (main.rs:284, two pins); +`WorkspaceIndex::members_of(unit)` is `pub`, documented for `pkg::` +and uncalled, but omits inherited members; every chain-resolving +helper (`resolve::member_of` prefix, `link_type`, `type_here`, +`member_chain`, `member_type`, `aliased_unit`) is private. Single +lane. Files: crates/vlog_semantic/src/{lib.rs, resolve.rs, +workspace.rs} (public API only — one walk, no second resolver), +crates/vlog_semantic/tests/*, crates/lucisv_server/src/{completion.rs, +main.rs} (+ server.rs only if context plumbing is needed), +crates/lucisv_server/tests/e2e.rs, editors/vscode/smoke.js (optional +pin), docs/features/member-completion/README.md (new), amendment in +docs/features/completion-core/README.md (the "every other tier ignores +position" sentence; the stale five-row tier table), TODO.md §18. + +- [ ] **Public prefix walk in `vlog_semantic`**: `Semantics::member_site + (from, head, mids) -> Option` — the prefix of `resolve::member_of`, which is + refactored to call it (one walk); `WorkspaceIndex::members_of_chain + (unit) -> members incl. inherited/aliased`, walking the same + `member_chain` hops nearest-first with subclass-overrides-base + dedup, and `WorkspaceIndex::member_unit(unit, member)` (= + `member_type`) to fold mids cross-file; an in-file class whose + `extends` leaves the file merges its scope members with the + chain's cross-file members. +- [ ] **`Word` learns its separator**: `.` or `::` immediately before + the run, plus the head spine (`a.b.c` identifiers, balanced + `[…]` index suffixes stripped so `q[i].` works; anything else → + no head). `this.`/`super.` map to the class scope / its base + chain. +- [ ] **Exclusive member tier**: with a separator, the answer is the + members of the site and nothing else (kind from + `completion_kind`, detail = kind label + declared type, table-only + — no file reads), prefix-filtered below 3 typed chars and fuzzy + from 3 (the house rule), `isIncomplete` only when the list is + truncated; an unresolvable head answers **nothing** (no popup) + instead of the 512-item dump. `pkg::` lists the package's + members; `cls::` its static-visible members. +- [ ] **Triggers**: `trigger_characters: [".", ":"]` (the two main.rs + pins updated); the handler decides from the buffer, not the + trigger context; a lone `:` (label/ternary) falls through to + ordinary completion unchanged. +- [ ] **Pins**: class in-file and cross-file with inherited members + from a base in another file; struct fields incl. nested via + synthesized key (`reg2hw.ctrl.`); interface signals + modports + + clocking (`vif.`, `vif.cb.`); `pkg::`; `this.`/`super.`; typed + prefix after the dot filters; the edit range is empty at the + cursor; unresolvable head → None; absent base stops the chain + but the known members still list; e2e over the wire with the + trigger character; the two-to-three-char rule after a dot. +- [ ] **QA on opentitan** (read-only): `item.`, `cfg.`, `reg2hw.`, + `reg2hw..`, `vif.`, `vif.cb.`, `tlul_pkg::`, `this.` in + real DV/RTL buffers — member lists complete (cross-check a + sample against the declaring file), inherited members present + for known bases, sub-ms answered-in, no whole-index dump after a + dot anywhere; zero wrong members. diff --git a/crates/lucisv_server/src/type_def.rs b/crates/lucisv_server/src/type_def.rs index 9ead36b..aef8ac7 100644 --- a/crates/lucisv_server/src/type_def.rs +++ b/crates/lucisv_server/src/type_def.rs @@ -41,7 +41,8 @@ use lsp_types::{Location, Uri}; use vlog_parser::ast::{ AnsiPort, DataType, Declarator, GenBlock, GenElse, GenIf, Instantiation, Item, ItemKind, - Module, ParamPort, PortList, Stmt, StmtKind, TfArg, Typedef, TypedefKind, + Module, ParamPort, PortList, Stmt, StmtKind, StructType, TfArg, TypeExtra, Typedef, + TypedefKind, }; use vlog_parser::TextRange; use vlog_semantic::{Semantics, SymbolKind}; @@ -171,7 +172,7 @@ fn item_site(item: &Item, offset: u32) -> Option> { ItemKind::DataDecl(d) => declarator_site(&d.ty, item.span, &d.declarators), ItemKind::PortDecl(p) => declarator_site(&p.ty, item.span, &p.declarators), ItemKind::ParamDecl(p) => declarator_site(&p.ty, item.span, &p.declarators), - ItemKind::Typedef(t) => alias_site(t, item.span), + ItemKind::Typedef(t) => alias_site(t, item.span, offset), ItemKind::Instantiation(i) => instance_site(i, item.span), ItemKind::Module(m) => module_site(m, offset), ItemKind::Class(c) => param_port_site(c.param_ports.as_deref().unwrap_or(&[]), offset) @@ -203,16 +204,36 @@ fn declarator_site<'a>( site(&ty.name, TextRange::new(span.start, first)) } -/// `typedef state_t alias_t;` — the alias's own type. The other typedef -/// spellings declare their type inline (`enum`, `struct`) or promise one -/// elsewhere (`typedef class c;`), and so name nothing to jump to. -fn alias_site(t: &Typedef, span: TextRange) -> Option> { +/// `typedef state_t alias_t;` — the alias's own type; and, since +/// struct-members (2026-09-01), a `typedef struct { hdr_t hdr; … }` body, +/// whose **fields** are declarations with types of their own and so have +/// somewhere to jump to. An `enum` body declares its type inline and a +/// `typedef class c;` promises one elsewhere, so both still name nothing. +fn alias_site(t: &Typedef, span: TextRange, offset: u32) -> Option> { match &t.kind { TypedefKind::Alias(ty) => site(&ty.name, TextRange::new(span.start, t.name_span.start)), + TypedefKind::Struct(s) => struct_member_site(s, offset), _ => None, } } +/// The field of a `struct`/`union` body the cursor is in, as a type site. +/// +/// Inline nested bodies are descended first, so the innermost field wins — the +/// generated-register-package shape (`struct packed { struct packed { logic q; +/// } ctrl; }`) is nested arbitrarily deep. A field whose type *is* an inline +/// aggregate has no name to jump to, and falls out through [`site`]'s own +/// empty-name refusal rather than through a check here. +fn struct_member_site(s: &StructType, offset: u32) -> Option> { + let member = s.members.iter().find(|m| m.span.contains(offset))?; + if let Some(TypeExtra::Struct(nested)) = member.ty.inline() { + if let Some(inner) = struct_member_site(nested, offset) { + return Some(inner); + } + } + declarator_site(&member.ty, member.span, &member.declarators) +} + /// `sub u_sub (...)`, and every interface instance written the same way. The /// instance name's type is the module it instantiates. fn instance_site(i: &Instantiation, span: TextRange) -> Option> { @@ -289,7 +310,7 @@ fn stmt_site(stmt: &Stmt, offset: u32) -> Option> { // cursor on the alias name jumps one hop to the aliased type. Added // when `StmtKind::Typedef` landed (testbench-mopup, 2026-08-29) — // QA's blast-radius audit caught this arm missing. - StmtKind::Typedef(t) => alias_site(t, stmt.span), + StmtKind::Typedef(t) => alias_site(t, stmt.span, offset), StmtKind::VarDecl(d) => declarator_site(&d.ty, stmt.span, &d.declarators), StmtKind::ParamDecl(p) => declarator_site(&p.ty, stmt.span, &p.declarators), StmtKind::PortDecl(p) => declarator_site(&p.ty, stmt.span, &p.declarators), diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index a22510f..6e6342e 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -6390,3 +6390,179 @@ endclass let _ = std::fs::remove_dir_all(&dir); } + +// ---------------------------------------------------------------------- +// struct-members (TODO.md §17) +// ---------------------------------------------------------------------- + +/// The generated-register-package shape, which is what the whole round is +/// for: `reg2hw.ctrl.tx.q` in one file, typed by a `typedef struct packed` +/// four links away in another — with the two inner links written as **inline** +/// aggregates that have no type name at all. Hover names the declaring file +/// and line, and F12 lands on it. +#[test] +fn a_register_packages_nested_struct_field_is_hovered_and_navigated_across_files() { + let dir = temp_dir("structreg"); + let pkg = dir.join("uart_reg_pkg.sv"); + let pkg_text = "\ +package uart_reg_pkg; + typedef struct packed { + struct packed { + logic q; + } tx; + } uart_reg2hw_ctrl_reg_t; + + typedef struct packed { + uart_reg2hw_ctrl_reg_t ctrl; + } uart_reg2hw_t; +endpackage +"; + std::fs::write(&pkg, pkg_text).expect("write"); + let core = dir.join("uart_core.sv"); + let text = "\ +module uart_core ( + input uart_reg_pkg::uart_reg2hw_t reg2hw +); + assign tx_enable = reg2hw.ctrl.tx.q; +endmodule +"; + std::fs::write(&core, text).expect("write"); + + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", core.display()); + + // Line 3 is ` assign tx_enable = reg2hw.ctrl.tx.q;`: `ctrl` at column 28, + // `tx` at 33, the tail `q` at 36. + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(WIDE_SCOPE), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(text).expect("json") + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":3,"character":36}}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":3,"character":36}}}}}}"# + )), + // The middle links answer too, each in the struct that declares it. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":3,"character":33}}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":3,"character":28}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + let response = |id: u32| -> &serde_json::Value { + messages + .iter() + .find(|m| m["id"] == id) + .unwrap_or_else(|| panic!("no response {id} in {messages:#?}")) + }; + + let hover = response(2)["result"]["contents"]["value"].as_str().expect("hover markdown"); + assert!(hover.contains("uart_reg_pkg.sv:4"), "the field's own file and line: got {hover}"); + assert!(hover.contains("logic q"), "the declaration's own line: got {hover}"); + assert!(hover.contains("**struct member**"), "labelled as what it is: got {hover}"); + + let definition = &response(3)["result"]; + let target = definition.get("uri").map_or(&definition[0], |_| definition); + assert!( + target["uri"].as_str().expect("a uri").ends_with("uart_reg_pkg.sv"), + "the jump follows the hover: {definition:#?}" + ); + assert_eq!(target["range"]["start"]["line"], 3, "{definition:#?}"); + + let tx = response(4)["result"]["contents"]["value"].as_str().expect("hover markdown"); + assert!(tx.contains("uart_reg_pkg.sv:5"), "the inline aggregate member: got {tx}"); + let ctrl = response(5)["result"]["contents"]["value"].as_str().expect("hover markdown"); + assert!(ctrl.contains("uart_reg_pkg.sv:9"), "the named-type member: got {ctrl}"); + + let _ = std::fs::remove_dir_all(&dir); +} + +/// Renaming a struct field from its own declaration rewrites the `s.field` +/// uses in other files — the edit set that used to hold only the declaration, +/// because nothing recorded the use. +#[test] +fn a_struct_field_is_renamed_with_its_uses_in_another_file() { + let dir = temp_dir("structrename"); + let bus = dir.join("bus_pkg.sv"); + let bus_text = "\ +package bus_pkg; + typedef struct packed { + logic [7:0] addr; + } bus_t; +endpackage +"; + std::fs::write(&bus, bus_text).expect("write"); + let top = dir.join("top.sv"); + let text = "\ +module top; + bus_pkg::bus_t s; + assign w = s.addr; +endmodule +"; + std::fs::write(&top, text).expect("write"); + + let root = format!("file://{}", dir.display()); + let bus_uri = format!("file://{}", bus.display()); + let top_uri = format!("file://{}", top.display()); + + // `addr` is declared at line 2 column 16 of the package, and used at line + // 2 column 15 of `top.sv`. + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(WIDE_SCOPE), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{bus_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(bus_text).expect("json") + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/references","params":{{"textDocument":{{"uri":"{bus_uri}"}},"position":{{"line":2,"character":16}},"context":{{"includeDeclaration":false}}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/rename","params":{{"textDocument":{{"uri":"{bus_uri}"}},"position":{{"line":2,"character":16}},"newName":"address"}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + let response = |id: u32| -> &serde_json::Value { + messages + .iter() + .find(|m| m["id"] == id) + .unwrap_or_else(|| panic!("no response {id} in {messages:#?}")) + }; + + let references = response(2)["result"].as_array().expect("a list"); + assert_eq!(references.len(), 1, "the cross-file use: {references:#?}"); + assert!(references[0]["uri"].as_str().expect("a uri").ends_with("top.sv")); + assert_eq!(references[0]["range"]["start"]["line"], 2); + + let changes = &response(3)["result"]["changes"]; + let own = changes[&bus_uri].as_array().expect("edits for the package"); + assert_eq!(own.len(), 1, "{own:#?}"); + assert_eq!(own[0]["range"]["start"]["line"], 2); + let elsewhere = changes[&top_uri].as_array().expect("edits for the using file"); + assert_eq!(elsewhere.len(), 1, "{elsewhere:#?}"); + assert_eq!(elsewhere[0]["range"]["start"]["line"], 2); + assert_eq!(elsewhere[0]["range"]["start"]["character"], 15); + assert!(elsewhere.iter().all(|e| e["newText"] == "address"), "{elsewhere:#?}"); + + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/vlog_semantic/src/bind.rs b/crates/vlog_semantic/src/bind.rs index ef594d0..525548e 100644 --- a/crates/vlog_semantic/src/bind.rs +++ b/crates/vlog_semantic/src/bind.rs @@ -527,14 +527,7 @@ impl<'a> Binder<'a> { } TypedefKind::Enum(e) => { self.declare(scope, &t.name, SymbolKind::Typedef, ns, span); - if let Some(base) = &e.base { - self.bind_data_type(base, TextRange::new(span.start, ns.start), scope); - } - // LRM: enum names belong to the scope holding the enum. - for m in &e.members { - self.declare(scope, &m.name, SymbolKind::EnumVariant, m.name_span, m.span); - self.bind_opt_expr(m.value.as_ref(), scope); - } + self.bind_enum_body(e, TextRange::new(span.start, ns.start), scope); } TypedefKind::Struct(s) => { let inner = self.declare_with_scope( @@ -545,15 +538,8 @@ impl<'a> Binder<'a> { span, ScopeKind::Struct, ); - for m in &s.members { - let first = m.declarators.first().map(|d| d.span.start).unwrap_or(m.span.end); - self.bind_data_type(&m.ty, TextRange::new(m.span.start, first), scope); - for d in &m.declarators { - self.declare(inner, &d.name, SymbolKind::StructMember, d.name_span, d.span); - self.bind_dims(&d.unpacked, scope); - self.bind_opt_expr(d.init.as_ref(), scope); - } - } + self.bind_struct_uses(s, scope); + self.bind_struct_members(s, inner); } // `typedef class c;` promises a class declared elsewhere; the // name is declared here so a reference to it resolves to the @@ -565,6 +551,78 @@ impl<'a> Binder<'a> { self.bind_dims(&t.unpacked, scope); } + /// An `enum` body: its base type, and its member names — which IEEE 1800 + /// §6.19 binds in the scope **holding** the enum, not in the enum itself, + /// which is why `IDLE` is written bare. One function for all three + /// spellings that can write one: `typedef enum {…} e_t;`, an anonymous + /// `enum {…} x;`, and an anonymous enum standing as a struct member's type. + fn bind_enum_body(&mut self, e: &EnumType, window: TextRange, scope: ScopeId) { + if let Some(base) = &e.base { + self.bind_data_type(base, window, scope); + } + for m in &e.members { + self.declare(scope, &m.name, SymbolKind::EnumVariant, m.name_span, m.span); + self.bind_opt_expr(m.value.as_ref(), scope); + } + } + + /// Every *use* written inside a `struct`/`union` body — each member's type + /// name, its dimensions, its initializer — recorded in the scope the body + /// is written in, because that is where those names are looked up from. + /// + /// Split from [`Binder::bind_struct_members`], which declares the members + /// themselves, so that a body written once and declared under several + /// declarators (`struct { hdr_t h; } a, b;`) records its type names once + /// rather than once per declarator. + fn bind_struct_uses(&mut self, s: &StructType, scope: ScopeId) { + for m in &s.members { + let first = m.declarators.first().map(|d| d.span.start).unwrap_or(m.span.end); + self.bind_data_type(&m.ty, TextRange::new(m.span.start, first), scope); + for d in &m.declarators { + self.bind_dims(&d.unpacked, scope); + self.bind_opt_expr(d.init.as_ref(), scope); + } + } + } + + /// The members of one `struct`/`union` body, declared in `inner` — the + /// scope hanging off whatever names the aggregate (a `typedef`, a plain + /// declarator, or an enclosing member). + /// + /// Each member carries its own declared type, so `s.hdr.addr` hops through + /// it exactly as a class property does. A member whose type is an **inline + /// nested** aggregate (`struct packed { struct packed { logic q; } ctrl; }` + /// — the shape every generated register package is made of) has no type + /// name to hop through at all, so it gets a `Struct` scope of its own and + /// `resolve.rs` reaches its members through that instead. + fn bind_struct_members(&mut self, s: &StructType, inner: ScopeId) { + for m in &s.members { + for d in &m.declarators { + // The unpacked-declarator rule, as everywhere: `logic [7:0] + // arr [4]` names a container, not a value of the type. + let plain = d.unpacked.is_empty(); + let id = self.declare_typed( + inner, + &d.name, + SymbolKind::StructMember, + d.name_span, + d.span, + plain.then_some(&m.ty), + ); + let (Some(id), Some(TypeExtra::Struct(nested))) = (id, m.ty.inline()) else { + continue; + }; + if !plain { + continue; + } + let child = self.new_scope(ScopeKind::Struct, inner, d.span); + self.symbols[id.0 as usize].child_scope = Some(child); + self.scopes[child.0 as usize].owner = Some(id); + self.bind_struct_members(nested, child); + } + } + } + fn bind_data_decl(&mut self, d: &DataDecl, span: TextRange, scope: ScopeId) { let kind = if d.net.is_some() { SymbolKind::Net } else { SymbolKind::Var }; self.bind_opt_expr(d.delay.as_ref(), scope); @@ -624,14 +682,19 @@ impl<'a> Binder<'a> { let first = declarators.first().map(|d| d.span.start).unwrap_or(span.end); self.bind_data_type(ty, TextRange::new(span.start, first), scope); for d in declarators { - self.declare_typed( - scope, - &d.name, - kind, - d.name_span, - d.span, - d.unpacked.is_empty().then_some(ty), - ); + let plain = d.unpacked.is_empty(); + let id = + self.declare_typed(scope, &d.name, kind, d.name_span, d.span, plain.then_some(ty)); + // An **anonymous** aggregate (`struct packed { logic a; } s;`) has + // no type name for `s.a` to be looked up through, so the members + // hang off the declarator itself. In-file only: no other file can + // name this variable's type, because it has none. + if let (Some(id), Some(TypeExtra::Struct(s)), true) = (id, ty.inline(), plain) { + let child = self.new_scope(ScopeKind::Struct, scope, d.span); + self.symbols[id.0 as usize].child_scope = Some(child); + self.scopes[child.0 as usize].owner = Some(id); + self.bind_struct_members(s, child); + } self.bind_dims(&d.unpacked, scope); self.bind_opt_expr(d.init.as_ref(), scope); } @@ -1530,6 +1593,16 @@ impl<'a> Binder<'a> { } } self.bind_dims(&ty.packed, scope); + // An anonymous aggregate written where a type name would go. Its + // *names* are declared by whoever owns the declarator (an enum's + // variants below, a struct's members in `bind_struct_members`); what + // is written here is every use inside it, recorded once for the type + // however many declarators share it. + match ty.inline() { + Some(TypeExtra::Enum(e)) => self.bind_enum_body(e, window, scope), + Some(TypeExtra::Struct(s)) => self.bind_struct_uses(s, scope), + _ => {} + } } /// The byte range of the `mp` in a glued `bus_if.mp` type name, given the diff --git a/crates/vlog_semantic/src/facts.rs b/crates/vlog_semantic/src/facts.rs index 4f1c9ae..435b3f0 100644 --- a/crates/vlog_semantic/src/facts.rs +++ b/crates/vlog_semantic/src/facts.rs @@ -50,7 +50,16 @@ use crate::workspace::{ /// a modport and a named clocking block are declarations, and every name /// written inside either is a reference, so a store written by an older build /// holds a strictly smaller `M` and `R` group for the same file. -pub const FACTS_FORMAT: u32 = 8; +/// +/// 8 → 9 (2026-09-01, struct-members): the census again, in both groups. A +/// `struct`/`union` typedef now exports its fields — and an inline nested +/// field its own fields, under a synthesized `owner.field` key — so the `M` +/// group of a register package grows from nothing to hundreds of entries; a +/// member carries the declared type it is hopped through; and `s.field` is a +/// reference where it used to be silence, so the `R` group grows too. A store +/// written by an older build would answer `reg2hw.ctrl.q` for the files it +/// cached and not for the files it did not. +pub const FACTS_FORMAT: u32 = 9; impl FileFacts { /// These facts as one line's worth of fields, tab-separated. diff --git a/crates/vlog_semantic/src/resolve.rs b/crates/vlog_semantic/src/resolve.rs index 5325b91..f36be82 100644 --- a/crates/vlog_semantic/src/resolve.rs +++ b/crates/vlog_semantic/src/resolve.rs @@ -187,7 +187,7 @@ enum Link { fn link_type(scopes: &[Scope], symbols: &[Symbol], id: SymbolId) -> Option { let symbol = symbols.get(id.0 as usize)?; let Some(type_name) = symbol.type_name.as_deref() else { - return member_scope(symbols, id).map(Link::Scope); + return member_scope(scopes, symbols, id).map(Link::Scope); }; // The type name is looked up where the declaration is written, by the same // walk the type *reference* itself took. @@ -316,7 +316,7 @@ fn type_here_seen( None => return TypeHere::NotAUnit, } } - if let Some(scope) = member_scope(symbols, current) { + if let Some(scope) = member_scope(scopes, symbols, current) { return TypeHere::Scope(scope); } match alias_target(symbols, current) { @@ -351,12 +351,22 @@ fn container_scope(symbols: &[Symbol], id: SymbolId) -> Option { /// The scope a symbol opens when a `.` may name its members: a class, a /// module, or an interface — which is what makes `vif.sig` and `u.internal` -/// reach into one. A package is a container to pass through, never a thing a -/// handle can be. -fn member_scope(symbols: &[Symbol], id: SymbolId) -> Option { +/// reach into one — **or** a `struct`/`union` body, whoever names it. A +/// package is a container to pass through, never a thing a handle can be. +/// +/// The struct half is deliberately written as "any symbol whose child scope is +/// a struct body", not "a `Typedef` whose child scope is one": the same rule +/// then serves all three ways a body gets named — the `typedef` that names it, +/// an **anonymous** aggregate's own declarator (`struct { logic a; } s;`), and +/// an **inline nested** member (`struct { struct { logic q; } ctrl; }`), where +/// no type name exists to look anything up by. `docs/features/struct-members/README.md`. +fn member_scope(scopes: &[Scope], symbols: &[Symbol], id: SymbolId) -> Option { let symbol = symbols.get(id.0 as usize)?; - (symbol.kind == SymbolKind::Class || symbol.kind.is_instantiable()) - .then_some(symbol.child_scope)? + if symbol.kind == SymbolKind::Class || symbol.kind.is_instantiable() { + return symbol.child_scope; + } + let child = symbol.child_scope?; + (scopes.get(child.0 as usize)?.kind == crate::model::ScopeKind::Struct).then_some(child) } /// The last `::` segment of a possibly-qualified path (`pkg::cls` → `cls`) — diff --git a/crates/vlog_semantic/src/workspace.rs b/crates/vlog_semantic/src/workspace.rs index 17425ed..0b0531e 100644 --- a/crates/vlog_semantic/src/workspace.rs +++ b/crates/vlog_semantic/src/workspace.rs @@ -1151,7 +1151,7 @@ fn facts_from_analysis( continue; } facts.units.push(Decl::unit(unit, src, lines)); - collect_members(sem, unit, lines, &mut facts.members); + collect_members(sem, &unit.name, unit, lines, &mut facts.members); } let exported: HashSet<(u32, u32)> = facts .units @@ -1250,9 +1250,16 @@ fn inheritance_of(tree: &SourceFile) -> Vec<(String, DeclSite)> { .collect() } -/// Read off the names another file may reach *into* this unit for. +/// Read off the names another file may reach *into* this unit for, under +/// `key` — the spelling `follow_one` looks the member table up by. +/// +/// `key` is the owner's bare name almost everywhere, which is why a class or a +/// struct `typedef` nested in a package is reachable as `cls::x` / `bus_t::f` +/// without the package in the path. The exception is an **inline nested** +/// struct member, which has no type name at all: see [`nested_key`]. fn collect_members( sem: &Semantics, + key: &str, unit: &Symbol, lines: &LineIndex, out: &mut Vec<(String, Decl)>, @@ -1267,17 +1274,48 @@ fn collect_members( if !is_exported(unit.kind, member.kind) || member.name_span.is_empty() { continue; } - out.push((unit.name.clone(), Decl::member(member, lines))); + let mut decl = Decl::member(member, lines); + let nested = nested_key(key, member); + if let Some(nested) = &nested { + decl.type_name = Some(nested.clone()); + } + out.push((key.to_string(), decl)); // A class nested in a package (the dominant UVM shape) is not a unit, // but an external `cls::x` candidate looks its members up under the - // *class's* name — register them there too. The scope tree is acyclic, + // *class's* name — register them there too. A struct `typedef` nested + // in a package is the same shape, and an inline aggregate member is + // the same shape under its synthesized key. The scope tree is acyclic, // so this recursion terminates. - if member.kind == SymbolKind::Class { - collect_members(sem, member, lines, out); + if matches!(member.kind, SymbolKind::Class | SymbolKind::Typedef) { + collect_members(sem, &member.name, member, lines, out); + } else if let Some(nested) = nested { + collect_members(sem, &nested, member, lines, out); } } } +/// The member-table key an **inline nested** struct member's own fields are +/// registered under, and the `type_name` the member's [`Def`] carries so that +/// [`member_type`]'s next hop finds them. +/// +/// `struct packed { struct packed { logic q; } ctrl; } reg2hw_t;` has no name +/// for the type of `ctrl`, so the index makes one: the container's key and the +/// member's name, joined by a **`.`**. Two properties earn the spelling. It is +/// unwritable as a type name — [`crate::Symbol::type_name`] strips the one +/// dotted spelling SystemVerilog has (`bus_if.mp`) down to the interface half +/// — so a synthesized key can never collide with a real unit or a real +/// typedef, however many register packages a workspace holds. And it survives +/// [`last_segment`] whole, so the existing hop needs no special case: the bare +/// alternative (`q`, `d`, `qe` — the field names every generated register +/// package repeats) would collide across every file in the tree. +/// +/// `None` for every member that is not one: only a `StructMember` that opens a +/// scope of its own is an inline aggregate. +fn nested_key(key: &str, member: &Symbol) -> Option { + (member.kind == SymbolKind::StructMember && member.child_scope.is_some()) + .then(|| format!("{key}.{}", member.name)) +} + /// The file list an index will be built from, in the order it is built in: /// sorted by path, one entry per path (a path handed over twice is one file, /// and the first copy wins). @@ -1448,6 +1486,14 @@ fn is_exported(unit: SymbolKind, member: SymbolKind) -> bool { | SymbolKind::Class ), SymbolKind::Module => matches!(member, SymbolKind::Port | SymbolKind::Param), + // A `typedef struct`/`union` exports its fields, and a field that is + // itself an inline aggregate exports its own — which is what a + // generated register package is: `reg2hw_t` → `ctrl` → `q`. Nothing + // else lives in a struct body, so this arm is exhaustive by + // construction rather than by policy. + SymbolKind::Typedef | SymbolKind::StructMember => { + matches!(member, SymbolKind::StructMember) + } SymbolKind::Interface => matches!( member, SymbolKind::Net diff --git a/crates/vlog_semantic/tests/member_access.rs b/crates/vlog_semantic/tests/member_access.rs index 57a28fe..0cedfd7 100644 --- a/crates/vlog_semantic/tests/member_access.rs +++ b/crates/vlog_semantic/tests/member_access.rs @@ -300,12 +300,19 @@ endmodule // 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: this file has said what the type -/// is, and it is not something with members this crate models. +/// 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_records_nothing() { +fn a_struct_typedef_typed_head_resolves_its_own_field() { let src = "\ typedef struct packed { bit field; } s_t; @@ -315,7 +322,22 @@ module m; endmodule "; let s = sem(src); - assert!(s.reference_at(tail(src, "s.field", 0)).is_none()); + 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 @@ -359,8 +381,16 @@ endmodule 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. - assert_eq!(ws.member("bus_t", "field").len(), 1); + // 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 @@ -436,10 +466,11 @@ endmodule assert!(s.reference_at(tail(src, "h.anything", 0)).is_none()); } -/// An alias of something with no members answers nothing, exactly as the -/// unaliased spelling does — the round-1 rule, one hop further away. +/// 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_records_nothing() { +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; @@ -450,7 +481,10 @@ module m; endmodule "; let s = sem(src); - assert!(s.reference_at(tail(src, "s.field", 0)).is_none()); + 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 @@ -779,33 +813,50 @@ fn a_chain_resolves_across_three_files() { } } -/// A link whose type has no members this crate models stops the chain: the -/// mid is still answered, and nothing at all is recorded past it — in this -/// file or through the workspace. +/// 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_broken_by_a_struct_link_records_nothing_past_the_break() { +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 the break resolves" + "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" ); - assert!(s.reference_at(tail(&src, "item.hdr.addr", 0)).is_none()); // Across files, where a class named `hdr_t` also exists somewhere else: - // the composed path must not reach it either. + // 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 diff --git a/crates/vlog_semantic/tests/struct_members.rs b/crates/vlog_semantic/tests/struct_members.rs new file mode 100644 index 0000000..b6ff844 --- /dev/null +++ b/crates/vlog_semantic/tests/struct_members.rs @@ -0,0 +1,588 @@ +//! `s.field` through a `struct`/`union`-typed value: the in-file lookup, the +//! cross-file member table, and the three anonymous forms that had no symbols +//! at all before this round. The rules live in +//! `docs/features/struct-members/README.md`. +//! +//! The governing rule, inherited from class-member-access and load-bearing for +//! every "records nothing" assertion below: **a link that cannot be resolved +//! honestly records nothing, and nothing after it — a wrong answer is the only +//! forbidden outcome.** + +use std::path::PathBuf; +use vlog_parser::parse_source; +use vlog_semantic::{ + analyze, resolve_external, Def, ExternalTarget, FileFacts, Resolution, Semantics, SymbolId, + SymbolKind, WorkspaceIndex, +}; + +// ---------------------------------------------------------------------- +// helpers — the same shapes `member_access.rs` uses, so the two files read +// alike and a reader moving between them is never guessing. +// ---------------------------------------------------------------------- + +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 **last** `.`-separated name of the `n`th occurrence of +/// `needle` — the tail of a member access, 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 +} + +/// The offset of the link `k` dots into the `n`th occurrence of `needle` +/// (`link(src, "a.b.c", 0, 1)` is `b`). +fn link(src: &str, needle: &str, n: usize, k: usize) -> u32 { + let at = nth(src, needle, n); + let dot = needle.match_indices('.').nth(k - 1).expect("that many dots").0; + at + dot 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) -> SymbolId { + let (i, _) = s + .symbols() + .iter() + .enumerate() + .find(|(_, sym)| sym.name == name) + .unwrap_or_else(|| panic!("no symbol {name}")); + 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 { + let s = sem(src); + let id = s.reference_id_at(offset)?; + resolve_external(&s, ws).get(id).and_then(ExternalTarget::best).cloned() +} + +/// Every workspace answer for the use at `offset`, ambiguity included. +fn overlay_target(ws: &WorkspaceIndex, src: &str, offset: u32) -> Option { + let s = sem(src); + let id = s.reference_id_at(offset)?; + resolve_external(&s, ws).get(id).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() +} + +// ---------------------------------------------------------------------- +// in one file +// ---------------------------------------------------------------------- + +/// The gap this round exists to close, in both spellings the grammar has: a +/// `struct` and a `union` answer their own fields. +#[test] +fn a_struct_and_a_union_both_answer_their_fields() { + let src = "\ +typedef struct packed { logic [7:0] addr; logic valid; } bus_t; +typedef union packed { logic [7:0] byte_view; logic [7:0] raw; } view_t; + +module m; + bus_t s; + view_t v; + initial begin + y = s.addr; + y = s.valid; + y = v.byte_view; + end +endmodule +"; + let s = sem(src); + for spelling in ["s.addr", "s.valid", "v.byte_view"] { + let name = spelling.split('.').nth(1).expect("a member"); + assert_eq!( + resolution_at(&s, tail(src, spelling, 0)), + Resolution::Resolved(symbol_named(&s, name)), + "{spelling}" + ); + } +} + +/// A field is a declaration with a **declared type**, so the chain hops +/// through it exactly as a class property's does. +#[test] +fn a_chain_hops_through_a_fields_own_type() { + let src = "\ +typedef struct packed { logic [7:0] addr; } hdr_t; +typedef struct packed { hdr_t hdr; logic ok; } pkt_t; + +module m; + pkt_t p; + initial y = p.hdr.addr; +endmodule +"; + let s = sem(src); + assert_eq!( + resolution_at(&s, link(src, "p.hdr.addr", 0, 1)), + Resolution::Resolved(symbol_named(&s, "hdr")), + "the middle link" + ); + assert_eq!( + resolution_at(&s, tail(src, "p.hdr.addr", 0)), + Resolution::Resolved(symbol_named(&s, "addr")), + "and the tail, in the field's own type" + ); +} + +/// A field's type carries the same unpacked rule every other declarator does: +/// `hdr_t hdrs [4]` names a container, not a value of the type, so the chain +/// stops rather than pretending the array is one element. +#[test] +fn an_unpacked_field_carries_no_type_and_stops_the_chain() { + let src = "\ +typedef struct packed { logic [7:0] addr; } hdr_t; +typedef struct packed { hdr_t hdrs [4]; } pkt_t; + +module m; + pkt_t p; + initial y = p.hdrs.addr; +endmodule +"; + let s = sem(src); + assert_eq!( + resolution_at(&s, link(src, "p.hdrs.addr", 0, 1)), + Resolution::Resolved(symbol_named(&s, "hdrs")), + "the field itself is still a declaration" + ); + assert!( + s.reference_at(tail(src, "p.hdrs.addr", 0)).is_none(), + "but its element's type is not the array's" + ); +} + +/// A field a struct genuinely does not have records nothing: the body is +/// written here whole, so no other file could supply it and `NotFound` would +/// overstate what is known. +#[test] +fn a_field_absent_from_a_struct_declared_here_records_nothing() { + let src = "\ +typedef struct packed { logic a; } s_t; + +module m; + s_t s; + initial y = s.nope; +endmodule +"; + let s = sem(src); + assert!(s.reference_at(tail(src, "s.nope", 0)).is_none()); +} + +/// The two heads that still record nothing, and must: an `enum` typedef, whose +/// `.name()`/`.next()` are built-in methods rather than members of anything +/// this crate models, and an alias of a built-in. +#[test] +fn enum_and_builtin_alias_heads_are_untouched_by_this_round() { + 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.name; + end +endmodule +"; + let s = sem(src); + assert!(s.reference_at(tail(src, "v.whatever", 0)).is_none(), "an alias of a built-in"); + assert!(s.reference_at(tail(src, "st.name", 0)).is_none(), "an enum's built-in method"); +} + +/// A struct typedef inside an **in-file** package answers through the +/// qualified spelling, on the same descent every other qualified type takes. +/// The round-1 pin for a *non*-aggregate typedef in an in-file package +/// (`p::alias_t`) is untouched and is re-asserted here beside it. +#[test] +fn a_struct_typedef_in_an_in_file_package_answers_and_an_alias_still_does_not() { + let src = "\ +package p; + typedef struct packed { logic [7:0] addr; } bus_t; + typedef int alias_t; +endpackage + +module m; + p::bus_t s; + p::alias_t v; + initial begin + y = s.addr; + y = v.whatever; + end +endmodule +"; + let s = sem(src); + assert_eq!( + resolution_at(&s, tail(src, "s.addr", 0)), + Resolution::Resolved(symbol_named(&s, "addr")), + "the package is walked through and the struct answers" + ); + assert!( + s.reference_at(tail(src, "v.whatever", 0)).is_none(), + "an int alias in the same package still says nothing" + ); +} + +// ---------------------------------------------------------------------- +// the anonymous forms (topo §2.9-13) +// ---------------------------------------------------------------------- + +/// `enum {A, B} x;` declares its variants in the enclosing scope, exactly as +/// `typedef enum {A, B} e_t;` always has — one helper, both spellings, and the +/// LRM's own rule (IEEE 1800 §6.19). +#[test] +fn an_anonymous_enums_variants_are_declared_in_the_enclosing_scope() { + let src = "\ +module m; + enum logic [1:0] { IDLE, RUN, DONE } state; + initial begin + state = RUN; + if (state == DONE) state = IDLE; + end +endmodule +"; + let s = sem(src); + for name in ["IDLE", "RUN", "DONE"] { + assert_eq!( + s.symbol(symbol_named(&s, name)).map(|sym| sym.kind), + Some(SymbolKind::EnumVariant), + "{name} is declared" + ); + } + assert_eq!( + resolution_at(&s, nth(src, "= RUN", 0) + 2), + Resolution::Resolved(symbol_named(&s, "RUN")), + "and a bare use of one resolves" + ); +} + +/// The same, one level in: an anonymous enum standing as a **struct field's** +/// type declares its variants in the scope the struct body is written in. +#[test] +fn an_enum_inside_a_struct_field_declares_its_variants_outside_the_struct() { + let src = "\ +typedef struct packed { + enum logic [1:0] { A_IDLE, A_RUN } mode; + logic ok; +} cfg_t; + +module m; + cfg_t c; + initial begin + y = c.mode; + y = A_RUN; + end +endmodule +"; + let s = sem(src); + assert_eq!( + resolution_at(&s, tail(src, "c.mode", 0)), + Resolution::Resolved(symbol_named(&s, "mode")), + "the field itself" + ); + assert_eq!( + resolution_at(&s, nth(src, "= A_RUN", 0) + 2), + Resolution::Resolved(symbol_named(&s, "A_RUN")), + "and the variant, bare, from outside the struct" + ); +} + +/// An **anonymous** `struct {…} s;` has no type name for `s.a` to be looked up +/// through, so its members hang off the declarator itself. +#[test] +fn an_anonymous_struct_variable_answers_its_own_fields() { + let src = "\ +module m; + struct packed { logic [7:0] addr; logic valid; } s; + initial begin + y = s.addr; + y = s.nope; + end +endmodule +"; + let s = sem(src); + assert_eq!( + resolution_at(&s, tail(src, "s.addr", 0)), + Resolution::Resolved(symbol_named(&s, "addr")) + ); + assert!( + s.reference_at(tail(src, "s.nope", 0)).is_none(), + "a field it does not have is still nothing" + ); +} + +/// A body written once and declared under **two** declarators gives each its +/// own members — and records the names written inside it exactly once, which +/// is why the declaration half and the use half of the binder are separate. +#[test] +fn two_declarators_share_one_anonymous_body_without_doubling_its_uses() { + let src = "\ +typedef logic [7:0] byte_t; + +module m; + struct packed { byte_t addr; } a, b; + initial begin + y = a.addr; + y = b.addr; + end +endmodule +"; + let s = sem(src); + assert!(s.reference_at(tail(src, "a.addr", 0)).is_some(), "the first declarator"); + assert!(s.reference_at(tail(src, "b.addr", 0)).is_some(), "and the second"); + let byte_uses = + s.references().iter().filter(|r| r.name == "byte_t" && !r.name_span.is_empty()).count(); + assert_eq!(byte_uses, 1, "the field's type name is written once and recorded once"); +} + +/// The generated-register-package shape, in one file: an **inline nested** +/// field, reached through the scope it opens rather than through a type name +/// it does not have. Three levels deep, because register packages are. +#[test] +fn an_inline_nested_field_answers_in_file_to_any_depth() { + let src = "\ +typedef struct packed { + struct packed { + struct packed { + logic q; + logic qe; + } inner; + } ctrl; +} reg2hw_t; + +module m; + reg2hw_t reg2hw; + initial begin + y = reg2hw.ctrl.inner.q; + y = reg2hw.ctrl.inner.qe; + end +endmodule +"; + let s = sem(src); + assert_eq!( + resolution_at(&s, link(src, "reg2hw.ctrl.inner.q", 0, 1)), + Resolution::Resolved(symbol_named(&s, "ctrl")) + ); + assert_eq!( + resolution_at(&s, link(src, "reg2hw.ctrl.inner.q", 0, 2)), + Resolution::Resolved(symbol_named(&s, "inner")) + ); + assert_eq!( + resolution_at(&s, tail(src, "reg2hw.ctrl.inner.q", 0)), + Resolution::Resolved(symbol_named(&s, "q")) + ); + assert_eq!( + resolution_at(&s, tail(src, "reg2hw.ctrl.inner.qe", 0)), + Resolution::Resolved(symbol_named(&s, "qe")) + ); +} + +// ---------------------------------------------------------------------- +// across files +// ---------------------------------------------------------------------- + +const BUS: &str = "typedef struct packed { logic [7:0] addr; logic valid; } bus_t;\n"; +const USER: &str = "module m;\n bus_t s;\n initial y = s.addr;\nendmodule\n"; + +/// A struct typedef at **file scope** in another file: the member table is +/// keyed by the typedef's own name, which is what the composed path spells. +#[test] +fn a_file_scope_struct_typedef_answers_from_another_file() { + let ws = index(&[("bus.sv", BUS), ("m.sv", USER)]); + let def = overlay_def(&ws, USER, tail(USER, "s.addr", 0)).expect("the field"); + assert_eq!(def.kind, SymbolKind::StructMember); + assert_eq!(file_name(&ws, &def), "bus.sv"); +} + +/// And the same typedef **inside a package**, which is where a real one lives: +/// the members land under the typedef's bare name, exactly as a class nested +/// in a package already does, and the qualified spelling composes to it. +#[test] +fn a_package_nested_struct_typedef_answers_from_another_file() { + const PKG: &str = + "package bus_pkg;\n typedef struct packed { logic [7:0] addr; } bus_t;\nendpackage\n"; + const TOP: &str = "module m;\n bus_pkg::bus_t s;\n initial y = s.addr;\nendmodule\n"; + let ws = index(&[("pkg.sv", PKG), ("m.sv", TOP)]); + assert!(ws.units("bus_t").is_empty(), "a typedef inside a package is no file-scope unit"); + let def = overlay_def(&ws, TOP, tail(TOP, "s.addr", 0)).expect("the field"); + assert_eq!(def.kind, SymbolKind::StructMember); + assert_eq!(file_name(&ws, &def), "pkg.sv"); +} + +/// The opentitan register-package shape, literally: a package of struct +/// typedefs whose fields are inline nested aggregates, and a module in another +/// file whose port is typed by the outermost one. `reg2hw.ctrl.tx.q` is the +/// most common member access in the whole of RTL. +#[test] +fn the_register_package_shape_walks_four_links_across_files() { + const REG_PKG: &str = "\ +package uart_reg_pkg; + typedef struct packed { + struct packed { + logic q; + } tx; + struct packed { + logic q; + logic qe; + } rxrst; + } uart_reg2hw_ctrl_reg_t; + + typedef struct packed { + uart_reg2hw_ctrl_reg_t ctrl; + } uart_reg2hw_t; +endpackage +"; + const CORE: &str = "\ +module uart_core ( + input uart_reg_pkg::uart_reg2hw_t reg2hw +); + assign tx_enable = reg2hw.ctrl.tx.q; + assign fifo_rst = reg2hw.ctrl.rxrst.qe; +endmodule +"; + let ws = index(&[("uart_core.sv", CORE), ("uart_reg_pkg.sv", REG_PKG)]); + + // The synthesized key is what carries the inline nested hop across files. + assert_eq!( + ws.member("uart_reg2hw_ctrl_reg_t.tx", "q").len(), + 1, + "the inner field is registered under `owner.field`" + ); + assert!(ws.member("uart_reg2hw_ctrl_reg_t.tx", "q")[0].type_name.is_none(), "a plain `logic`"); + + let def = overlay_def(&ws, CORE, tail(CORE, "reg2hw.ctrl.tx.q", 0)).expect("the tail"); + assert_eq!(def.kind, SymbolKind::StructMember); + assert_eq!(file_name(&ws, &def), "uart_reg_pkg.sv"); + assert_eq!(def.lines.name, 4, "the `logic q;` inside `tx`"); + + // `qe` and `q` sit in the same inner struct and are told apart, which is + // the whole reason the key is synthesized rather than the bare field name. + let def = overlay_def(&ws, CORE, tail(CORE, "reg2hw.ctrl.rxrst.qe", 0)).expect("the tail"); + assert_eq!(def.lines.name, 8); +} + +/// The collision the bare-name convention buys, stated as a measurement rather +/// than argued away: two packages each declaring `cfg_t` put two `field`s in +/// one member table, and the lookup answers **both** or nothing — never one of +/// them chosen silently. +#[test] +fn two_packages_with_the_same_struct_typedef_name_never_answer_one_of_them() { + const A: &str = "package pa;\n typedef struct packed { logic field; } cfg_t;\nendpackage\n"; + const B: &str = "package pb;\n typedef struct packed { logic field; } cfg_t;\nendpackage\n"; + const TOP: &str = "module m;\n pa::cfg_t c;\n initial y = c.field;\nendmodule\n"; + let ws = index(&[("a.sv", A), ("b.sv", B), ("top.sv", TOP)]); + assert_eq!(ws.member("cfg_t", "field").len(), 2, "the premise: one key, two declarations"); + match overlay_target(&ws, TOP, tail(TOP, "c.field", 0)) { + Some(ExternalTarget::Ambiguous(defs)) => assert_eq!(defs.len(), 2, "every candidate"), + Some(ExternalTarget::StillUnresolved) | None => {} + other => panic!("a silent pick between two packages: {other:?}"), + } +} + +/// A hop whose type name the **workspace** declares twice is refused outright, +/// which is round 2's guard doing its job now that the struct half can answer. +#[test] +fn a_hop_through_a_name_the_workspace_declares_twice_is_refused() { + const HDR: &str = "typedef struct packed { logic [7:0] addr; } hdr_t;\n"; + const STRANGER: &str = "class hdr_t;\n bit [7:0] addr;\nendclass\n"; + const PKT: &str = "typedef struct packed { hdr_t hdr; } pkt_t;\n"; + const TOP: &str = "module m;\n pkt_t p;\n initial y = p.hdr.addr;\nendmodule\n"; + let ws = index(&[("hdr.sv", HDR), ("stranger.sv", STRANGER), ("pkt.sv", PKT), ("m.sv", TOP)]); + assert_eq!(ws.units("hdr_t").len(), 2, "the premise"); + assert!( + overlay_def(&ws, TOP, tail(TOP, "p.hdr.addr", 0)).is_none(), + "two answers is not one answer" + ); +} + +/// A struct-typed value whose type this file declares is **never** handed to +/// the workspace, however tempting a same-named class elsewhere looks. Round +/// 1's rule, re-attacked now that the in-file answer exists. +#[test] +fn the_in_file_struct_answers_and_a_stranger_class_never_does() { + const A: &str = "\ +typedef struct packed { logic 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)]); + let s = sem(A); + assert_eq!( + resolution_at(&s, tail(A, "s.field", 0)), + Resolution::Resolved(symbol_named(&s, "field")), + "answered here" + ); + assert!( + overlay_def(&ws, A, tail(A, "s.field", 0)).is_none(), + "so the workspace is never asked at all" + ); +} + +// ---------------------------------------------------------------------- +// determinism +// ---------------------------------------------------------------------- + +/// The new member census survives the record format and every index mutation, +/// and does not depend on the order files arrive in. +#[test] +fn struct_members_survive_the_record_format_and_every_index_mutation() { + const PKG: &str = "\ +package p; + typedef struct packed { + struct packed { logic q; } ctrl; + } reg2hw_t; +endpackage +"; + const TOP: &str = "module m;\n p::reg2hw_t r;\n initial y = r.ctrl.q;\nendmodule\n"; + + // A record encoded and decoded is the same record. + let facts = FileFacts::of(PathBuf::from("p.sv"), PKG); + let line = facts.encode().expect("encodable"); + assert_eq!(FileFacts::decode(&line).as_ref(), Some(&facts), "round trip"); + + let forward = index(&[("p.sv", PKG), ("top.sv", TOP)]); + let backward = index(&[("top.sv", TOP), ("p.sv", PKG)]); + assert_eq!(forward.fingerprint(), backward.fingerprint(), "insertion order is not an input"); + + let answer = |ws: &WorkspaceIndex| { + overlay_def(ws, TOP, tail(TOP, "r.ctrl.q", 0)).map(|d| (d.kind, d.lines.name)) + }; + let expected = answer(&forward); + assert!(expected.is_some(), "the premise: it answers at all"); + assert_eq!(answer(&backward), expected); + + // Rebuild the same index by hand, then mutate it back to itself. + let mut ws = index(&[("p.sv", PKG), ("top.sv", TOP)]); + ws.update_file(PathBuf::from("p.sv"), PKG); + assert_eq!(ws.fingerprint(), forward.fingerprint(), "a no-op update is a no-op"); + assert_eq!(answer(&ws), expected); + + assert!(ws.remove_file(&PathBuf::from("p.sv"))); + assert!(answer(&ws).is_none(), "the declaring file is gone, so the answer is"); + ws.absorb(vec![FileFacts::of(PathBuf::from("p.sv"), PKG)], &[]); + assert_eq!(answer(&ws), expected, "and comes back when it returns"); +} diff --git a/docs/features/class-member-access/README.md b/docs/features/class-member-access/README.md index d381b90..5b38aff 100644 --- a/docs/features/class-member-access/README.md +++ b/docs/features/class-member-access/README.md @@ -84,6 +84,10 @@ answer is the only forbidden outcome.** declaration all name no type at all, so they stay exactly what they were: nothing recorded. The walk is visited-guarded, so `typedef a_t b_t; typedef b_t a_t;` terminates. + **Amended 2026-09-01 by struct-members**: a `typedef struct` no longer needs + following — it *is* the type, and it now opens a scope of its own, which is + what makes `typedef s_t alias_t; alias_t s; s.field` land through this very + same alias chase. The other three are unchanged and still record nothing. - **Only `Ident` heads** — *amended by round 2*. A chain of `.`-separated identifiers is walked whole (`a.b.c.d`), and an instance name is a head like any other because its declared type is its module. Still head-only: an @@ -483,6 +487,11 @@ symbol to take a type from, and inventing one is a model change. An indexed or called link (`q[i].x`, `f().x`) is unchanged. A cross-file alias is followed only for a **file-scope** typedef (`index.units`); a typedef inside a package is a member, not a unit, and is not chased — filed, not attempted. +**Note added 2026-09-01 by struct-members**: the package-nested case is now +covered for *aggregates* by a different route — `collect_members` recurses into +a package's struct typedef and registers its fields under the typedef's bare +name — so `pkg::bus_t s; s.field` lands. A package-nested **alias** of a class +(`package p; typedef c1 my_t;`) is still not chased; unchanged, still filed. **Pins rewritten in place, all four because the round changes what is true:** `semantics.rs::a_hierarchical_name_resolves_only_its_head` → diff --git a/docs/features/struct-members/README.md b/docs/features/struct-members/README.md new file mode 100644 index 0000000..a37af2b --- /dev/null +++ b/docs/features/struct-members/README.md @@ -0,0 +1,534 @@ +# struct-members + +## Goal + +`typedef struct packed { logic [7:0] addr; } bus_t; bus_t s; s.addr` recorded +nothing at all before this round: hovering `addr` showed nothing, F12 did +nothing, and renaming the field left every use behind. Struct and union fields +are how RTL is written — a generated register package (`reg2hw.ctrl.q`), a +bus payload (`tl_i.a_address`), a DV config bundle — so the single largest +class of daily-driver names in a Verilog workspace was invisible. This round +gives a `struct`/`union` body the same standing every other named container +already has: its fields are **declarations** with their own declared types, +`resolve.rs` looks a member access up in them in-file, and the workspace index +exports them so `pkg::bus_t s; s.addr` crosses a file boundary. It also +delivers topo §2.9-13, the three **anonymous** forms that had no symbols at +all: `enum {A,B} x;`, `struct {…} s;`, and the inline nested member +(`struct packed { struct packed { logic q; } ctrl; } reg2hw_t;`) that every +generated register package is made of. + +The governing rule is class-member-access's, unchanged and load-bearing for +every stopping condition below: **a link that cannot be resolved honestly +records nothing, and nothing after it — a wrong answer is the only forbidden +outcome.** + +## Assumptions + +- **A struct body is a scope, and its fields are its members.** The binder + already opened a `ScopeKind::Struct` scope on the typedef symbol and declared + each field into it; nothing looked in. What changes is who may look: a `.` + through a value of that type, and the workspace's member table. Nothing else + searches a struct scope — name lookup still never walks into one, because no + pending use is ever recorded *in* one (a field's type, dimensions and + initializer are all bound in the scope the body is **written** in, which is + where those names are looked up from). +- **`union` is `struct`.** One AST node (`StructType::kw`), one scope kind, one + set of rules. A union's fields overlap in storage, which is a fact about + elaboration and not about which names a `.` may write. +- **A field carries its declared type, on the same terms every other + declarator does** — including the unpacked rule: `logic [7:0] arr [4]` names + a container, so no `type_name`, so `s.arr.anything` records nothing rather + than pretending the element's type is the array's. +- **A field genuinely absent from a struct records nothing.** The body is + written here whole; no other file can supply a field, so there is nothing to + ask the workspace and `NotFound` would overstate what is known. Same rule as + a fully-known class with no base. +- **An enum typedef head still records nothing.** `state_e st; st.name()` is a + built-in method (IEEE 1800 §6.19.5), not a member of anything this crate + models, and inventing an answer for it would be the forbidden outcome. So + would an alias of a built-in (`typedef int alias_t; v.whatever`). Both pins + from round 1 stay exactly as written. +- **An anonymous aggregate's members hang off the declarator that names it.** + `struct packed { logic a; } s;` has no type name for `s.a` to be looked up + through, so `s`'s own symbol opens the `Struct` scope and `resolve.rs` + reaches it through the same "this symbol opens a body" rule. This is + **in-file only**: no other file can name this variable's type, because it has + none, so `pkg::cfg.f` from another file stays unresolved. Stated, not + worked around. +- **An inline nested member is reached in-file by its own scope and across + files by a synthesized key.** `struct packed { struct packed { logic q; } + ctrl; } reg2hw_t;` gives `ctrl` a scope of its own in-file. Across files the + index registers the inner fields under `reg2hw_t.ctrl` — the container's key + and the member's name joined by a **`.`** — and puts that same spelling on + `ctrl`'s own `Def::type_name`, so the existing `member_type` hop walks + `reg2hw_t` → `ctrl` → `reg2hw_t.ctrl` → `q` with no new mechanism. Two + properties earn the `.`: no source can write it as a type name (the one + dotted spelling SystemVerilog has, `bus_if.mp`, is stripped to the interface + half before it is ever recorded), so a synthesized key can never collide with + a real unit or typedef; and it survives `last_segment` whole, which the + brief's `::` spelling would not. The bare alternative is unusable: `q`, `d` + and `qe` are the field names *every* generated register package repeats. +- **A struct typedef nested in a package exports under its bare name**, exactly + as a class nested in a package already does — which is what makes + `pkg::bus_t s; s.addr` land, because `resolve.rs` composes the path from the + type name's **last segment**. The cost is stated rather than solved: two + packages each declaring `typedef struct {…} cfg_t` collide in the member + table under `cfg_t`, and the lookup then answers `Ambiguous` (every + candidate, never a guess) or, for a *hop* through such a name, nothing at + all. That is the crate-wide duplicate-name policy, not a new one. +- **A type name the workspace declares twice still refuses the hop.** A struct + `hdr_t` in one file and an unrelated class `hdr_t` in another are two + answers, and `member_type` picks between candidates nowhere. This round makes + the struct half *able* to answer, which makes the refusal matter more, not + less. + +## Handshakes + +**Consumed from `vlog_parser`** (no change requested): +`TypedefKind::Struct(StructType)`, `StructType::members`, +`StructMember::{ty, declarators}`, `Declarator::{name, name_span, unpacked}`, +`DataType::inline() -> Option<&TypeExtra>` and `TypeExtra::{Enum, Struct}` — +the last two are what make an anonymous or inline aggregate reachable at all. +Handshake item 2 (a span for `DataType`) stays open and untouched. + +**Changed in `vlog_semantic` (this crate), all additive:** + +1. `bind.rs::bind_struct_members` declares a body's fields with + `declare_typed` (they carried no type before), and gives a field whose type + is an **inline nested** aggregate a `ScopeKind::Struct` child scope of its + own, recursively to any depth. +2. `bind.rs::bind_struct_uses` records every *use* written inside a body — a + field's type name, its dimensions, its initializer — in the scope the body + is written in. Split from the declaration half so a body written once and + declared under several declarators (`struct { hdr_t h; } a, b;`) records its + type names **once**. The pending-use order is byte-for-byte what it was, + because declarations record no pendings. +3. `bind.rs::bind_enum_body` is the one function all three enum spellings go + through — `typedef enum`, an anonymous `enum {A,B} x;`, and an anonymous + enum standing as a struct field's type. Its members are declared in the + scope **holding** the enum (IEEE 1800 §6.19), which is what `typedef enum` + already did and what the anonymous form now does too. +4. `bind.rs::bind_data_type` descends into an inline aggregate (`ty.inline()`) + for its uses, and `bind_declarators` gives an anonymous `struct {…} s;` + declarator its own `Struct` scope. +5. `resolve.rs::member_scope` accepts **any symbol whose child scope is a + `Struct` scope**, not only a class/module/interface. One rule serves the + typedef that names a body, the declarator of an anonymous one, and an + inline nested member — three shapes, no special cases. `type_here`'s alias + chase and `link_type`'s "a head with no type name may still open a scope" + arm both reach it unchanged. +6. `workspace.rs::is_exported` gains a `Typedef | StructMember` arm exporting + `StructMember`, and `collect_members` takes the member-table **key** + explicitly so it can recurse into a struct typedef nested in a package + (under the typedef's bare name, the nested-class convention) and into an + inline nested member (under the synthesized key from `nested_key`). +7. `FACTS_FORMAT` 8 → 9: the member census and the reference census both grow. + +**Promised to consumers:** `analyze` still never panics; every recorded +`name_span` still slices back to exactly the name; the `paths` spelling +contract is unchanged and `follow_one` reads it exactly as before — the only +new spelling is a synthesized `Def::type_name`, which is consumed by +`member_type` alone and is unwritable in source. + +**Requested of `lucisv_server`, and delivered inside this lane's own file +list:** `type_def.rs::alias_site` descends into a `typedef struct` body so +`textDocument/typeDefinition` answers on a field's type name and on the +field's own declarator. `index_cache.rs` needed no change: 8 → 9 alters the +census, not the record layout, so `as_a_format_4_record` strips exactly the +fields it stripped before. + +**Filed, not done (for the lead):** + +- **Member completion after `.`** — the follow-on lane TODO.md §17 already + names. `completion.rs` has no dot context at all today, and now that + `reg2hw.` has members to list, that is the natural next daily driver. Not + this lane's file. +- **`typeDefinition` inside an anonymous aggregate written as a data + declaration** (`struct { hdr_t h; } s;`, as opposed to a `typedef struct`). + `declarator_site` would have to take the cursor offset, which means touching + every one of its eight call sites for a shape the brief did not ask for. + Filed rather than done. +- **Cross-file anonymous struct variables** (`pkg::cfg.f` where `cfg` is a + package-level `struct {…} cfg;`). The variable's type has no name, so the + member table has nothing to key on; a synthesized key would have to be + minted for a *variable*, which is a different decision from minting one for + an inline member of a named type. In-file resolution works. + +## Status / TODO + +- [x] In-file: `member_scope` accepts a `Struct` child scope; fields declared + with `declare_typed`; an alias of a struct follows to it; enum and + int-alias heads still record nothing. +- [x] Cross-file: `is_exported(Typedef|StructMember, StructMember)`; + `collect_members` keyed and recursive; `Def::type_name` on fields. +- [x] Anonymous forms: `enum {A,B} x;` variants; anonymous `struct {…} s;` + child scope; inline nested members in-file and, across files, under the + synthesized `owner.field` key. +- [x] `FACTS_FORMAT` 8 → 9. +- [x] `type_def.rs`: descent into a `typedef struct` body. +- [x] Pins flipped and kept — see the work log. +- [x] Tests: new `crates/vlog_semantic/tests/struct_members.rs`, flips in + `member_access.rs`, e2e in `crates/lucisv_server/tests/e2e.rs`. +- [x] Corpus acceptance and store delta. + +## Corpus acceptance and cost + +`cargo test -p vlog_semantic --test corpus -- --nocapture`, plus the +`#[ignore]`d probe `what_the_tail_references_cost_the_index` in +`tests/member_access.rs`. "Before" was measured in a detached worktree at this +round's trunk (`95f930c`, v0.24.0) with the same corpus symlinked in, so both +columns are the same 860 files on the same machine. + +| 860-file corpus | before (`95f930c`) | after | +|---|---:|---:| +| symbols | 26 844 | **26 953** (+109) | +| references | 99 237 | **99 553** (+316) | +| resolved in-file | 70.3 % | 70.4 % | +| external candidates | 20.6 % | 20.5 % | +| inherited candidates | 7.9 % | 7.9 % | +| **unresolved** | 1 203 (1.21 %) | **1 162** (1.17 %) | +| names unplaced | 0 | **0** | +| indexed members | 12 298 | **12 642** (+344) | +| store bytes (`FileFacts::encode`, all 860 records) | 3 216 689 | **3 179 905** | +| time to read all 860 records | 1.004 s | 1.005 s | + +**The store got 36 784 bytes *smaller* (−1.14 %) while gaining 344 indexed +members**, which is worth stating plainly because it is the opposite of what a +round that exports more declarations should cost. The reason is the anonymous +forms: a bare use of an `enum {A, B} x;` variant used to be an +`ExternalCandidate` (or an `InheritedCandidate`) carrying its name and every +import path in scope, and is now `Resolved` — encoded as a `Local` fact, two +ranges and nothing else. Converting a few hundred of those buys back more than +the new `M` entries cost on this corpus. **The corpus is not the whole story**: +it holds 22 file-scope typedefs and no generated register packages, so a real +RTL tree with `*_reg_pkg.sv` files will grow instead. QA's opentitan pass is +where that number comes from; it is expected to be a *gain*, and the read path +is unchanged either way. + +**Unresolved falls by 41 and unplaced stays at 0.** That is the acceptance +column that matters: the round added 316 references and not one of them is a +name that resolves to nothing — every new tail either lands on a declaration or +was never recorded — and it *removed* 41 names that used to resolve to nothing, +which is exactly the anonymous-enum variants finally having declarations. + +**What a lookup costs.** Nothing new on the hot path. In-file, `member_scope` +gains one scope-kind comparison; the walk is the same `lookup_local` it always +was. Across files, a struct hop is the same `member_chain` map read a class hop +is — no file is read and nothing is parsed in either layer. + +**Live check against the real shape** (read-only, `hw/ip/uart/rtl` of the +owner's opentitan checkout, four files indexed, `git status` unchanged before +and after): + +| use in `uart_core.sv` | answer | +|---|---| +| `reg2hw.ctrl.tx.q` | `uart_reg_pkg.sv:159`, `logic q;` inside `} tx;` | +| `reg2hw.ctrl.nco.q` | `uart_reg_pkg.sv:135`, `logic [15:0] q;` inside `} nco;` | +| `reg2hw.fifo_ctrl.rxrst.qe` | `uart_reg_pkg.sv:215`, the `qe` of `} rxrst;` | +| `hw2reg.status.txfull.d` | `uart_reg_pkg.sv:293`, `txfull`'s `d` — **not** + `rxfull`'s, two lines up, which is the synthesized key earning its keep | + +Four uses, four right answers, each four links deep through two levels of +inline nested aggregate. + +## Work log + +**2026-09-01 — dev agent.** Read CLAUDE.md, TODO.md §17, the +class-member-access README in full (both rounds, both QA passes and both lead +reviews), interface-semantics, types-decls and vlog-semantic rules 3/4/8 +before touching anything. The lead's map was accurate. Five decisions where it +left latitude, and two deviations: + +1. **`member_scope` is written as "any symbol whose child scope is a `Struct` + scope", not "a `Typedef` whose child scope is one."** The brief asked for + the narrow version, which would have needed two more special cases later — + one for the anonymous `struct {…} s;` declarator and one for the inline + nested member, neither of which is a `Typedef`. Written the general way, all + three shapes are the same rule and there is nothing to keep in step. The + check is on the *scope's* kind rather than the symbol's, so it cannot + accidentally admit a class, a module or a package. +2. **The synthesized key joins with `.`, not `::`.** The brief specified + `reg2hw_t::ctrl`. That spelling does not survive `member_type`, which calls + `last_segment` on a `Def::type_name` before using it — `reg2hw_t::ctrl` + would become `ctrl`, a bare name that collides with every other `ctrl` in + the workspace, which is the exact failure the synthesized key exists to + avoid. A `.` survives `last_segment` whole, needs no special case anywhere, + and is unwritable as a type name: `type_name_of` strips SystemVerilog's one + dotted type spelling (`bus_if.mp`) down to the interface half before it is + ever recorded, so no source can produce a colliding key. The + `index.units(key)` ambiguity guard passes for free because no unit has a dot + in its name. +3. **The synthesized name lives on the `Def`, never on the `Symbol`.** Putting + it on `Symbol::type_name` would have broken the in-file answer: `link_type` + reads `type_name` *first* and only falls through to `member_scope` when + there is none, so an inline member carrying `reg2hw_t.ctrl` would have gone + to `type_here`, found nothing, and stopped the chain in the very file that + declares it. In-file the scope is the answer; across files the key is. The + two layers do not need the same representation and are better off not + sharing one. +4. **The binder's declaration half and use half are separate functions** + (`bind_struct_members` / `bind_struct_uses`). One function that did both + would have recorded a body's type names once *per declarator*, so + `struct { hdr_t h; } a, b;` would post two references at the same span — + two identical edits in a rename's edit set. Split, the pending-use order is + byte-for-byte what it was before this round, because declarations record no + pendings at all. +5. **One enum helper for all three spellings.** `bind_enum_body` is called from + the `typedef enum` arm and from `bind_data_type`'s inline arm, so an + anonymous enum and a typedef'd one cannot drift. + +**Deviation 1, argued: `a_chain_broken_by_a_struct_link_records_nothing_past_ +the_break`'s cross-file half stays "nothing".** The brief said the struct +should answer there. It must not: that fixture puts a struct `hdr_t` in one +file and an unrelated class `hdr_t` in another, so the workspace declares the +name twice and `member_type`'s existing guard refuses the hop. Picking the +struct because it is "the right one" would mean this layer choosing between two +workspace declarations on a hunch — round 2's lesson, one hop out. The test is +renamed `a_chain_continues_through_a_struct_link`, its in-file half flipped to +resolve, its cross-file half kept as a *refusal* with the ambiguity premise +asserted, and a third case added with the stranger removed, where the chain +does land on the struct's field. + +**Deviation 2, filed rather than done:** `typeDefinition` descends into a +`typedef struct` body but not into an anonymous one written as a data +declaration (`struct { hdr_t h; } s;`). `declarator_site` would have to take +the cursor offset, which means touching all eight of its call sites for a shape +the brief did not name. Filed in Handshakes. + +**Pins flipped, all four in this lane's own files and all four because the +round changes what is true:** `a_struct_typedef_typed_head_records_nothing` → +`..._resolves_its_own_field` (with an absent-field case added, so the "records +nothing" half of the rule is still pinned); `an_alias_of_a_struct_records_ +nothing` → `..._is_followed_to_its_fields`; +`a_chain_broken_by_a_struct_link_records_nothing_past_the_break` → +`a_chain_continues_through_a_struct_link` (see deviation 1); and +`a_local_typedef_is_never_looked_up_in_a_same_named_class_elsewhere` **keeps +its name and its point** — its premise line now reads 2 exports rather than 1, +because this file's own struct is one of them, which is precisely why the +reference is answered here and the workspace never asked. The two round-1 pins +the brief said must stay (`an_alias_or_enum_typedef_typed_head_records_nothing`, +`a_qualified_type_inside_an_in_file_package_records_nothing_unless_it_is_a_class`) +are untouched and green, and both are re-attacked from the new angle in +`struct_members.rs`. + +**Nothing outside the lane's file list was touched.** +`crates/vlog_refactor/tests/rename.rs:159` +`a_struct_member_renames_where_it_is_declared` asserts the declaration only, on +a fixture with no *use* of the member, so it keeps passing unchanged — the lead +may want to extend it now that a use is renamed too; this lane's own e2e +(`a_struct_field_is_renamed_with_its_uses_in_another_file`) pins the new +behavior instead. `crates/lucisv_server/src/index_cache.rs` needed no change: +8 → 9 is a census bump, not a layout one. + +**Gates**, run to completion on this tree: `cargo fmt --all -- --check` clean; +`cargo clippy --all-targets --workspace` zero warnings; `cargo test --workspace +--no-fail-fast` **2 810 passed, 0 failed, 38 ignored**; `cargo build -p +lucisv_server` clean; `node editors/vscode/smoke.js target/debug/lucisv-server` +→ `smoke: OK`. + +## QA log + +**2026-09-01 — QA agent.** Read CLAUDE.md, TODO.md §17, and this README in +full (Goal/Assumptions/Handshakes/work log) before touching anything. +Verdict: **SHIP**. + +**Gates**, re-run to completion on the unmodified working tree: `cargo fmt +--all -- --check` clean; `cargo clippy --all-targets --workspace` zero +warnings; `cargo test --workspace --no-fail-fast` → **2 810 passed, 0 failed, +38 ignored** (summed from every `test result:` line, matches the dev's number +to the digit); `cargo build --release` and `cargo build --release -p +lucisv_server` clean; `node editors/vscode/smoke.js target/release/lucisv-server` +→ `smoke: OK`. + +**Scope.** `git diff --stat` against `95f930c`: `TODO.md`, +`crates/lucisv_server/src/type_def.rs`, `crates/lucisv_server/tests/e2e.rs`, +`crates/vlog_semantic/src/{bind,facts,resolve,workspace}.rs`, +`crates/vlog_semantic/tests/member_access.rs`, three README amendments, +`docs/topo.md`, plus new `crates/vlog_semantic/tests/struct_members.rs` and +`docs/features/struct-members/`. No `vlog_parser`, `vlog_refactor` (source), +`completion.rs`, `model.rs`, or `editors/*` touched — matches the brief. No +`unwrap()`/`expect()`/`panic!` added to any library code path (checked the +full diff of every changed `src/` file). + +**Attack tests** (temporary, all in scratch, reverted after — none pin a bug, +so nothing was folded in): + +- `crates/vlog_semantic/tests/qa_attack.rs` (6 tests, deleted after running): + a struct member typed as a **class** chases through it + (`s.h.user_id` where `h: c1` inside a struct — resolves); **three-deep** + inline nesting cross-file with a same-named leaf at each branch + (`x.mid.inner_a.q` vs `x.mid.inner_b.q` — right sibling every time, lines 5 + vs 8 confirmed distinct); the synthesized key when the **owner is itself + package-nested** (`p::reg2hw_t` with an inline `ctrl.q`) — confirmed the key + stays the typedef's *bare* name (`reg2hw_t.ctrl`), matching the nested-class + convention `collect_members` already used, not the package-qualified + spelling; an inline nested field named the same as a real **file-scope + module** elsewhere in the workspace (`ctrl` as both a module and a nested + field) — no collision, resolves into the struct; **union** members resolve + like struct members; two packages with a same-named struct typedef, + approached through an explicit `pkg::` qualifier from a third file — never a + silent cross-package pick (ambiguous or, if resolved, provably the qualified + package's own field). All 6 passed on the first correct run (two initial + failures were the test's own line-number arithmetic, 0- vs 1-indexed — + `Def::lines.name` is 1-indexed, confirmed against the dev's own + `the_register_package_shape_walks_four_links_across_files` pin). +- `crates/vlog_refactor/tests/qa_attack_rename.rs` (2 tests, deleted after + running): renaming one nested inline field (`tx`'s `q`, sibling `rx`'s `q` + left alone) rewrites the declaration and every `owner.field` cross-file use, + and does not leak into the sibling nesting level; renaming a struct + typedef's own name (`bus_t` → `bus2_t`) leaves the field name (`addr`) + completely untouched in both the declaring and the using file. Both passed. +- `documentHighlight` was not separately attacked: `nav.rs::document_highlights` + is generic over `symbol_at`/`occurrences` with no kind-specific branch, so it + rides the same resolution already exercised above — read, not re-tested. + +**Opentitan RTL — read-only**, release server `--verbose`, opentitan root as +workspace (`index.scope: workspace`), hand-rolled Node LSP driver on stdio +(`scratchpad/qa_driver.js`, modeled on `editors/vscode/smoke.js` and prior +rounds' `qa_driver.js`). `git -C .../opentitan status --porcelain` before and +after: unchanged (`hw/ip/aes/dv/tb/tb.sv`, +`hw/{top_darjeeling,top_earlgrey}/ip/ast/rtl/ast.sv` only, the pre-existing +state the charter names). + +28 probes, 6 IPs (uart, spi_device, aes, i2c, usbdev, tlul) plus one DV file, +hover + definition on each: + +| use | file:line | answer | hover ms | def ms | +|---|---|---|---:|---:| +| `reg2hw.ctrl.tx.q` | `uart_core.sv` | `uart_reg_pkg.sv:159` | 3930* | 0 | +| `reg2hw.ctrl.rx.q` | `uart_core.sv` | `uart_reg_pkg.sv:156` | 0 | 0 | +| `reg2hw.ctrl.nco.q` | `uart_core.sv` | `uart_reg_pkg.sv:135` | 0 | 0 | +| `reg2hw.fifo_ctrl.rxrst.q` | `uart_core.sv` | `uart_reg_pkg.sv:214` | 0 | 0 | +| `reg2hw.fifo_ctrl.txrst.qe` | `uart_core.sv` | `uart_reg_pkg.sv:211` | 0 | 0 | +| `reg2hw.cfg.tx_order.q` | `spi_device.sv` | `spi_device_reg_pkg.sv:164` | 5 | 0 | +| `hw2reg.status.csb.d` | `spi_device.sv` | `spi_device_reg_pkg.sv:484` | 0 | 0 | +| `hw2reg.status.tpm_csb.d` (sibling of csb) | `spi_device.sv` | `spi_device_reg_pkg.sv:481` | 0 | 0 | +| `reg2hw.intr_enable.upload_cmdfifo_not_empty.q` | `spi_device.sv` | `spi_device_reg_pkg.sv:100` | 1 | 0 | +| `reg2hw.intr_test.upload_cmdfifo_not_empty.qe` | `spi_device.sv` | `spi_device_reg_pkg.sv:135` | 0 | 0 | +| `hw2reg.intr_state.upload_cmdfifo_not_empty.d` | `spi_device.sv` | `spi_device_reg_pkg.sv:463` | 0 | 0 | +| `hw2reg.status.fmtfull.d` | `i2c_core.sv` | `i2c_reg_pkg.sv:549` | 3 | 0 | +| `hw2reg.status.rxfull.d` **(the acid-test pair)** | `i2c_core.sv` | `i2c_reg_pkg.sv:546` | 0 | 0 | +| `hw2reg.status.hostidle.d` | `i2c_core.sv` | `i2c_reg_pkg.sv:540` | 0 | 0 | +| `hw2reg.rdata.d` (2-deep) | `i2c_core.sv` | `i2c_reg_pkg.sv:554` | 0 | 0 | +| `hw2reg.host_fifo_status.fmtlvl.d` | `i2c_core.sv` | `i2c_reg_pkg.sv:562` | 0 | 0 | +| `hw2reg.host_fifo_status.rxlvl.d` (sibling) | `i2c_core.sv` | `i2c_reg_pkg.sv:559` | 0 | 0 | +| `reg2hw.fifo_ctrl.avsetup_rst.qe` | `usbdev.sv` | `usbdev_reg_pkg.sv:417` | 4 | 0 | +| `reg2hw.fifo_ctrl.avout_rst.q` (sibling) | `usbdev.sv` | `usbdev_reg_pkg.sv:420` | 0 | 0 | +| `hw2reg.usbstat.rx_empty.d` | `usbdev.sv` | `usbdev_reg_pkg.sv:593` | 1 | 0 | +| `tl_i.a_address` (struct port, `tl_h2d_t`) | `tlul_adapter_reg.sv` | `tlul_pkg.sv:73` | 0 | 1 | +| `tl_o.d_valid` (struct port, `tl_d2h_t`) | `tlul_adapter_reg.sv` | `tlul_pkg.sv:108` | 0 | 0 | +| `item.a_addr` (DV, class member — unchanged) | `tl_agent/tl_monitor.sv` | `tl_seq_item.sv:45` | 1 | 0 | +| `reg2hw.ctrl_aux_shadowed.key_touch_forces_reseed.q` | `aes_core.sv` | `aes_reg_pkg.sv:105` | — | — | +| `reg2hw.trigger.start.q` | `aes_core.sv` | `aes_reg_pkg.sv:120` | — | — | +| `reg2hw.status.output_lost.q` | `aes_core.sv` | `aes_reg_pkg.sv:132` | — | — | +| `reg2hw.key_share0[i].q` | `aes_core.sv` | *no reference at all* | — | — | +| `reg2hw.iv[i].q` | `aes_core.sv` | *no reference at all* | — | — | + +\* First hover of the session pays the one-time answer-formatting warm-up; +every hover/definition after it is sub-millisecond. **Zero wrong answers.** +The three sibling "acid-test" pairs (`i2c` rxfull:546/fmtfull:549, `usbdev` +avsetup_rst:417/avout_rst:420, `spi_device` tpm_csb:481/csb:484) were +independently hand-verified by reading the generated `*_reg_pkg.sv` sources — +every one lands on its own sibling's field, never the other's. + +**The AES array misses are informational, not a struct-members defect.** +`reg2hw.key_share0[i].q` and `reg2hw.iv[i].q` fail because the chain has an +**indexed link mid-chain** (`key_share0[i]`), which `vlog-semantic`'s README +(rule 8, "What is still head-only") and `class-member-access`'s README both +document as out of scope *before this round and unrelated to it* — the same +`a[i].b`/`q[i].x` limitation that already refuses at a class member. Confirmed +by isolating the variable: three other AES chains through the very same +wildcard-imported `aes_reg2hw_t` (`import aes_reg_pkg::*;`), with no index, +answer correctly (`ctrl_aux_shadowed.key_touch_forces_reseed.q`, +`trigger.start.q`, `status.output_lost.q` — all three above). The struct half +is not what's missing here. + +**Diagnostics**: all 7 opened files (`uart_core.sv`, `spi_device.sv`, +`aes_core.sv`, `i2c_core.sv`, `usbdev.sv`, `tlul_adapter_reg.sv`, +`tl_monitor.sv`) published **0 diagnostics** — unchanged from what a struct- +unaware server would have shown on them (no regression this round could +introduce fires here regardless). + +**Timing.** Cold scan, `--verbose`, same 3 976-file / 3-skipped opentitan +checkout: trunk `95f930c` **3 543.79 ms**; this tree **3 925.48 ms** — both +comfortably in the same ballpark, reported honestly rather than rounded away +(the 10.8% gap is consistent with page-cache/machine noise across two +separate `cargo build --release` invocations minutes apart, not a hot-path +change — `member_scope` and `member_type` both do the same O(1) extra work the +README's cost section claims). Every hover and definition after the first +warm one answered in **0.00–0.52 ms**, sub-millisecond as required. + +**Store, opentitan on-disk index-cache** (the OS cache dir the server uses by +default, `~/Library/Caches/lucisv/index//index-cache` — same +mechanism and same file `interface-semantics`'s QA measured): trunk `95f930c` +**32 208 241 bytes** (matches that round's own reported "after" figure to the +byte, a sanity check on the methodology) → this tree **33 583 533 bytes**, +**+1 375 292 bytes (+4.27 %)**. This is a real, expected *gain*: the synthetic +860-file corpus (no register packages) shrank 1.14 % because it converts +external-candidate enum variants to local facts, but the README predicted a +real RTL tree with generated `*_reg_pkg.sv` files would grow instead, because +those files are almost entirely new exported `M` (member) entries with real +content. Opentitan is exactly that tree; the number is the predicted direction +and the QA methodology (trunk worktree build vs. this tree's build, same +opentitan checkout, same on-disk cache path) matches the dev's own corpus +comparison technique one level up, on the real target. + +**Docs.** The feature README is complete against the template (all seven +section headers present, Work log filled, Review reserved). All three +amendments (`types-decls`, `vlog-semantic`, `class-member-access`) were +re-read against the actual diff and are accurate — no claim in any of the +three overstates or misdescribes what `bind.rs`/`resolve.rs`/`workspace.rs` +actually do. The dev's five filed-not-done items (member completion after +`.`, `typeDefinition` inside an anonymous data-declaration aggregate, +cross-file anonymous struct variables, a package-nested class alias still +unchased, and — noted here for the lead, not filed by the dev — +`documentHighlight` was read rather than separately attacked, see Attack +tests above) are all recorded either in this README's Handshakes or in this +QA log for the lead to see. + +**Verdict: SHIP.** No wrong answer found anywhere — not in six targeted +adversarial unit-test attacks, not in two rename attacks, not across 28 real +probes spanning 6 opentitan IPs plus a DV file, including three planted +sibling-name acid tests hand-verified against source. The five misses are all +the same documented, pre-existing, unrelated limitation (`a[i].b` mid-chain +indexing). Gates green, scope respected, store growth is the predicted +direction at a plausible magnitude, timing sub-millisecond, diagnostics clean. + +## Review + +## Review + +**2026-09-01 — lead.** Approved and committed. + +- Read the resolver and index hunks in full. The in-file fix is exactly the + one gate the lead's map named — `member_scope` returning any symbol's + child scope when that scope is a `Struct` scope, so typedef, anonymous + declarator and inline nested field are one rule — and the fields moving + to `declare_typed` is what lets a chain hop through a member's own type. +- **The synthesized key is the round's real design**, and the dev's + deviation from the brief is the right one: `.`-joined, not `::`-joined, + because `member_type` runs `last_segment` on `Def::type_name` and `::` + would have collapsed `reg2hw_t::ctrl` back to the bare `ctrl` the key + exists to avoid. The `.` form is unwritable as a type name and passes the + `units()` ambiguity guard for free. QA's three planted sibling pairs + (`rxfull`/`fmtfull`, `avsetup_rst`/`avout_rst`, `tpm_csb`/`csb`) are the + proof it works where it matters — opentitan's generated register + packages — and the dev's own live check (`hw2reg.status.txfull.d` → + `txfull`'s `d`, not `rxfull`'s two lines up) found it before QA did. +- The cross-file stranger-class half of the old "chain broken by a struct + link" pin correctly stays a refusal: two workspace declarations of + `hdr_t` with different kinds is ambiguity, and the round-1 rule (nothing + rather than a guess) holds one hop out. +- Unresolved fell again, 1 203 → 1 162 (anonymous-enum variants that were + external candidates are now resolved), and the corpus store *shrank* + 1.14 % because a resolved local fact encodes smaller than the candidate + it replaced; opentitan's real register packages grow the store +4.27 %, + reported honestly by QA, with hover at 0.00–0.52 ms. +- Filed, carried forward: indexed mid-chain links (`reg2hw.key_share0[i].q`) + — a pre-existing vlog-semantic limitation QA isolated from this round; + `typeDefinition` inside an anonymous aggregate written as a data + declaration; cross-file anonymous struct variables; the package-nested + class-alias chase; and member completion after `.`, planned as TODO §18. +- Gates re-run by the lead: fmt clean, clippy zero warnings, 2 810 passed / + 0 failed, smoke OK. `docs/topo.md`: §2.9-13 struck as delivered, handshake + row added. Ships as 0.25.0 (FACTS_FORMAT 9). diff --git a/docs/features/types-decls/README.md b/docs/features/types-decls/README.md index 91b8d55..0843a67 100644 --- a/docs/features/types-decls/README.md +++ b/docs/features/types-decls/README.md @@ -26,6 +26,11 @@ packed dimensions, a `type` parameter outside the `#( ... )` list — plus a - Enum member names introduced by an *anonymous* enum are not entered into the semantic model's scopes (only `typedef enum` members are). Nothing in the formatter needs them; see Handshakes. + **Struck 2026-09-01 by struct-members** (`docs/features/struct-members/ + README.md`): they are now, in the scope holding the enum, exactly as a + `typedef enum`'s are — and so are an anonymous struct's members and an + inline nested member's. The assumption was only ever about what the + *formatter* needed; the LSP gap it left is closed. - An anonymous `struct`/`union` body always breaks one member per line, like the `typedef struct` path it shares. An anonymous `enum` body is a group: one line if it fits, else one member per line — again the `typedef enum` rule. @@ -68,12 +73,18 @@ packed dimensions, a `type` parameter outside the `#( ... )` list — plus a **Requests for other modules (not done here)** -- `vlog_semantic::bind` declares `typedef enum` members and `typedef struct` - members as symbols (`bind.rs:395`, `bind.rs:406`). The equivalent members of - an *anonymous* aggregate — `enum {A, B} x;`, the nested `struct packed {...} - q;` of a register-package typedef — are not declared, so go-to-definition - and hover do not find them. Purely an LSP completeness gap; the formatter - and the corpus metric do not depend on it. +- ~~`vlog_semantic::bind` declares `typedef enum` members and `typedef struct` + members as symbols. The equivalent members of an *anonymous* aggregate — + `enum {A, B} x;`, the nested `struct packed {...} q;` of a register-package + typedef — are not declared, so go-to-definition and hover do not find + them.~~ **Delivered 2026-09-01** by struct-members + (`docs/features/struct-members/README.md`), which reads exactly the two + hooks this section asked for: `DataType::inline()` and + `TypeExtra::{Enum, Struct}`. An anonymous enum declares its variants in the + enclosing scope; an anonymous `struct {…} s;` and an inline nested member + each open a `Struct` scope of their own, so `s.a` and `reg2hw.ctrl.q` + resolve, hover, navigate and rename. No parser change was needed — the AST + this feature shipped was already the whole handshake. - `vlog_linter`'s `enum-name-style` / `struct-union-name-style` only look at `ItemKind::Typedef`, so an anonymous aggregate is out of their reach by construction. That is correct today (an anonymous type has no name to diff --git a/docs/features/vlog-semantic/README.md b/docs/features/vlog-semantic/README.md index a4e2c32..cc9da83 100644 --- a/docs/features/vlog-semantic/README.md +++ b/docs/features/vlog-semantic/README.md @@ -114,14 +114,26 @@ Verilog requires at module scope — and as an editor needs mid-edit anywhere. 3. **Enum variants land in the scope holding the enum**, per the LRM — not inside the typedef. `typedef enum { IDLE } state_e;` in a module binds both `state_e` and `IDLE` in that module. + **Amended 2026-09-01 by struct-members**: so do an **anonymous** enum's + (`enum {A, B} x;`) and those of an enum standing as a struct field's type, + which declared nothing at all before — one binder function now serves all + three spellings. 4. **Struct members land in a `Struct` scope of their own**, hung under the typedef. Nothing ever *looks up* into it, so members cannot be reached as bare names — which is correct — but they are still symbols, so the outline - can show them. A `Struct` scope is deliberately **not** one of the scopes - the 2026-09-01 member access reaches into either (rule 8): a struct-typed - `s.field` needs handshake §2.9-13 (anonymous aggregates declare no symbols - at all) before it can answer the same question consistently, so it answers - nothing rather than answering half the spellings. + can show them. + **Amended 2026-09-01 by struct-members** (`docs/features/struct-members/ + README.md`), which delivers §2.9-13 and strikes the paragraph that used to + stand here (a `Struct` scope was "deliberately not one of the scopes member + access reaches into", pending the anonymous forms). A member access **does** + reach into one now, and consistently across every spelling: the scope hangs + off the `typedef` that names the body, off the *declarator* of an anonymous + `struct {…} s;`, or off an **inline nested** field, and `resolve.rs` accepts + any symbol whose child scope is a `Struct` scope. Fields carry their own + declared type, so `s.hdr.addr` hops through one. Bare-name lookup still + never enters a struct scope, and no pending use is ever recorded inside one + — a field's type, dimensions and initializer are bound in the scope the body + is *written* in. 5. **Imports.** `import p::*;` / `import p::x;` is recorded as an `Import` on the scope that wrote it (module header imports land on the module scope). Resolution consults it **only when `p` is a package declared in this @@ -170,15 +182,22 @@ Verilog requires at module scope — and as an editor needs mid-edit anywhere. two claims are different and only the first is honest here — and **a link that cannot be resolved honestly stops the chain**, so nothing is recorded for it or for anything after it. That covers: a type name **this file - declares as something with no members** (a struct or enum `typedef`, a - parameter, a shadowing variable), a member absent from a class this file - declares whole, and — across files — a hop through a type name the - workspace declares more than once. This file has answered what the type is, - and asking the index for a same-named class elsewhere would answer a - question the source never asked (QA finding 1 of round 1). Across files a - module still exports only its **ports and parameters**, so `u.internal_sig` - answers only when the module is in the same file (round 2's ruling, with - the measurement, in the feature README). + declares as something with no members** (an enum `typedef`, an alias of a + built-in, a parameter, a shadowing variable), a member absent from a class + or struct this file declares whole, and — across files — a hop through a + type name the workspace declares more than once. This file has answered + what the type is, and asking the index for a same-named class elsewhere + would answer a question the source never asked (QA finding 1 of round 1). + Across files a module still exports only its **ports and parameters**, so + `u.internal_sig` answers only when the module is in the same file (round + 2's ruling, with the measurement, in the feature README). + **Amended 2026-09-01 by struct-members**: a `struct`/`union` typedef is no + longer one of the "no members" answers — see rule 4. `bus_t s; s.addr` + resolves in-file, `pkg::bus_t s; s.addr` across files, and + `reg2hw.ctrl.tx.q` walks four links through two levels of inline nested + aggregate. The **rule** is untouched, and is what still refuses a stranger: + a file that declares `bus_t` as a struct answers `s.field` itself, and an + unrelated class `bus_t` elsewhere is never asked. 9. **Type names are uses.** A declaration written with a user-defined type (`my_t x;`, `pkg::word_t y;`) records a reference for the type, so go-to-definition works on it. Built-in type keywords record nothing. @@ -201,7 +220,8 @@ region | generate block | for-generate header | for/foreach statement`. `genvar i;` written at module scope binds there instead, as the LRM says. - A `for`/`foreach` *statement* opens a scope for the same reason (`for (int i = 0; ...)`). -- A `struct`/`union` body opens a `Struct` scope that lookup never enters. +- A `struct`/`union` body opens a `Struct` scope that bare-name lookup never + enters — and which, since 2026-09-01, a `.` member access does (rule 4). ### Simplifications (deliberate, all of them LRM-inexact) diff --git a/docs/topo.md b/docs/topo.md index c5650ef..e29b2e2 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -435,6 +435,7 @@ promise: | `class-member-access ◀──▶ workspace-index / index-persistence / vlog-semantic` | handshake | **`FACTS_FORMAT` 5 → 6** (2026-09-01): the field layout is unchanged but the reference census grew — `head.member` tails (`Target::MemberOf`, resolved head → `Symbol::type_name` → class scope → member, in-file `extends` chase) and names inside out-of-class method bodies (a stand-in `Class` scope carrying the class path as `extends`) are references now, so older stores must be discarded whole. `WorkspaceIndex::base_of` is a subclass → base map rebuilt in `merge` from the existing inheritance census (no new facts field); the cross-file chase lives in `follow_one` so hover, references and rename cannot disagree about what a tail names. `Symbol::type_name` is the declared type as written, deliberately absent on unpacked declarators (`c1 q[$]`) so `q.size()` never resolves against `c1`. `resolve` returns `Option`: a tail with nothing to say records no reference (not `NotFound`), keeping `a_hierarchical_name_resolves_only_its_head` and the unresolved count byte-stable. | | `class-member-access (round 2) ◀──▶ workspace-index / index-persistence / refactor-rename` | handshake | **`FACTS_FORMAT` 6 → 7** (2026-09-01): `Def::type_name` / `Decl::type_name` (the same capture rule as `Symbol::type_name`, now in `fingerprint`) and `ReferenceFact::External.base` (so `this.x`/`super.x` inherited uses post cross-file). Chains `a.b.c`: `Target::MemberOf { head, mids }` carries *spellings*, so the outer tail never depends on the inner's result — in-file `member_of` hops declared type → declared type; a chain leaving the file is ONE composed path `Unit::mid::tail` that `follow_one` walks via `member_type`, refusing a hop through a type name the workspace declares twice with different kinds. Instance heads: an instance symbol's `type_name` is its module; **modules export ports and parameters only** (lead ruling on measurement: nets/vars export cost +24 % store AND made `.port(w)` connections resolve to internal nets) — so `u.port` resolves cross-file, `u.internal` in-file only. Typedef-alias chase in `type_here`, file-scope typedefs cross-file. **Rename truth flipped**: `u_sub.sig` is sub's `wire sig` and is edited (`a_hierarchical_tail_that_resolves_is_renamed_with_its_declaration`); an unresolvable tail is left alone but no longer warned about — §2.9-20. | | `interface-semantics ◀──▶ workspace-index / index-persistence / class-member-access / editor-scopes` | handshake | **`FACTS_FORMAT` 7 → 8** (2026-09-01): three new kind names (`Interface`, `Modport`, `Clocking`), no layout change. `SymbolKind::is_instantiable()` (`Module | Interface`) is the predicate every "is this a module" filter now reads — resolve (`Target::Module`/`Port`, container/member scopes), `is_unit`, the completion module table, `nearest_definition`/`module_header`, candidates, design hierarchy, call hierarchy, refactor `locate_module`/`module_definition`/`module_names` — each pinned in place; the sidebar's schema-2 wire shape is unchanged. Export: `Interface => Net | Var | Port | Param | Typedef | Function | Task | Modport | Clocking` (a module still exports ports and params only — round-2 ruling stands). Modport and clocking-block names are symbols; the names inside them are `Target::InScope` references (scope-local, nothing on a miss — a lexical walk would land a modport port on a file-scope lure); a clocking block carries `type_name` = its enclosing unit so `vif.cb.data` hops through round-2 machinery unchanged. The modport half of `bus_if.mp` in a type position is `Target::TypeMember { unit }`, resolved through `type_here`. `IndexCounts.interfaces` is separate so `modules` still means modules. Semantic-token legend deliberately not grown (indices are wire contract): Interface/Modport highlight as `class`, Clocking as `variable`. Rename truth flipped: a modport renames from its type-position use (`renaming_the_modport_half_of_a_port_type_renames_the_modport`). | +| `struct-members ◀──▶ workspace-index / index-persistence / class-member-access / type-definition` | handshake | **`FACTS_FORMAT` 8 → 9** (2026-09-01): struct members exported (`is_exported(Typedef \| StructMember, StructMember)`), fields declared with `declare_typed` so `s.hdr.addr` hops through a member's own type, and `collect_members` recursing into package-nested struct typedefs (bare-name key, the nested-class convention — two packages with a same-named struct typedef collide by name and answer `Ambiguous`/nothing, never a guess) and into **inline nested fields under a synthesized key `owner.field` joined with `.`** carried as the field's `Def::type_name` — `.` not `::` because `member_type` runs `last_segment` on it and `::` would collapse to the bare field name; the key is unwritable as a type name and passes `units()`'s ambiguity guard for free. This is what makes opentitan's generated register packages resolve (`hw2reg.status.txfull.d` picks `txfull`'s `d`, not `rxfull`'s). `resolve::member_scope` accepts any symbol whose child scope is `ScopeKind::Struct` — typedef, anonymous declarator or inline field, one rule. `type_def.rs::alias_site` descends into `typedef struct` bodies. Corpus unresolved 1 203 → 1 162; store shrank 1.14 % (resolved anonymous-enum variants encode smaller than the external candidates they replaced). | | `define-table ◀──▶ macro-expansion` | handshake | What began as free-to-change became contract at M14: params stored **as written**, `NAME()` = `Some(vec![])` — `expand.rs` counts arguments against them and declines on mismatch. | ### 2.6 Refactor lane (the M-plan) @@ -534,7 +535,7 @@ update the filing README(s) and this file. | ~~10~~ | ~~`Fmt::raw_text`'s string-crossing path emits a `Doc::Text` carrying newlines~~ — **delivered 2026-08-26 (`53f2269`)**: both `raw_text` and the parameterized-type `#( … )` now emit `Doc::Inline`, whose printer arm resumes measuring from the text's own last line. directive-split's README (QA round 3 note) still documents it as open and should be struck there too | directive-split QA | ~~vlog_formatter~~ done | | 11 | Corpus scripts match `parse error:` / `lex error:` / `verification failed:` textually; a structured `--output-format json` for format mode would remove it | corpus-check | crates/lucisv | | 12 | `vlog_refactor::rename::Scope::build` re-derives sort-and-dedup by hand; could call `index_order` | indexing-ux | vlog_refactor | -| 13 | Anonymous-aggregate members (`enum {A,B} x;`) not declared as symbols — hover/definition gap | types-decls | vlog_semantic | +| ~~13~~ | ~~Anonymous-aggregate members (`enum {A,B} x;`) not declared as symbols — hover/definition gap~~ — **delivered 2026-09-01 by struct-members**: anonymous enum variants land in the enclosing scope via the shared `bind_enum_body`; an anonymous `struct {…} s;` declarator and every inline nested struct field carry their own `Struct` child scope, and `member_scope` accepts any symbol whose child scope is a `Struct` scope. Residue filed in the struct-members README: cross-file anonymous struct *variables*, `typeDefinition` inside an anonymous aggregate written as a data declaration | types-decls | ~~vlog_semantic~~ done | | 14 | A `program` node with `name_span`/`end_label_span` (today it lands in `Error`/verbatim), which would let linked-editing serve it with one arm | linked-editing | vlog_parser | | 15 | Bind semantics: whether a `bind`'s target scope and connections should resolve through the workspace index (today only the instantiated module name is recorded) | bind | vlog_semantic | | 16 | DPI/package re-export halves as real references (`export pkg::item` doesn't resolve; `*::*` has `"*"` as its package name, which nothing expects) | dpi-export | vlog_semantic |