# ansi-first-port ## Goal An ANSI module header whose **first** port carries no direction did not parse: `module m (bus_if bus, input logic clk);` became an `Error` item, and so did `module m (bus_if.mp bus);` and `module m (my_pkg::state_t s);`. IEEE 1800 §23.2.2.2 makes the direction optional on every ANSI port including the first (it defaults to `inout`, and to whatever the previous port wrote for a continuation port), and for an *interface* port there is no direction to write at all — `bus_if bus` is the only spelling there is. This round closes that gap: the port list is classified ANSI-or-not by what follows the first identifier rather than by the identifier alone, and an interface port may name its modport. It was filed as Handshake request 2 of `docs/features/type-definition/README.md`, whose interface-port tests had to write the port *second* to have anything to test. ## Assumptions - **A first port spelled `ident ident` is a type and a name, never two non-ANSI port names.** SystemVerilog has no port list in which two identifiers stand side by side without a separator, so the pair is unambiguous. The non-ANSI list is exactly the case where the first identifier is followed by `,` or `)`, and that is what the disambiguation tests for — through the same lookahead (`at_typed_declarator`) that already decides `pkg::my_t x` from `x[i] = 1` everywhere else in the parser. - **A `.` after an identifier is a member access everywhere except a port header.** That is why `bus_if.mp bus` is recognized in `parse_ansi_port` and not in `parse_opt_data_type`: making the general type parser accept a dotted name would change how an identifier is read in expression and declaration positions, which is far more than this gap asks for. `virtual bus_if.mp v;` (a modport-qualified *virtual interface*, legal per §25.9) is therefore still not parsed — see Status. - **A modport belongs in the type name, glued.** `DataType::name` already carries `pkg::state_t` glued, and every consumer prints or scans that one string; `bus_if.mp` follows the same rule, so no consumer needed a new field. The one place the two halves matter is `vlog_semantic`, which binds the interface half (below). - ~~**A modport is not a symbol.**~~ **Delivered 2026-09-01** by `docs/features/interface-semantics/README.md`: a modport is a `SymbolKind::Modport` declared in its interface's scope, and the tail of the glued type name is bound where this said it would be — in `bind_data_type`, as `Target::TypeMember { unit }`, resolved through the interface's own scope in-file and as the path `bus_if::mp` across files. Until then it read: *`ItemKind::Modport` is a leaf in `vlog_semantic` (it declares nothing into a scope), so the modport half of the type name is left unbound rather than recorded as a name that could never resolve. The day modports become symbols, the tail is where to bind them.* - **`module m (interface bus);`** — the *generic* interface port, whose type is the `interface` keyword itself — is a separate production and still does not parse. It is neither one of the three shapes filed nor reachable from them; deliberately out of scope (Status). ## Handshakes **Changed in `vlog_parser` (`crates/vlog_parser/src/parser.rs`):** - `parse_port_list`'s ANSI/non-ANSI classification now also answers "ANSI" for a leading `Ident` that begins a typed declarator (`at_typed_declarator`, which already looks past a `pkg::` chain, a `#( ... )` override and packed dimensions) or a modport-qualified port (`at_modport_port`). Every other input classifies exactly as before — a macro token is `TokenKind::Directive` and never `Ident`, and a name followed by `,`/`)` is still a non-ANSI list. - `parse_ansi_port` takes `bus_if.mp` as the port's type via the new `at_modport_port` / `parse_modport_port_type` pair. - **No AST change.** The new shapes are ordinary `AnsiPort`s with `dir: None` — the value a non-first direction-less port has always carried — so `PortList`, `AnsiPort` and `DataType` are byte-identical to what downstream already handles. `AnsiPort::ty.name` is the one field that can now contain a `.`. **Changed in `vlog_semantic` (`crates/vlog_semantic/src/bind.rs`):** - `bind_data_type`'s unqualified arm binds the half of the type name before a `.` (`bus_if` of `bus_if.mp`) as `Target::Type`, instead of using the glued string as a name. The ANSI-port call site (`bind_module`, `bind.rs:393`) is unchanged: the type window is still "start of the port → start of its name", which is exactly right for a port that writes no direction. **Changed in `lucisv_server` (`crates/lucisv_server/src/type_def.rs`):** - `type_span` matches a site's type name by the half before its `.` as well as by its last `::` segment, so the cursor on a modport-qualified port reaches the interface. See that feature's work log. **Consumed, unchanged:** `vlog_formatter` prints `AnsiPort` through `ansi_port_cells`/`data_type`, which write `ty.name` verbatim — a glued modport round-trips with no formatter change. `vlog_refactor`'s `instantiate::ansi_ports` reads the port's *source text* between its start and its name, so it reports `iface_bus.mst` as the type with no change either. **Requested of other modules:** nothing. ## Status / TODO - [x] Reproduce all three shapes as `Error` items before changing anything. - [x] `parse_port_list`: classify a leading `ident ident` / `ident :: ident ident` / `ident . ident ident` as ANSI. - [x] `parse_ansi_port`: the modport-qualified interface port. - [x] `bind_data_type`: bind the interface half of a dotted type name. - [x] `type_def::type_span`: match it back. - [x] 9 parser tests, 7 formatter table cases, 1 semantic binding test, 2 server tests, 2 refactor tests (one flipped, one new). - [x] Corpus before/after: identical, with every file's formatted output byte-identical (below). - [x] Handshake 2 struck in `docs/features/type-definition/README.md`; the stale annotation in `TODO.md` §9c corrected. - [ ] **Not done, deliberately: `module m (interface bus);`** — the generic interface port (IEEE 1800 §25.3), whose type is the `interface` keyword itself. It is a different production, none of the three filed shapes needs it, and it wants a `DataType` that can say "any interface", which is a modelling question this round should not answer in passing. - [x] ~~**Not done, deliberately: `virtual bus_if.mp v;`**~~ — delivered by the testbench-mopup round (2026-08-29): `at_modport_port` — this feature's own gate — is reused at the two `virtual` positions, so the dot is read only where a modport can legally follow, exactly the narrow reading this item said a broad `parse_opt_data_type` change would violate. The pinning test here was amended in the same round (`the_two_shapes_left_open_by_ansi_first_port_still_refuse` still pins what genuinely remains open). See `docs/features/testbench-mopup/README.md`. - [ ] **Not done, pre-existing: `module m (a[3], b);`** — a non-ANSI port with a bit-select. It failed before this round and fails identically after (pinned by `a_broken_header_still_reports_its_own_token`), and it is not what this gap was about. ## Work log ### 2026-08-26 — dev agent - **Reproduced first, and the filed report was accurate to the token.** A throwaway `parse_source_tolerant` harness (removed after use) gave, for the three shapes: `expected ")" (found "bus")`, `expected ")" (found ".")`, `expected ")" (found "::")` — each producing two `Error` items, the header and the orphaned `endmodule`. It also turned up two facts the report did not state and the fix had to account for: `my_pkg::state_t s` already parsed in a *non-first* position (`at_typed_declarator` walks `::` chains), while `bus_if.mp bus` parsed in **no** position at all — so the modport is a second, independent gap that merely looked like part of the first. - **The disambiguation is a lookahead, not a new grammar.** `parse_port_list` classified the list from its first token: a direction keyword, a type keyword or a net keyword meant ANSI, anything else meant a non-ANSI name list. The fix adds one clause — a leading `Ident` that `at_typed_declarator` says still leaves an identifier for the declarator name. That predicate already exists and is already the parser's answer to "type-then-name or something else", including past `pkg::`, `#( ... )` and packed dimensions; reusing it means the header list cannot drift out of step with how a body declaration is read. The complement is exactly the non-ANSI list: after the first name comes a `,` or a `)`, neither of which is an identifier. - **The modport is glued into the type name, and only in a port header.** `interface_port_header ::= interface_identifier [ . modport_identifier ]` is a port production, not a data-type production, and after an identifier anywhere else a `.` opens a member access — so `at_modport_port` / `parse_modport_port_type` sit in `parse_ansi_port`, four tokens of lookahead wide (`ident . ident ident`), and `parse_opt_data_type` is untouched. Gluing follows the `pkg::state_t` precedent, which is what kept the AST, the formatter and `vlog_refactor` out of this change entirely. - **`vlog_semantic` binds the interface, not the glued string.** Left alone, `bind_data_type` would have recorded a use of the name `bus_if.mp`, which resolves nowhere and never could. It now takes the half before the dot. The modport half was dropped rather than bound because this crate declared no symbol for a modport — a reference to a name nothing can declare is worse than no reference. **Since 2026-09-01 it does declare one**, and both halves are bound (`docs/features/interface-semantics/README.md`). - **`type_def::type_span` needed the mirror of that.** The server matches a declaration site's type name against the references the binder left in the same window; with the site saying `bus_if.mp` and the reference saying `bus_if`, the match failed and the jump answered nothing. One line: match by the half before the `.` too, alongside the existing "last `::` segment" rule. - **No AST change, which was the point.** The brief asked whether `AnsiPort` already models absence of direction — it does (`dir: Option`), and every continuation port (`input a, b`) has carried `dir: None` since the beginning. So the new shapes produce AST that every existing consumer was already written for, and the whole downstream cost of this round was two match widenings (one in `vlog_semantic`, one in `lucisv_server`) that exist only because of the modport dot. - **Snapshot churn: none.** `crates/vlog_formatter/tests/snapshots/` is untouched, and `git diff --stat` shows no fixture file changed. No previously-refused fixture started formatting, so there was nothing to justify. - **Corpus: identical, which is itself the finding.** Baseline (HEAD 0e740d7, the change stashed) and after: `813/820 (99.1%)`, 11 ok-unchanged, 802 would-reformat, 7 parse-error, 0 verification-error, 0 crash — and the two TSVs are byte-identical, path for path, message for message. To prove the stronger property the TSV does not carry, every corpus file was formatted to stdout and hashed on both sides: all 820 hashes identical. So the passing set is a (trivially strict) superset, no file's output moved by a byte, and the safety net never fired. The reason nothing was gained is that this corpus contains no direction-less first port at all — had it contained one, that file would have been a `parse-error` row before and a formatted one after; the 7 that remain are the known macro-bracketed covergroup, the `` ` ``-number lex error and friends, unchanged. `vlog_semantic`'s corpus acceptance run agrees from the other side: 860 files, 561 modules, 94685 references, 88.8% of external candidates answered — identical to three decimal places before and after, so no previously-`Error` module header joined the index either. - **Tests.** `vlog_parser` +9 (`parser.rs` tests module): the three shapes, each alone and mixed with directed ports in both orders; an `interface` header taking the same list; a typed first port with packed dimensions and a parameterized one; the non-ANSI list pinned by name *and* by comma flags, plus the one-name list; `module m ();` and `module m;`; the `input a, b` direction carry-over; a macro-produced list, an escaped name and a comment before the comma, all three still non-ANSI because the clause fires only on a `TokenKind::Ident`; and recovery on two genuinely broken headers plus a never-closed one through `parse_source_tolerant`. `vlog_formatter` +7 table cases in `tests/cases/module_headers.cases` (each is an idempotency and equivalence assertion too — `format_source` verifies both, and the harness re-formats the expected output). `vlog_semantic` +1 (`tests/workspace.rs`): `a_direction_less_first_ansi_port_binds_its_interface_type_cross_file`, both spellings, cross-file through the unit table, plus an assertion that the port declarations themselves survived. `lucisv_server` +2 and one flipped (`type_def.rs`, now 47). `vlog_refactor`: `an_interface_typed_port_list_is_refused_as_a_parse_failure` → `an_interface_typed_port_list_is_planned_like_any_other` (it asserted the gap; it now asserts the plan, the rendered skeleton and that the skeleton parses), and +1 rename test through a direction-less first port. - **Gates.** `cargo fmt --all -- --check`: clean. `cargo clippy --all-targets --workspace`: 0 warnings. `cargo test --workspace`: green (0 failed anywhere; `vlog_parser` 214, `lucisv_server` 873). `cargo test -p vlog_formatter`: green, all 8 targets, no snapshot churn. `tools/corpus_check.sh` before and after: identical, exit 0 both times. `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`. No `git commit`, no `git push`; `docs/site/` untouched. ## QA log ### 2026-08-26 — QA agent **Gates, re-run independently — all matched the dev's claim exactly.** `cargo fmt --all -- --check`: clean. `cargo clippy --all-targets --workspace`: 0 warnings. `cargo test --workspace`: green, `vlog_parser` 214 passed, `lucisv_server` 873 passed / 4 ignored (the 4 ignored are pre-existing in `lucisv_server::{hierarchy,includes,inlay}`, unrelated to this round). `cargo test -p vlog_formatter --all-targets`: green, 7 test binaries run (`lib`, `cases`, `deep_nesting`, `fences`, `fixtures`, `ranges`, `verification`) — the work log's "all 8 targets" is one over the actual binary count; cosmetic, not a gate failure. `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`: `smoke: OK`. **Corpus proof — reproduced independently, not taken on the dev's word.** Built release binaries at the working tree and at a `git worktree add` of `0e740d7` (the round's parent commit) so the working tree was never stashed. `tools/corpus_check.sh corpus`: `813/820 (99.1%)` on both binaries, and the two TSVs are byte-identical (`diff` exit 0) — this also matches the dev's own `corpus-check-results.tsv` left in the tree byte-for-byte. Then, independent of the TSV, every one of the 820 corpus files was formatted with `--stdout` and SHA-256 hashed under both binaries: **all 820 hashes identical.** This is the round's central safety claim and it now has two independent confirmations (the dev's and this one), not one. **A. Classification-boundary sweep** (`vlog_parser::parse_source_tolerant`, current tree vs. the `0e740d7` worktree, diffed on `{diagnostics, debug AST}`): | shape | verdict | |---|---| | `module m (a, b);` | unaffected, byte-identical AST (non-ANSI, untouched) | | `module m (a);` | unaffected, byte-identical AST | | `module m (mytype a);` | now ANSI, `ty.name="mytype"` — correct | | `module m (a[3:0] b);` | now ANSI, packed dim consumed correctly | | `module m (a #(8) b);` | now ANSI, `#(...)` consumed correctly | | `module m (a.b);` (3-token, closes) | **unaffected** — `at_modport_port` needs a 4th `Ident` after the dotted name and correctly does not fire on `)`; still the same `expected ")" (found ".")` error both sides | | `module m (a.b.c d);` (5-token) | **unaffected** — the lookahead is exactly 4 tokens wide (`ident . ident ident`), a longer dotted chain does not match `at_modport_port`, so this still errors identically both sides (an underdocumented but correctly-failing edge, not a misfire) | | `module m (bus_if.mp bus, foo.bar baz);` (modport non-first) | now parses — confirms the work log's claim that `at_modport_port` fires per-port in `parse_ansi_port`, not just at list-classification, so any `ident.ident` port anywhere in an ANSI list now parses, not only `bus_if.mp` specifically | | `module m (my_pkg::t.mp bus);` (`pkg::type` + modport dot) | **unaffected, fails safe** — neither `at_typed_declarator` nor `at_modport_port` fires (the `::`-chain walk stops before a bare `.`), so this still reports `expected ")" (found "::")` on both sides. Not filed, not tested by the dev, but does not misfire — worth a line in Assumptions if this shape is ever revisited | | directive before first port, then a direction-less port (`` `ifdef FOO `endif bus_if bus, input logic clk); ``) | parses correctly — `take_list_directives` already peels the directive off before the ANSI/non-ANSI decision reads the next token, independent of this round's change | **No misfire found in either direction**: nothing that used to be a non-ANSI list started parsing as ANSI, and no shape swallowed characters it should not have. **B. Formatter round-trip.** All boundary and headline shapes above were run through `format_source` (`vlog_formatter::format_source`); every one that parses returned `Ok` (i.e. both `verify_equivalence` and `verify_convergence` passed internally — the safety net never fired). The three headline shapes' formatted output matches `module_headers.cases` byte-for-byte. `module m (a, b); input a; output b; endmodule` and `module m (a); input a; endmodule` (non-ANSI) format byte-identically between the `0e740d7` binary and the working-tree binary. No real corpus file with an old-style bare-name port list was found to spot-check against (consistent with the dev's note that this corpus has no such file) — the in-memory comparison above is the substitute. **C. `bind_data_type` / `type_span` modport handling — attacked, holds.** Added one test, `renaming_the_modport_half_of_a_port_type_is_refused` in `crates/vlog_refactor/tests/rename.rs` (kept; passes; +1 to `vlog_refactor`'s rename suite, 52 total): a rename request positioned on the `mp` of `bus_if.mp bus` is refused (`rename()` returns `Err`) rather than silently renaming the interface or corrupting the modport spelling — confirming `ItemKind::Modport` being an unbound leaf actually protects the rename path, not just the go-to-type-definition path. Renaming `bus_if` itself through the same port still renames correctly (already covered by the dev's `an_interface_renames_through_a_direction_less_ansi_port`). **D. Error recovery — two diagnostic-drift findings, not corruption.** Severity: low. The claim "error recovery unchanged" holds for the two specific fixtures the dev pinned (`module m (input, );` — confirmed byte-identical diagnostics and AST both sides) but **does not hold** for one of the exact shapes named in this round's own attack brief: - `module m (foo bar` (never closes, no `endmodule`) — file: `crates/vlog_parser/src/parser.rs`, the `ansi` lookahead added at the `parse_port_list` classification site (~line 2415) plus `parse_ansi_port` (~line 2494). Baseline: `expected ")" (found "bar")` at line 1 col 15. Current: `expected ")" (found "")` at line 2 col 1. Cause: `foo bar` is now recognized as a typed declarator (`at_typed_declarator` fires), so the parser commits to consuming it as one `AnsiPort` and only then looks for the next `,`/`)`, which is past EOF instead of at the second identifier. - `module m (bus_if bus;` and `module m (bus_if bus\nendmodule\n)` — same cause: baseline reports the error at the second identifier (`bus`, since it reads `bus_if` alone as a non-ANSI name and then chokes on a second identifier); current reports it at the token *after* the successfully parsed `bus_if bus` port (`;` or `endmodule` respectively). The dev's own test (`a_broken_header_still_reports_its_own_token`) only asserts `!diags.is_empty()` for the never-closed case, not a specific position, so this drift does not contradict any committed test — it contradicts the QA-brief's framing of "same error positions/recovery as baseline", which is not literally true for any genuinely-broken header that happens to start with two adjacent identifiers. - In every case checked, the file still ends up as a single `Error(RawText)` item over the same span with the same raw text on both sides — no partial output, no corruption, invariant #1 holds. This is a diagnostic-quality regression at worst (arguably the new position is more precise, since it points at the actual unexpected token rather than the first token past a guessed name), not a safety issue. No fix applied; recorded for the lead's judgment on whether the work log's phrasing needs softening. **E. Fuzz-ish sweep.** 50 corpus files with an ANSI first port whose leading direction keyword (`input`/`output`/`inout`) was stripped, re-parsed through `parse_source_tolerant` under `catch_unwind`: **0 panics**. 23 re-parsed clean (the stripped port had a real type after the keyword, e.g. `input logic clk` → `logic clk`, and the new classification correctly reads it as a direction-less typed port). 27 still report a parse error (the stripped port was just `input a` → bare `a`, which correctly falls back to non-ANSI classification and then fails on the *next* port's leading keyword with a sensible `expected identifier (found "input")` — fails safe, not a crash, not a silent misparse). **F. The three left-open items.** `module m (a[3], b);` is pinned by `a_broken_header_still_reports_its_own_token`, confirmed unchanged (matches the dev's specific pinning claim — this is the only one of the three the dev actually claimed a test for). `module m (interface bus);` (generic interface port) and `virtual bus_if.mp v;` (modport-qualified virtual interface declaration) are **not** pinned by any test anywhere in the diff, but both were confirmed byte-identical (diagnostics + AST) between `0e740d7` and the working tree by the same harness as section A. Recommendation, not a blocker: a one-line regression test for each would close the gap between "verified today" and "protected going forward," since neither has a test to catch a future regression. **G. CLAUDE.md compliance.** `crates/vlog_formatter/src/verify.rs`: `git diff --stat` shows no change — invariant #4 correctly not triggered (no normalization was widened, so no masked-corruption attack tests were owed). `unwrap()`/`expect()`/`panic!`: the only three `panic!`s added are inside `crates/vlog_parser/src/parser.rs`'s `#[cfg(test)] mod tests` (test-helper `ansi_ports`/list-shape assertions) — permitted, not library-path code. `at_modport_port` and `parse_modport_port_type` both have doc comments. `docs/features/ansi-first-port/README.md` has each required section exactly once, in the required order. The `type-definition` feature's Handshake 2 is struck with `~~...~~` and a "Delivered 2026-08-26" annotation, matching this repo's existing struck-handshake convention. `docs/site/` was not touched. **Not independently verifiable:** the work log's `vlog_semantic` corpus figure ("860 files, 561 modules, 94685 references, 88.8%... identical to three decimal places before and after") has no corresponding script under `tools/` and no committed test that reproduces it — unlike the `vlog_formatter` corpus proof (section above), which was fully reproduced. Not flagged as a defect (the two headline corpus proofs this round rests on are independently confirmed), just noted as an unverifiable secondary claim. **Fix made:** added `renaming_the_modport_half_of_a_port_type_is_refused` to `crates/vlog_refactor/tests/rename.rs` (section C above). No other changes to the diff under review. **Verdict: committable as-is.** No hard-invariant violation found (no corruption, comments-preservation and idempotency untouched, `verify.rs` untouched). One low-severity, non-blocking finding (D: diagnostic-position drift on genuinely-broken headers, which the lead may want reflected in the work log's phrasing) and two documentation/test-coverage gaps (the unpinned left-open items in F, and the unreproducible semantic-corpus figure) are recorded for follow-up, not for blocking this round. ## Review ## Review ### 2026-08-26 — lead Reviewed the diff, the work log and the QA log; re-ran all gates myself, clean. For the highest-invariant-risk crate in the repo, this round set the standard: reproduction before any fix (which surfaced that the modport shape was a second, independent gap), a classification clause built on the parser's own existing lookahead rather than a new recognizer, no AST change, and the corpus proof taken past the TSV to all 820 formatted-output hashes — which QA then re-established independently through a worktree build rather than trusting it. The boundary AST-diff harness and the 50-file direction-stripping sweep are exactly the adversarial coverage a parser change needs. Rulings on QA's three notes. The diagnostic-position shift on broken two-identifier headers is accepted: the parser committing further before failing is inherent to recognizing the new legal prefix, no Error item's span or text moved, and better commitment usually means better messages. The two unpinned left-open items are now pinned — I added `the_two_shapes_left_open_by_ansi_first_port_still_refuse` to the parser suite so a future round changes them on purpose. The unreproducible vlog_semantic corpus figure is a fair point filed against that README's tooling, not this round; the workspace harness tests remain the executable check. QA's modport-rename refusal test closes the one write-path question the match-widenings raised. Accepted as shipped.