# parser-skips ## Goal Close the two parser skips TODO §11 left open after the opentitan sweep — the last two shapes in that sweep that were grammar work rather than "not SystemVerilog". 1. **Rival unit headers in a conditional region** (`jtag_if.sv`). One `interface` header written twice across the arms of an `` `ifdef ``/`` `else `` region, both spellings bracket-*balanced*: ```verilog `ifdef GATE_LEVEL interface jtag_if #(parameter int unsigned P = 41_664) (); `else interface jtag_if #(parameter int unsigned P = 20_000) (); `endif wire tck; … endinterface ``` Before this round the first header parsed in full, the `` `else `` became a directive item of its body, the second `interface jtag_if` became a *nested* interface, and the outer one ran out of file: `163:1: expected `endinterface``. `directive-split`'s trigger never fired, because nothing errored until EOF and neither arm left a bracket open. Now the body loop recognises the rival before it parses the item, fails there, and the existing conditional-split recovery turns the **whole unit** into one `ItemKind::Verbatim` item — the same treatment a bracket-unbalanced split header has had since `directive-split`. 2. **A net delay written after the type** (`SimDTM.sv`). IEEE 1800 §6.7 puts `delay3` after the data type — `wire [31:0] #0.1 x = y;` — and lucisv parsed it only between the net keyword and the type. `DataDecl::delay` now carries the position it was written in and the formatter prints it there. No normalisation: moving a delay across the type reorders tokens, which `verify.rs` rightly refuses. ## Assumptions - **A rival header is a fragment, the way an unclosed bracket is.** Two bracket-balanced spellings of one header sharing one body are not a tree any more than two heads sharing one `{` are: there is no AST for "either this header or that one". So the unit joins the verbatim bucket rather than getting a layout. **The standing trade is `directive-split`'s** (README → Goal, and Status → "any canonical *layout* for the inside of a split region — it stays byte-for-byte"): the captured bytes come back exactly as written, so the unit's **body is not formatted**. For `jtag_if.sv` that means the file's one visible change is the block's own re-indent — `Fmt::raw_lines` dedents every line by the head's column, so a unit written two spaces in comes back at column 1 with its *relative* layout intact (`directive-split` README → Assumptions, "a verbatim block's relative layout is what survives"). `--check` therefore says "would reformat", not "unchanged". - **The rival trigger is five conditions at once**, and every one of them is read from the tokens — never from a flag someone could set by mistake: 1. the cursor stands on a `` `else `` / `` `elsif ``; 2. a conditional region was open at the unit's own first token (`open_conds > 0` there); 3. that region is still the live one — nothing opened inside the body is still open (`open_conds` is back to the header's value) **and** the header's own region was never closed inside the body (the body's lowest nesting never dipped below it). Without the second half, a body that closes the outer region and opens another would present a `` `else `` that continues the *new* region at the same count; 4. the token after the directive is the unit's own keyword; 5. the token after that is the unit's own name. - **The evidence is re-derived at the split, not carried on the error.** `ParseError` is a public struct with three public fields and no room for a flag; adding one would touch every construction site in the crate and give every error path a way to reach the recovery. `Parser::rival_end_kw` reads the same shape back out of `ItemMark::pos` and the cursor instead, which is exactly how the other three conditions of `at_split_conditional` are already checked. Cost: the shape is spelled twice (`at_rival_header` for the body loop, `rival_end_kw` for the split). Benefit: the whole trigger stays in one file and is provable from the token stream alone. - **The extent scan ends at the unit's closing keyword.** A unit header's own `;` closes only the header, so the `;` rule `scan_split_extent` has always used would have ended the block at the first body declaration. With `unit_end = Some(kw)` the scan runs to the matching `endmodule` / `endinterface` / `endprogram`, counting units of the same kind so one nested in the body cannot end it early, and swallowing an `endinterface : name` label the way the opening split already does. An `interface class` nested inside a captured `interface` closes with `endclass`, leaves the unit count above zero and makes the scan give up — the parse error stands, which is the safe side of the trade. - **Both delay positions, never both at once.** `wire #5 [31:0] #6 x;` is a parse error naming the rule. Only a *net* declaration reads a delay in either position, so `logic #5 x;` and `logic [7:0] #5 x;` are the ordinary syntax errors they always were. - **A comment written directly in front of the `#` has no slot.** It is refused by `verify.rs` (token reorder), for the after-type position and for the before-type position alike. That is **pre-existing** — the before-type spelling has behaved this way since the delay was first parsed — and the new position inherits it unchanged. Recorded as a `#SKIP` case in `net_delay_position.cases`, not fixed: giving the delay a comment slot is a `comment-slots` change. The other gaps around a delay (an attribute in front of the declaration, a comment after the delay) do round-trip. ## Handshakes ### Consumed - `Parser::split_conditional_item` / `capture_split` / `verbatim_since` / `Fmt::raw_lines` — the `directive-split` recovery and its verbatim printer, used unchanged. `ItemKind::Verbatim` gains no new producer: the same call in `parse_item_inner` produces it. - `Parser::open_conds` and `ItemMark::conds` — the item-scope conditional nesting `directive-split` maintains in `note_item_conditional`. Read, not written, by the rival path; the one write is the existing `self.open_conds = conds_after` in `split_conditional_item`. - `Parser::parse_delay_value` (`parser/instance.rs`) — reads `#5`, `#0.1` and `#(1:2:3)`. Used unchanged for both positions. ### Promised / changed for others - **`at_split_conditional`'s fourth condition widened**, from "the arm left a bracket open" to "the arm left a bracket open **or** the arm behind the directive re-writes this item's own unit header". Recorded in `docs/features/directive-split/README.md` → Status. Everything that refused before still refuses; the three negatives are pinned as tests. - **`scan_split_extent` gained a second parameter**, `unit_end: Option<&str>`. `None` is byte-identical to the old behaviour and is what every pre-existing caller path passes. - **`DataDecl::delay` changed type**, `Option` → `Option` where `NetDelay { expr: Expr, after_type: bool }`. Two readers existed in the whole workspace and both were one-line changes (`vlog_formatter/src/format/decl.rs`, `vlog_semantic/src/bind/decl.rs`), so the struct was preferred over a second `DataDecl` field: it makes "after_type set with no delay" unrepresentable, at no cost to consumers. - **`verify.rs` is untouched.** No normalization was added and no forgiveness widened. Both halves of this round are the *opposite* of forgiveness — the delay is printed where it was written precisely so the token order the safety net compares is unchanged, and a verbatim block is re-lexed as ordinary tokens on both sides. - **`ast::size_pins` still green, unchanged.** It pins `Expr`, `Stmt` and `StmtKind`; `NetDelay` adds a `bool` to `DataDecl`, which none of the three contains. ### Requests to other clusters - **`comment-slots`**: a net delay has no slot for the comment written immediately in front of its `#`, so such a file is refused by the safety net rather than reformatted. Pre-existing, both positions, recorded as a `#SKIP` case (see Assumptions). ## Status / TODO - [x] 38.1 rival-header detection in `parse_module`'s body loop (`parser/module.rs`), `at_rival_header` / `rival_end_kw` / `opens_unit` and the widened trigger (`parser/split.rs`), the keyword-ended extent scan. - [x] 38.1 tests: the four header spellings, both modes' trees equal, comments kept, a unit nested in a captured body, the three negatives — `parser/tests/split.rs`; four formatter cases including the real `jtag_if.sv` in full — `tests/cases/rival_headers.cases`. - [x] 38.2 `NetDelay` with its position (`ast/decl.rs`), `parse_net_delay` for either side and the both-sides error (`parser/decl.rs`), `Fmt::net_delay` printing it where it was written (`format/decl.rs`), the one consumer update (`bind/decl.rs`). - [x] 38.2 tests: both positions and their spans, both-at-once refused, only a net reads one — `parser/tests/decl.rs`; five formatter cases including the real `SimDTM.sv:38-41` — `tests/cases/net_delay_position.cases`. - [x] docs: this README; §11's two lines and §38's checkboxes ticked in `TODO.md`; the `directive-split` cross-reference. - [x] Gates (guarded): `cargo fmt -p` on the three touched crates, clippy `--all-targets` clean, `cargo test --workspace` 3 744 passed / 0 failed, `tools/corpus_check.sh` 814/820 with the same six failures, both opentitan files through `format --check`. - [ ] **Not done, deliberately:** a rival header whose two arms spell the keyword differently (`module` in one arm, `macromodule` in the other); a rival written across three or more arms where the *name* differs in one of them; any layout for the inside of a captured unit. Each is refused, not mis-parsed. - [x] QA. Verdict: PASS. See QA log (2026-09-04). ## Work log ### 2026-09-04 — dev **38.1, the rival header.** Read `parse_module`, `split.rs` and `directive-split`'s README first. The failure the plan describes is real and reproduced on trunk grammar: with both arms bracket-balanced, nothing errors until the outer unit reaches EOF, so `at_split_conditional` — which is only ever consulted from `parse_item_inner`'s `Err` arm — never sees a cursor on the `` `else ``. Detection went into `parse_module`'s body loop, before `item_or_recover`, as the plan asked. `parse_module` now records `open_conds` at its own first token and tracks the lowest nesting the body has reached (`UnitHead::floor`); the check itself, `Parser::at_rival_header`, lives in `split.rs` beside the rest of the trigger, so `module.rs` grew by twelve lines and stayed at 635. Routing: **a dedicated check beside the bracket one**, not a flag on the error. `ParseError` is public with three public fields; a fourth would be an API change touching every construction site, and a flag is a thing an unrelated error path can set. `rival_end_kw` re-derives the shape from `ItemMark::pos` and the cursor — which is how the trigger's other three conditions are already checked — and returns the unit's closing keyword, which the extent scan then needs anyway. So the one helper both widens the trigger and steers the scan. `scan_split_extent` took an `Option<&str>` closer. With `None` it is the old function byte for byte. With `Some`, it ends at the matching closing keyword (past an `endinterface : name` label) instead of at a `;`, counting units of the same kind so a module nested in the captured body cannot end it early — pinned by `a_unit_nested_in_a_captured_body_does_not_end_the_scan_early`. The three negatives the plan named are each a test, and each is refused by a *different* condition: a region opened inside the body fails condition 3 (or 2, when nothing was open around the unit at all); a different name after the `` `else `` fails condition 5; a region closed before the header fails condition 2. A fourth shape — a body that closes the header's region and opens another, which leaves the *count* equal — is what `floor` is for, and is the second half of `a_region_closed_before_the_header_leaves_the_else_stray`. The real file: `hw/dv/sv/jtag_agent/jtag_if.sv` parses, formats, is idempotent, keeps all 34 of its comments and comes back at the same 162 lines. Its one change is the verbatim block's dedent (the unit was written two spaces in). It is in `rival_headers.cases` in full, input and output, so the harness proves the idempotency and the byte-identity of the body on the actual bytes rather than on a paraphrase. One deviation worth naming: the comment written between the `` `ifdef `` and the header (`// jtag interface with default 24MHz tck for GLS`) is **not** inside the verbatim block — the capture starts at the item's first token, so it is the item's own leading comment, exactly as in every other split. It is printed, not dropped; the test asserts where it lands. **38.2, the net delay.** `NetDelay { expr, after_type }` rather than two `DataDecl` fields: with only two readers in the workspace, both one-line either way, the struct wins because it cannot represent "after_type set with no delay". The parser reads the delay through one helper called twice, once on each side of `parse_opt_data_type`, and `(Some, Some)` is an error naming the rule. The formatter's `Fmt::net_delay` prints the delay only on the side it was written on; nothing is normalised, so both spellings round-trip byte for byte and `verify.rs` sees the token order it was given. `SimDTM.sv` now parses; its diff is ordinary layout (the DPI header, the port list, an `else begin`), and the four `#0.1` wire lines come back untouched. `ast::size_pins` is unchanged and green: it pins `Expr`, `Stmt` and `StmtKind`, none of which holds a `DataDecl`. **Found, not fixed:** a comment written directly in front of a delay's `#` has no slot, so the file is refused by the safety net. It behaves identically in the *pre-existing* before-the-type position, so this is not a regression of this round; recorded as a `#SKIP` case and as a handshake request to `comment-slots`. **Files touched outside the plan's expected set:** `docs/features/directive-split/README.md` (one Status bullet, the cross-reference §38 asked for) and this README. Nothing else. ## QA log ### 2026-09-04 — QA Read `TODO.md` §38 and this README (Goal/Assumptions/Handshakes/Work log) in full, then the diffs of every touched file and both new `.cases` files. Built `target/release/lucisv` (release) from the dev's tree; the 0.41.0 baseline binary was already cached at `~/.cache/lucisv-baselines/`, so no scratch worktree was needed. **38.1, rival headers.** Traced `at_rival_header` / `rival_end_kw` / `scan_split_extent` by hand against the token stream: the extent scan's else-if chain disables the `;` terminator whenever `unit_end` is `Some` (confirmed by reading the branch order), `opens_unit` is keyed to the failed unit's own closing keyword so a nested unit of a *different* kind never touches the counter, and a same-kind-but-different-closer nested unit (`interface class … endclass`) leaves the counter stuck above zero and makes the scan give up — the parse error stands, as documented. Attacked with `target/release/lucisv format --stdout` (a Rust-level strict/tolerant-parity and comment-preservation pass was already covered by the dev's own `parser/tests/split.rs` additions, which I re-ran rather than duplicating): - Header spellings: `interface`, `module`, `program`; with and without `#(...)`; `()`, a real port list, and no port list; three arms (`ifdef`/`elsif`/`else`, all three rival); a comment directly before the rival header in the `else` arm; the region's own `` `endif `` written after the body's first item; rival arms with *different* `#(...)` lengths; a `module` nested inside a captured `interface` body (does not end the scan early); an `end : label` inside the body; `endinterface : jtag_if`. All parse, format unchanged (0 diff from input), and are idempotent. - The three plan negatives, plus the "region closed and a new one opened at the same count" fourth shape the dev's `floor` field targets — all four stay `expected end (found "")` parse errors, never a Verbatim. - Termination: an unterminated rival (no `endinterface` at all) and a rival whose `` `endif `` is the last token in the file both surface the original `rival header for … in a conditional region` parse error (the extent scan finds no closer, so it returns `None` and the original error stands) — no corruption, no panic, no silent accept. - A rival shape nested inside `generate … if (1) begin … end … endgenerate`: parses, is idempotent, and reindents only the verbatim block's own base to the surrounding column (relative layout preserved) — an odd but non-corrupting result; not a shape the plan named, recorded here as a curiosity rather than a finding since nothing breaks. - Three additional attempts at over-widening `at_split_conditional`'s fourth condition, per the QA brief: (1) a real syntax error inside the body, unrelated to any header, immediately followed by an `else`/rival-shaped arm; (2) the header parses fully and the *next* declaration errors right before a rival-shaped `else`; (3) a rival-shaped arm one nesting level *outside* the item that actually failed (nested units). All three stay ordinary parse errors — `rival_end_kw` reads `mark.pos`, the position of the item that actually failed, and returns `None` whenever that token is not the unit's own keyword+name, so none of the three ever reaches the split. The trigger does not over-fire. - "Not done, deliberately" claims verified directly: a keyword mismatch across arms (`macromodule` vs `module`) and a three-arm rival with one wrong name both stay the pre-existing `expected endmodule (found )` error, not a mis-parse. - The real file (`hw/dv/sv/jtag_agent/jtag_if.sv`, read via `--stdout` only): idempotent; 162 lines in and out; all 34 `//` comments present, 0 `/*` comments in either (matches); the only diff from the source is the verbatim block's dedent, confirmed with `diff` — every other line byte-identical. Matches the dev's account exactly. - `rival_headers.cases`: read start to finish, including the copied `jtag_if.sv` case — its input half diffs clean against the read-only opentitan file. **38.2, net delay.** Attacked before/after positions for `wire`, `tri`, `wand`, `supply0`, and a `logic`-typed net (`wire logic #2 x;`); packed dims; `signed`; delay forms `#5`, `#(1:2:3)`, `#0.1`, `#1ns`; both positions at once (`a net delay is written before or after the type, not both` — matches the plan's message); a delay on `reg`/`logic` variable declarations (ordinary `expected identifier (found "#")` syntax errors, exactly the pre-§38.2 behavior — not net declarations, so `parse_net_delay`'s `is_net` gate correctly refuses). `wire vectored [3:0] x;` (no delay) also errors on both the new binary and the 0.41.0 baseline identically — a pre-existing, unrelated gap (`vectored` net-decl qualifier is not parsed at all), not a regression of this round. Every working shape is idempotent (checked `format(format(x)) == format(x)` on seven distinct shapes). Confirmed the `#SKIP` case (`wire /* c */ #5 x;`) is genuinely pre-existing by running `~/.cache/lucisv-baselines/lucisv-0.41.0 format --stdout` on the isolated before-type shape: identical `verification failed: token stream diverges …` error, same column, on the baseline that predates this round entirely. Ran the same probe on the new after-type shape and on the exact two lines in the `.cases` `#SKIP` block — same failure mode both times, confirming the struct's `after_type` field inherits the gap rather than introducing it. The other two round-tripping cases in `net_delay_position.cases` (an attribute before the declaration, a comment after the delay) were run directly and match their expected output byte for byte, including the forced line break the comment causes. Semantic consumer: added a temporary `#[test]` in `crates/vlog_semantic/tests/semantics.rs` (`qa_scratch_a_delayed_net_still_resolves`, removed after use — final `git diff` on that file is empty) declaring `wire [31:0] #0.1 delayed_net = other;` and asserting `definition_of` on a later use resolves back to the `Net` symbol. Passed. `bind_data_decl`'s one-line change (`d.delay.as_ref().map(|n| &n.expr)`) is correct. **Byte-identity.** Corpus (820 files, `find corpus -name '*.sv' -o -name '*.v'`): compared `format --stdout` output and exit code between `target/release/lucisv` and the 0.41.0 baseline over every file — **0 differences** (neither skip file is in the corpus, as the dev's README says). Opentitan sweep over `hw/ip`, `hw/top_earlgrey/ip`, `hw/top_darjeeling/ip`, `hw/dv`, `hw/vendor` (2 554 `.sv`/`.v`/`.svh`/`.vh` files) comparing `format --check` exit codes between the two binaries: **exactly** `hw/dv/sv/jtag_agent/jtag_if.sv` and `hw/vendor/pulp_riscv_dbg/tb/unused/SimDTM.sv` changed, both from exit 2 (parse error) to exit 1 (would-reformat) — no other file in the sweep differs. `git -C /Users/guoliangchen/repo/opentitan status --porcelain` after every read-only invocation shows only the three files the task's baseline convention already allows (`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`), none of which this session touched. **Gates (guarded).** - `cargo clippy --all-targets`: clean. - `tools/guard.sh -- cargo test --workspace`: **3 744 passed / 0 failed** (36 ignored, all pre-existing `#[ignore]` measurement tests) — matches the dev's claimed count exactly. - `tools/guard.sh -- tools/corpus_check.sh`: **814/820** parsed & formattable, same six pre-existing failures (`parse-error` count 6, `verification-error` 0, `crash` 0). No HIGH or MEDIUM findings. One LOW/informational note (the `generate` nesting shape above) recorded for the trail, not requiring rework — the result is correct and non-corrupting, just an untested corner the plan didn't name. **Verdict: PASS.** ## Review **2026-09-04 — lead.** Accepted; ships in 0.42.0 with §39. 38.1 does what the §11 skip asked and no more: the rival is detected where it can be detected (a continuing directive at the unit's own entry level, followed by the same keyword and the same name), the error is routed into the split that already exists, and the capture runs to the unit's real closer counting nested units of the same kind. The dev's deviation — a dedicated check beside the bracket one rather than a flag on the public `ParseError` — is the right call for the reason given, and QA's three attempts to make the widened trigger over-fire all stayed ordinary errors. The body of a split unit is verbatim, which is the standing directive-split trade. 38.2 is a positional field with no normalisation, so `verify.rs` is untouched and the token order is preserved on both spellings; the comment-before-`#` gap is pre-existing (QA confirmed against 0.41.0) and stays a `#SKIP` with a handshake to comment-slots. Byte-identity: 0 of 820 corpus files differ from 0.41.0, and over 2 554 opentitan files exactly the two named files change outcome, both from parse error to formattable. QA's LOW (a rival nested in a generate `if` arm also recovers) is fine as it is.