From d5abf815631429c28e468163ae721ca93cf2a68a Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Fri, 4 Sep 2026 23:06:37 -0500 Subject: [PATCH] =?UTF-8?q?The=20two=20=C2=A711=20parser=20skips:=20rival?= =?UTF-8?q?=20unit=20headers=20across=20an=20ifdef/else=20split=20as=20one?= =?UTF-8?q?=20verbatim=20unit,=20a=20net=20delay=20accepted=20after=20the?= =?UTF-8?q?=20type?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TODO §38 (docs/features/parser-skips). Closes the jtag_if.sv and SimDTM.sv skips from the §11 sweep. 38.1 `Parser::at_rival_header`: in a module/interface/program body, a continuing directive at the unit's own entry level followed by the same keyword and name is a header written twice across the arms, not a nested unit. The error routes into the existing conditional split (`at_split_conditional` now fires on a rival as well as an open bracket; `scan_split_extent` runs to the unit's real closer, counting nested units of the same kind), so the whole unit is one Verbatim item in both modes. jtag_if.sv now formats (body verbatim, the standing directive-split trade). 38.2 `DataDecl::delay: Option`: a net delay is accepted before or after the type (IEEE 1800 §6.7 puts it after), never both, and printed where it was written. SimDTM.sv now formats; its four `#0.1` lines come back byte-identical. Byte-identity vs 0.41.0: 0 of 820 corpus files differ; over 2 554 opentitan files exactly the two named files change outcome. Co-Authored-By: Claude Fable 5.1 --- TODO.md | 278 +++++++++++- crates/vlog_formatter/src/format/decl.rs | 21 +- .../tests/cases/net_delay_position.cases | 83 ++++ .../tests/cases/rival_headers.cases | 386 ++++++++++++++++ crates/vlog_parser/src/ast/decl.rs | 22 +- crates/vlog_parser/src/parser/decl.rs | 30 +- crates/vlog_parser/src/parser/module.rs | 12 + crates/vlog_parser/src/parser/split.rs | 129 +++++- crates/vlog_parser/src/parser/tests/decl.rs | 55 +++ crates/vlog_parser/src/parser/tests/split.rs | 155 +++++++ crates/vlog_semantic/src/bind/decl.rs | 2 +- docs/features/directive-split/README.md | 9 + docs/features/parser-skips/README.md | 413 ++++++++++++++++++ 13 files changed, 1557 insertions(+), 38 deletions(-) create mode 100644 crates/vlog_formatter/tests/cases/net_delay_position.cases create mode 100644 crates/vlog_formatter/tests/cases/rival_headers.cases create mode 100644 docs/features/parser-skips/README.md diff --git a/TODO.md b/TODO.md index 6ebfcf3..b512d06 100644 --- a/TODO.md +++ b/TODO.md @@ -43,13 +43,14 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both. `vlog_parser::parser` that returns a parse error past a documented limit (ruff does the same). Do the same in the formatter's recursive walk. -- [ ] **Atomic in-place writes.** QA find during cli-filelist (2026-08-25, +- [x] **Atomic in-place writes.** QA find during cli-filelist (2026-08-25, pre-existing): `process_file` and the `--fix` path write with plain `fs::write` (open/truncate/write) while `cache.rs` next door already does tempfile+rename. Two workers reaching one inode through two spellings (symlink alias — lexical dedup cannot see it) could tear a file. Fix: tempfile+rename in both writers; optionally canonicalized dedup keys as a second line of defense. + **Delivered by §36.3** (0.40.0): `lucisv_core::atomic::write_atomic` in all three writers. ## 2. Formatter features @@ -246,10 +247,11 @@ Verible's rule ergonomics (waivers, configurable rules). and an "every registered rule appears" test. Renderable today via `cargo run -p vlog_linter --example rules_markdown`; a `lucisv check --rules-doc` flag is filed as a handshake for `crates/lucisv`. -- [ ] Seed rules (all syntactic, all from Verible's default set): +- [x] Seed rules (all syntactic, all from Verible's default set): no-tabs, no-trailing-spaces, explicit-parameter-storage-type, case-missing-default, always-ff-non-blocking / always-comb-blocking, forbid `wire`-reg mixups in SV files, module-filename match. + **All delivered** — every rule named here exists (`explicit-parameter-storage-type`, `case-missing-default`, `always-ff-non-blocking`, `always-comb-blocking`, `module-filename`, the two above); 73 rules as of 0.39.0. - [x] `no-tabs`, `no-trailing-whitespace`, `explicit-parameter-storage-type`, `case-missing-default`, `always-ff-non-blocking`, `always-comb-blocking`, `module-filename` — @@ -278,14 +280,16 @@ Adapt each: Port cases directly from `formatter_test.cc` where our supported-syntax overlaps — it encodes years of accumulated edge cases (translate expected output to our style: 2-space indent matches, wrap style differs). -- [ ] **[V] Run equivalence + convergence on *every* test case**, not just +- [x] **[V] Run equivalence + convergence on *every* test case**, not just snapshots — once §1's `verify_equivalence` exists, assert it in the fixture harness too, so every new case buys three checks for free. -- [ ] **[V] Component-level tests.** Verible tests the pipeline stages + **Delivered:** `format_source` runs `verify_equivalence` and `verify_convergence` on every output (`format/mod.rs`), so every fixture, snapshot, corpus file and fuzz case buys all three checks. +- [x] **[V] Component-level tests.** Verible tests the pipeline stages separately (`token-annotator_test.cc`, `tree-unwrapper_test.cc`). Ours: unit tests for `lexer.rs` trivia attachment (comment → leading/trailing decisions, blank-line counting), `parser.rs` per-construct parse tests, and `printer.rs` group-breaking behavior on synthetic docs. + **Delivered incrementally:** `lexer.rs` carries 37 unit tests on trivia and tokens, `parser/tests/` is one module per construct, `printer.rs` has its own group-breaking tests. - [x] **[V] Lint test harness with inline violation markers.** Port the `LintTestCase` / `RunLintTestCases` idea: test cases embed expected findings positionally in the source (Verible splices `ExpectedTokenInfo` @@ -309,8 +313,9 @@ Adapt each: (inputs the formatter refuses must say `#tolerant`, enforced in both directions like `#SKIP`; that population is empty today — all 5 fix cases for the 2 fixable rules run the full cross-tool check). -- [ ] **[V] Error-case tests.** Table of inputs that must *fail* to parse +- [x] **[V] Error-case tests.** Table of inputs that must *fail* to parse with the expected error position — locks in the failsafe path. + **Delivered** by error-recovery / header-recovery: the `BROKEN` table in `vlog_parser/tests/error_recovery.rs` plus `a_diagnostics_span_is_the_token_its_line_col_names`. - [x] **[R] Real-world corpus check (ruff's "ecosystem check").** ruff CI runs against big OSS codebases and diffs results between commits. Do the same with permissively-licensed RTL: e.g. lowRISC Ibex, OpenTitan, @@ -392,12 +397,14 @@ Adapt each: lives in a file lucisv deliberately does not read. `directive-split` (14 files) is still the top blocker, and every remaining failure is in a deliberately-unsupported category. -- [ ] **[R] Fuzzing.** ruff fuzzes its parser. `cargo-fuzz` targets: +- [x] **[R] Fuzzing.** ruff fuzzes its parser. `cargo-fuzz` targets: (a) parser must never panic on arbitrary bytes, (b) for inputs that parse, format must satisfy equivalence + convergence. -- [ ] **[R] Consider `insta`** for the snapshot harness (review workflow + **Delivered in-tree, without `cargo-fuzz`** (nightly + a dependency): the guarded truncation and single-character-deletion fuzzers in `vlog_parser/tests/error_recovery.rs` (a), and the formatter gap fuzzers from comment-slots (b), all run under `tools/guard.sh`. +- [x] **[R] Consider `insta`** for the snapshot harness (review workflow `cargo insta review` beats `UPDATE_SNAPSHOTS=1`), keeping the idempotency loop from `fixtures.rs`. + **Ruled 2026-09-04:** no. The `UPDATE_SNAPSHOTS=1` loop plus the idempotency suite has served 40 releases; a dependency for a review UI is not worth its weight. ## 6. LSP: full editor support (a first-class goal, not a maybe) @@ -560,7 +567,7 @@ later: `exit` over hand-rolled framing. Manual install steps only — CI packaging and Marketplace publishing are out of scope, and `publisher` is a placeholder. `docs/features/editor-packaging/README.md`. -- [ ] **Salsa-style incrementality — defer.** ruff's `ruff_db` uses salsa; +- [x] **Salsa-style incrementality — defer.** ruff's `ruff_db` uses salsa; don't take that dependency until hover/definition across files exists. Per-file recompute is fine at Verilog file sizes. **Partly answered without salsa, 2026-08-27** @@ -611,6 +618,7 @@ later: Answers given mid-scan read the index as of that moment, and only the startup scan gives them: a request queued behind a message that asked for a rescan waits for that rescan, which is the order contract the loop always kept. + **Ruled 2026-09-04:** not needed. `incremental-index` (per-file `update_file`, batch publish) and the persistent facts store answer every cross-file question without salsa. - [x] **Release prep.** `LICENSE` (MIT), `CHANGELOG.md` (v0.2.0), version bumped to 0.2.0 across the workspace and the extension, `tools/release.sh` (release binaries + `.vsix` + `SHA256SUMS` into a gitignored `dist/`) and @@ -1220,16 +1228,18 @@ Files: `crates/lucisv_server/src/{candidates.rs,state.rs,server.rs,perf.rs}`, own, which is quadratic in the batch — **403 ms of the 935 ms** on opentitan's `hw/ip`. Counted per batch and merged once: 43 ms. Warm **935 / 881 → 555 / 564 ms**, cold **1 529 → 1 175 ms**. -- [ ] **Still slow, filed:** what is left of that jump is real work over +- [x] **Still slow, filed:** what is left of that jump is real work over 1 683 genuinely new files — 325 ms re-lexing them for the completion word table (the persistent store holds a file's facts but not its words), ~100 ms walking and reading them, ~80 ms hashing and decoding records. Storing the word list beside the facts is the next lever and is `index-persistence`'s call: it is a `FACTS_FORMAT` change. -- [ ] **Not done, deliberately:** a widen still does not interleave, so + **Delivered by `FACTS_FORMAT` 13** (semantic-lints-on, 2026-09-02): the word census is a fact, so a cached hit brings its words and a scan never re-lexes for the table (`state.rs`, "Read off the record"). +- [x] **Not done, deliberately:** a widen still does not interleave, so this is a bar the user watches once per session per big widen. The coalescing rule is unchanged. + **Ruled 2026-09-04:** stays as is; a widen is one bar per session per big widen. ### Deferred, filed @@ -1349,8 +1359,9 @@ README.md, TODO.md §11 Lane B lines) swallowed by the condition's first call. Out of Lane B's file set; filed as a handshake in `docs/features/formatter-bug-fixes/ README.md`. -- [ ] Owner/lead: the one-line parser fix above (Lane A's file), which +- [x] Owner/lead: the one-line parser fix above (Lane A's file), which closes the last of the 12. + **Delivered 2026-08-29** by directive-in-statements (`take_before_open` request, formatter-bug-fixes README). ### Serial, after Lane A merges (parser.rs frees up) @@ -1441,23 +1452,35 @@ into an opaque blob are now parsed (see below). Corpus byte-identical at true at 256, false at 1024 — while re-verifying the phase argument that keeps the two budgets additive. `docs/features/recursion-limit/README.md` round 4. -- [ ] **Skipped, `jtag_if.sv`**: its clocking blocker is fixed; a +- [x] **Skipped, `jtag_if.sv`**: its clocking blocker is fixed; a **pre-existing** one sits behind it. Two rival, bracket-*balanced* interface headers in an `` `ifdef ``/`` `else `` region, which `at_split_conditional` does not fire on (it requires an open bracket), so the parser nests them. Handshake request to a future `directive-split` round; reproduced on trunk grammar alone. -- [ ] **Skipped, `SimDTM.sv`**: a net delay written *after* the type + **Delivered by §38.1** (2026-09-04): `parse_module`'s body loop detects + the rival, `at_split_conditional`'s fourth condition is now "bracket + open **or** rival header" and `scan_split_extent` runs to the unit's own + closing keyword, so the whole unit is one `ItemKind::Verbatim`. The file + parses and formats; its body is not laid out — the standing + `directive-split` trade. `docs/features/parser-skips/README.md`. +- [x] **Skipped, `SimDTM.sv`**: a net delay written *after* the type (`wire [31:0] #0.1 x = y;`), which is where the LRM puts it — lucisv parses it only before. One `DataDecl` field has one print position, so accepting both spellings needs a positional field or the safety net rightly refuses the reordered tokens. One vendor file in `tb/unused/`. -- [ ] **Skipped, `kmac_reduced_tb.sv`**: a trailing comma in a *named* + **Delivered by §38.2** (2026-09-04): the positional field is + `NetDelay { expr, after_type }`; the parser accepts either position and + never both, and the formatter prints it where it was written, so no + token moves. `docs/features/parser-skips/README.md`. +- [x] **Skipped, `kmac_reduced_tb.sv`**: a trailing comma in a *named* parameter override list. Not legal SystemVerilog; rejecting it is correct. -- [ ] **Recommended instead of grammar work**, for the sweep's non-SystemVerilog + **Closed 2026-09-04:** rejecting it is correct; nothing to do. +- [x] **Recommended instead of grammar work**, for the sweep's non-SystemVerilog files: exclude patterns `**/*.tpl.sv`, `**/vendor/google_riscv-dv/**`, `**/pulp_riscv_dbg/tb/unused/**`. + **Ruled 2026-09-04:** not excluded; the six failures (all in the three trees named here) stay in the 814/820 count as the honest number, and are listed in the release gates each round. ## 12. Inline instantiation wave (2026-08-30) — owner request @@ -2191,13 +2214,14 @@ docs/features/escaped-identifiers/README.md (new), TODO.md §19. comment, so no corpus file reaches the new branch. Same for the read-only opentitan sweep (13 failures, all parse/lex, zero verification errors). -- [ ] **Follow-up for a parser lane**: `Parser::parse_scoped_name` +- [x] **Follow-up for a parser lane**: `Parser::parse_scoped_name` joins `pkg::name` into one `String`, losing the boundary, so a `\my-pkg ::\state-t` type (or instantiated module, or `bind` target) is still rejected by the net — an error, never a corruption. Keep the segments. Recorded as the file's one `#SKIP` case and as `an_escaped_name_in_a_scoped_type_is_rejected_rather_than_corrupted`. + **Delivered by escaped-identifiers** (2026-09-02): `push_scope_segment` keeps the terminating space, the `#SKIP` is gone, the verification pin is inverted (README, "How it was answered"). - [x] **QA (2026-09-02)**: gates clean (fmt, clippy 0, tests 2819/0 after one QA-added attack pair, corpus 813/820 unchanged); scope matches the file list above exactly, `verify.rs` confirmed absent from the @@ -4121,3 +4145,225 @@ byte-identity vs 0.40.0, opentitan read-only sweep, 0.41.0. equality over the encoding shapes; opentitan timing re-derived — PASS, no findings above LOW; offer ~4.5 ms vs eager ~77 ms over the wire at the 128-file fan-out + + +## 38. The two §11 parser skips (planned 2026-09-04) — rival headers in a conditional region, a net delay after the type + +One lane in the main tree, dev Opus 5 then QA Sonnet 5, §36's protocol. +Feature README: `docs/features/parser-skips/README.md`. Ships as 0.42.0 +together with §39. + +**Expected touch set:** `crates/vlog_parser/src/parser/{module.rs,split.rs, +decl.rs}`, `crates/vlog_parser/src/ast/decl.rs`, +`crates/vlog_formatter/src/format/decl.rs`, `crates/vlog_formatter/tests/cases/*` +(new cases), `crates/vlog_parser/src/parser/tests/{module.rs,decl.rs,split.rs}`, +`crates/vlog_parser/tests/error_recovery.rs`, the two §11 lines (1453, 1459), +this section. + +### 38.1 Two rival, bracket-balanced module/interface headers in an `ifdef`/`else` region (`jtag_if.sv`) + +The real file: `/Users/guoliangchen/repo/opentitan/hw/dv/sv/jtag_agent/jtag_if.sv` +(read-only; copy it into a test case). Shape: +``` +`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 +``` +Today the first header parses in full, the `` `else `` is a directive item +of its body, the second `interface jtag_if` becomes a *nested* interface, +and the outer one reaches EOF without its `endinterface`: "163:1: expected +`endinterface`". `at_split_conditional` (split.rs) never fires because +nothing errors until EOF and the headers are bracket-balanced. + +- **Detect the rival in `parse_module`'s body loop**, before the item is + parsed: the cursor is on an `` `else ``/`` `elsif `` that continues a + region opened *before this item's own first token* (`open_conds` at the + item's mark is above zero and no region has been opened since), and the + tokens after it are the same keyword (`module`/`interface`/`program`) and + the same name as the header just parsed. That is a header written twice + across the arms, not a nested unit. Raise a `ParseError` there ("rival + header for `jtag_if` in a conditional region"). +- **Route it into the existing split.** `split_conditional_item` already + turns an item that errored inside a region into `ItemKind::Verbatim` + over the whole item (`capture_split`) — extend `at_split_conditional`'s + trigger so this error qualifies with the brackets balanced (a flag on + the error, or a dedicated check beside the bracket one; say which and + why), and make sure `scan_split_extent` runs to the unit's real closer + (`endinterface`) so the whole unit is the verbatim item, the way a + bracket-unbalanced header is today. Strict and tolerant modes get the + same tree. The formatter prints a `Verbatim` item byte-for-byte, so the + file formats (its body is not formatted; that is the standing trade for + a split header, recorded in the directive-split README — cite it). +- Not a rival: a second `module x` written in the `` `else `` arm of a + region opened *inside* the body (that is two nested units, illegal, and + stays the error it is); a different name after the `` `else ``; a region + closed before the item began. Pin each as a negative. +- Tests: the jtag_if shape (`module` and `interface` spellings, with and + without `#(...)`, with `()` and with a real port list); the three + negatives; the real file as a cases entry (idempotent, comments kept, + the body verbatim); `tolerant_parse_equals_strict_parse_on_valid_sources` + still green; the fuzzers. + +### 38.2 A net delay written after the type (`SimDTM.sv`) + +`wire [31:0] #0.1 x = y;` is where IEEE 1800 §6.7 puts a net delay +(`net_type [drive_strength] [vectored|scalared] data_type_or_implicit +[delay3] list_of_net_decl_assignments`); lucisv parses the delay only +between the net keyword and the type. Real file: +`/Users/guoliangchen/repo/opentitan/hw/vendor/pulp_riscv_dbg/tb/unused/SimDTM.sv` +lines 38–40 (read-only). + +- `DataDecl` gains the position: replace `delay: Option` with + `delay: Option` where `NetDelay { expr: Expr, after_type: bool }` + (or two fields — pick the one that keeps every existing consumer a + one-line change, and say). The parser accepts the delay in either + position, never both (both is an error), and records which. The + formatter prints it where it was written: `wire #5 w;` stays, `wire + [31:0] #0.1 x = y;` stays. No normalisation — the safety net compares + token order, and the LRM position is the one the vendor file uses. +- Consumers: every `d.delay` reader across the workspace (`grep -rn + '\.delay' crates`), each a mechanical change; `ast::size_pins` + unchanged or explained. +- Tests: both positions round-trip byte-identical; both written is a + parse error; a delay after a *packed* dimension and after a plain + `logic`-typed net; the SimDTM lines as a cases entry; snapshot suite + green; the corpus check unchanged. + +### Gates (dev, guarded) + +`cargo fmt -p` per touched crate; clippy clean; `tools/guard.sh -- cargo +test --workspace`; `tools/guard.sh -- tools/corpus_check.sh` — **814/820 +still**, since neither file is in the corpus (say so); `lucisv format +--check` on the two opentitan files now parses both (read-only; report the +outcome — `jtag_if.sv` should now be "would reformat" or "unchanged", not +an error). Lead at review: byte-identity vs 0.41.0 over the corpus and the +opentitan sweep — the *only* files whose result may change are these two; +any other difference is a REWORK. + +- [x] 38.1 the rival-header detection, the split routing, tests — the + routing is a **dedicated check** (`rival_end_kw`) beside the bracket + one, not a flag on `ParseError`; `scan_split_extent` takes the unit's + closing keyword +- [x] 38.2 `NetDelay` position, both spellings, tests — `NetDelay { expr, + after_type }` as a struct, since both consumers were one-line either + way and the struct cannot represent a position without a delay +- [x] docs: feature README; §11 lines ticked; directive-split README + cross-reference +- [x] Gates (guarded) — workspace 3 744 passed / 0 failed; corpus 814/820, + the same six; both opentitan files "would reformat" (neither is a + parse error any more), opentitan tree untouched +- [x] QA: rival shapes and the three negatives attacked; the two real + files through `--check` and `--stdout` (read-only); delay positions + attacked with comments and attributes around them; opentitan sweep + re-derived with exactly two files changing. Verdict PASS — see + `docs/features/parser-skips/README.md` QA log (2026-09-04). + +## 39. External waiver files (planned 2026-09-04) — §4's last waiver item + +One lane after §38 merges, same protocol. Feature README: +`docs/features/waiver-files/README.md`. Ships as 0.42.0 with §38. + +**Decisions taken by the lead** (the "file format, discovery rule and +precedence story" §4 asked for): + +- **Format: Verible's**, so an existing `.waiver` file carries over + unchanged. One directive per line: + `waive --rule= [--line=|--line=-] [--location=]`; + `#` comments and blank lines ignored. `--rule` is required and must name + a lucisv rule (`rules_named` validates it, severity words not accepted); + `--line` is 1-based, a range inclusive; `--location` is matched the way + `--exclude` patterns are (`lucisv_core`'s matcher: a pattern with `/` + matches a path suffix, otherwise the file name) — a regex is not accepted + and a `--location` that looks like one (`.*`, `\.`) is an error naming + the difference. No `--location` means every file; no `--line` means the + whole file. +- **Discovery:** `[lint] waivers = ["path", …]` in `lucisv.toml`, paths + relative to that toml; `lucisv check --waiver-file ` (repeatable, + relative to the cwd) adds to them; the editor setting + `lucisv.lint.waivers` (a list, relative to the workspace root) adds to + them for the server. A file that does not exist or has a bad line is a + configuration error, reported as `:: message` exactly like a + bad `[lint.]` entry (CLI exit 2; the server logs it through + `notification.rs` and drops that line, never the file). +- **Precedence: union.** A violation is suppressed when an inline waiver + *or* an external one covers it; nothing overrides anything. Unused + external waivers are reported under the existing `unused-waiver` rule + with the *waiver file* as the path and the directive's line — by the + CLI only, after the whole run (a `--location` may match a file not yet + seen); the server does not report unused external waivers (documented: + it never sees a whole run). An external waiver whose `--location` names + no file in the run is unused. + +**Expected touch set:** `crates/vlog_linter/src/waiver_file.rs` (new: parse ++ match; `waiver.rs` stays the inline story and is near 250 lines), +`crates/vlog_linter/src/lib.rs` (apply both), `crates/lucisv_core/src/config.rs` +(`[lint] waivers`), `crates/lucisv/src/{args.rs,lint.rs}`, +`crates/lucisv_server/src/{lint.rs,settings.rs}` + `server/notification.rs`, +`editors/vscode/package.json` (the setting, plus `vlog_linter::vscode`'s +drift test if it generates lint settings), `README.md` and +`docs/site/src/content/docs/reference/` (a "Waivers" section), the §4 +lines (221, 229), this section. + +- Tests: parse every directive shape and every error (unknown rule, + missing `--rule`, bad line range, regex-looking location); matching by + file name and by path suffix; line and range; union with an inline + waiver on the same violation (one suppression, neither reported unused); + unused external waiver reported at the waiver file's line; server: the + setting adds a file, a bad line is logged once and the rest applies; an + e2e case over the wire; CLI: `--waiver-file` twice, toml + CLI combined, + exit codes. + +- [ ] 39.1 `waiver_file.rs` + application in `lib.rs` +- [ ] 39.2 discovery: toml, CLI flag, editor setting +- [ ] 39.3 unused reporting (CLI), errors (both front ends) +- [ ] docs: feature README; README/site "Waivers" section; §4 lines ticked +- [ ] Gates (guarded): fmt/clippy/workspace tests; corpus unchanged; smoke +- [ ] QA: every directive shape and error attacked on both front ends; + precedence attacked; an opentitan run with a waiver file that waives + one real finding, read-only, counts re-derived + +## 40. Performance take 3 on opentitan (owner request 2026-09-04) — after §38 and §39 merge + +Read-only measurement, no code changes unless a regression is found (then +it is filed, not fixed in this lane). Output: `docs/performance_take3.md`, +same table shapes as `docs/performance_take2.md` so every row is a +before/after, plus a `docs/perf/README.md` entry. Tree: +`/Users/guoliangchen/repo/opentitan` (never written; the three +pre-existing modified files stay as they are). Every run under +`tools/guard.sh`. + +- **Server, the take-2 request table** (§2 of take 2): startup and scan + per scope config and cache state (cold / warm), the `didOpen` widen at + the default scope, `codeAction` at the five cursors of §6a (now the + lazy offer *and* a `codeAction/resolve` at each), `prepareRename` / + `rename`, `completion` at the worst prefix, `definition` (index-only + path), `hover`, `inlayHint` (workspace scope and default scope, with + §37.2's ruling restated), `references`, `documentSymbol`, + `workspaceSymbol`, `semanticTokens/full`, diagnostics publish. Driven + over the wire against `target/release/lucisv-server` at 0.42.0 and, + for the rows that exist there, the 0.39.0 baseline + (`~/.cache/lucisv-baselines/` holds CLI binaries only — build the + 0.39.0 server from the tag in a scratch worktree under the scratchpad, + removed after). +- **CLI sweeps** over `hw/ip`, `hw/top_earlgrey/ip`, `hw/top_darjeeling/ip`, + `hw/dv`, `hw/vendor`: `format --check` (cold cache and warm), `check` + (all rules on; default rules), wall time and peak RSS (`/usr/bin/time + -l`), 0.42.0 vs 0.39.0 vs 0.41.0; the failure counts per tree and the + list of files whose outcome changed since 0.39.0 (expected: exactly + jtag_if.sv and SimDTM.sv from §38). +- **Method** as take 2 §9: three tries per row, first try and repeat + range both reported, machine state noted; no server-side + instrumentation added. +- Findings: any row slower than take 2 by more than noise is a filed + item with a reproduction; anything faster is credited to the section + that did it. + +- [ ] server table re-measured, 0.42.0 vs take 2 vs 0.39.0 +- [ ] CLI sweeps, three binaries, RSS included +- [ ] `docs/performance_take3.md` + perf README entry +- [ ] opentitan status unchanged after every run diff --git a/crates/vlog_formatter/src/format/decl.rs b/crates/vlog_formatter/src/format/decl.rs index 4fe756e..0ec15a9 100644 --- a/crates/vlog_formatter/src/format/decl.rs +++ b/crates/vlog_formatter/src/format/decl.rs @@ -298,20 +298,31 @@ impl<'a> Fmt<'a> { if let Some(net) = &d.net { docs.push(text(format!("{net} "))); } - if let Some(delay) = &d.delay { - docs.push(text("#")); - docs.push(self.expr(delay)); - docs.push(text(" ")); - } + self.net_delay(d, false, &mut docs); self.qualifier_run(&d.qualifiers, &mut docs); if let Some(t) = self.data_type(&d.ty) { docs.push(t); docs.push(text(" ")); } + self.net_delay(d, true, &mut docs); docs.push(self.declarators(&d.declarators)); concat(docs) } + /// `#5 ` — the declaration's net delay and the space after it, but only + /// when it was written on the side of the data type `after_type` names. + /// IEEE 1800 §6.7 allows either side and lucisv prints it where the + /// source put it; moving it across the type would reorder tokens, which + /// `verify.rs` refuses. + fn net_delay(&self, d: &DataDecl, after_type: bool, docs: &mut Vec) { + let Some(delay) = d.delay.as_ref().filter(|n| n.after_type == after_type) else { + return; + }; + docs.push(text("#")); + docs.push(self.expr(&delay.expr)); + docs.push(text(" ")); + } + pub(super) fn port_decl(&self, d: &PortDecl) -> Doc { let mut docs = vec![text(format!("{} ", d.dir))]; if let Some(net) = &d.net { diff --git a/crates/vlog_formatter/tests/cases/net_delay_position.cases b/crates/vlog_formatter/tests/cases/net_delay_position.cases new file mode 100644 index 0000000..a12d1e0 --- /dev/null +++ b/crates/vlog_formatter/tests/cases/net_delay_position.cases @@ -0,0 +1,83 @@ +# TODO §38.2 — a net delay is printed on the side of the data type it was +# written on. IEEE 1800 §6.7 puts `delay3` after the type; the rest of the +# corpus puts it before. Neither spelling is normalised into the other. +# docs/features/parser-skips/README.md +module m; +wire #5 before_the_type; +wire [31:0] #0.1 after_the_type = y; +endmodule +---- +module m; + wire #5 before_the_type; + wire [31:0] #0.1 after_the_type = y; +endmodule +==== +# after a packed dimension, after a plain `logic`-typed net, and after a +# signing keyword — with the min:typ:max spelling of the delay itself +module m; +wire [7:0] #1 a; +wire logic #2 b; +wire signed [7:0] #(1:2:3) c; +wire #(1:2:3) signed [7:0] d; +endmodule +---- +module m; + wire [7:0] #1 a; + wire logic #2 b; + wire signed [7:0] #(1:2:3) c; + wire #(1:2:3) signed [7:0] d; +endmodule +==== +# the real lines: hw/vendor/pulp_riscv_dbg/tb/unused/SimDTM.sv:38-41 +# (opentitan, read-only there), the §11 skip this item closes +module SimDTM ( + input clk, + output [31:0] exit +); + + bit r_reset; + + wire #0.1 __debug_req_ready = debug_req_ready; + wire #0.1 __debug_resp_valid = debug_resp_valid; + wire [31:0] #0.1 __debug_resp_bits_resp = {30'b0, debug_resp_bits_resp}; + wire [31:0] #0.1 __debug_resp_bits_data = debug_resp_bits_data; + +endmodule +---- +module SimDTM (input clk, output [31:0] exit); + bit r_reset; + + wire #0.1 __debug_req_ready = debug_req_ready; + wire #0.1 __debug_resp_valid = debug_resp_valid; + wire [31:0] #0.1 __debug_resp_bits_resp = {30'b0, debug_resp_bits_resp}; + wire [31:0] #0.1 __debug_resp_bits_data = debug_resp_bits_data; +endmodule +==== +# SKIP a comment written directly in front of the `#` has no slot to be +# printed from, so `verify.rs` refuses the file rather than moving it. This +# is *pre-existing* for the before-the-type position — it behaves the same +# way with no `[7:0]` in front — and the after-the-type position inherits +# it unchanged. Recorded, not fixed: giving the delay a comment slot is a +# `comment-slots` change, not a §38 one. +module m; + wire /* c */ #5 x; + wire [7:0] /* d */ #1 z; +endmodule +---- +module m; + wire /* c */ #5 x; + wire [7:0] /* d */ #1 z; +endmodule +==== +# the other three gaps around a delay do have slots and round-trip +module m; + (* keep *) wire [3:0] #2 k = j; + wire #5 /* after */ x; +endmodule +---- +module m; + (* keep *) + wire [3:0] #2 k = j; + wire #5 /* after */ + x; +endmodule diff --git a/crates/vlog_formatter/tests/cases/rival_headers.cases b/crates/vlog_formatter/tests/cases/rival_headers.cases new file mode 100644 index 0000000..a3026b3 --- /dev/null +++ b/crates/vlog_formatter/tests/cases/rival_headers.cases @@ -0,0 +1,386 @@ +# TODO §38.1 — two rival, bracket-balanced unit headers written across the +# arms of one `ifdef region. The whole unit is one verbatim item, so it comes +# back byte for byte apart from the block's own re-indent. +# docs/features/parser-skips/README.md +`ifdef A +interface i (); +`else +interface i (); +`endif + wire tck; +endinterface + +parameter int AFTER = 1; +---- +`ifdef A +interface i (); +`else +interface i (); +`endif + wire tck; +endinterface + +parameter int AFTER = 1; +==== +# a module spelling with a real port list and a closing label +`ifdef SYNTHESIS +module m (input a, output b); +`else +module m (input a, output b); +`endif + wire x; +endmodule : m +---- +`ifdef SYNTHESIS +module m (input a, output b); +`else +module m (input a, output b); +`endif + wire x; +endmodule : m +==== +# the block's *relative* layout is what survives: the whole unit is dedented +# to the item's own indent, exactly as every other verbatim block is +`ifdef A + interface i #(parameter int P = 1) (); +`else + interface i #(parameter int P = 2) (); +`endif + wire tck; +endinterface +---- +`ifdef A +interface i #(parameter int P = 1) (); +`else +interface i #(parameter int P = 2) (); +`endif +wire tck; +endinterface +==== +# the real file: hw/dv/sv/jtag_agent/jtag_if.sv (opentitan), the §11 +# skip this item closes. Read-only there; copied here verbatim. +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// TODO(#24580): A JTAG UVM agent should configure the JTAG frequency (and not this interface) +`ifdef GATE_LEVEL + // jtag interface with default 24MHz tck for GLS + interface jtag_if #(parameter int unsigned JtagDefaultTckPeriodPs = 41_664) (); +`else + // jtag interface with default 50MHz tck for faster DV simulations + interface jtag_if #(parameter int unsigned JtagDefaultTckPeriodPs = 20_000) (); +`endif + + // interface pins + wire tck; + wire trst_n; + wire tms; + wire tdi; + wire tdo; + + // Is this interface being driven (through _drive_active and the clocking blocks), or is it just + // observing some signals from the wider simulation? + // + // The flag is defined as a wire with a weak pull-up. This ensures that a testbench that doesn't + // customise is_active will see the interface be driven actively, but allows a testbench that + // *does* want to customise the signal to pull it low. + wire is_active; + assign (weak0, weak1) is_active = 1'b1; + + // Should this interface generate a local tck signal? To enable that, set tck_en as well as + // is_active. + bit tck_en; + + // Output-enable flags for tms, tdi, tdo (which only have an effect if is_active is true). The + // default configuration enables tms and tdi, so acts as the root of the JTAG tree plus the + // "previous device in the scan chain". + bit tms_oe = 1'b1; + bit tdi_oe = 1'b1; + bit tdo_oe = 1'b0; + + logic _tck_internal, _trst_n_internal, _tms_internal, _tdi_internal, _tdo_internal; + assign tck = (is_active === 1'b1) ? _tck_internal : 'z; + assign trst_n = (is_active === 1'b1) ? _trst_n_internal : 'z; + assign tms = ((is_active === 1'b1) && tms_oe) ? _tms_internal : 'z; + assign tdi = ((is_active === 1'b1) && tdi_oe) ? _tdi_internal : 'z; + assign tdo = ((is_active === 1'b1) && tdo_oe) ? _tdo_internal : 'z; + + // Use negedge to drive jtag inputs because design also use posedge clock edge to sample. + clocking host_cb @(negedge tck); + default output #1ns; + output tms = _tms_internal; + output tdi = _tdi_internal; + input tdo; + endclocking + modport host_mp(clocking host_cb, output trst_n); + + clocking device_cb @(posedge tck); + input tms; + input tdi; + output tdo = _tdo_internal; + endclocking + modport device_mp(clocking device_cb, input trst_n); + + clocking mon_cb @(posedge tck); + input tms; + input tdi; + input tdo; + endclocking + modport mon_mp (clocking mon_cb, input trst_n); + + // Signals for local tck + int unsigned _tck_period_ps = JtagDefaultTckPeriodPs; + int unsigned _clk_hi_ps, _clk_lo_ps; + assign _clk_hi_ps = _tck_period_ps / 2; + assign _clk_lo_ps = _tck_period_ps - _clk_hi_ps; + + // Sets the TCK frequency. + function automatic void set_tck_period_ps(int unsigned value); + _tck_period_ps = value; + endfunction + + function automatic int unsigned get_tck_period_ps(); + return _tck_period_ps; + endfunction + + // Wait for one TCK cycle + // + // This waits for TCK to clear and then be asserted (so is waiting for the next posedge), but + // bounds the wait by _tck_period_ps (in case the clock has stopped). + // + // Waiting for !tck, then for tck ensures that we don't get any strange races when the clock is + // enabled: no matter what the relative phase, we will definitely wait at least a half cycle. + task automatic wait_one_tck(); + fork : isolation_fork begin + fork + begin + wait(!tck); + wait(tck); + end + #(_tck_period_ps * 1ps); + join_any + disable fork; + end join + endtask + + // Wait for the given number of cycles of TCK + task automatic wait_tck(int cycles); + repeat (cycles) wait_one_tck(); + endtask + + // Start asserting a test reset through trst_n (no effect if the interface is not active) + function automatic void assert_test_reset(); + _trst_n_internal <= 1'b0; + endfunction + + // Clear any test reset asserted through trst_n (no effect if the interface is not active) + function automatic void clear_test_reset(); + _trst_n_internal <= 1'b1; + endfunction + + // Assert a test reset through trst_n (no effect if the interface is not active) + task automatic do_trst_n(int cycles = $urandom_range(5, 20)); + assert_test_reset(); + wait_tck(cycles); + clear_test_reset(); + endtask + + // Drive _tck_internal with period _tck_period_ps whenever tck_en is high. If active is true, this + // gets used to drive the tck signal. + task automatic _drive_active(); + forever begin + wait(tck_en); + fork : isolation_fork begin + fork + wait(!tck_en); + forever begin + _tck_internal = 1'b1; + #(_clk_hi_ps * 1ps); + _tck_internal = 1'b0; + #(_clk_lo_ps * 1ps); + end + join_any + disable fork; + end join + end + endtask + + initial begin + _tck_internal = 1'b1; + forever begin + wait(is_active === 1'b1); + fork : isolation_fork begin + fork + wait(is_active !== 1'b1); + _drive_active(); + join_any + disable fork; + end join + end + end + +endinterface +---- +// Copyright lowRISC contributors (OpenTitan project). +// Licensed under the Apache License, Version 2.0, see LICENSE for details. +// SPDX-License-Identifier: Apache-2.0 + +// TODO(#24580): A JTAG UVM agent should configure the JTAG frequency (and not this interface) +`ifdef GATE_LEVEL +// jtag interface with default 24MHz tck for GLS +interface jtag_if #(parameter int unsigned JtagDefaultTckPeriodPs = 41_664) (); +`else +// jtag interface with default 50MHz tck for faster DV simulations +interface jtag_if #(parameter int unsigned JtagDefaultTckPeriodPs = 20_000) (); +`endif + +// interface pins +wire tck; +wire trst_n; +wire tms; +wire tdi; +wire tdo; + +// Is this interface being driven (through _drive_active and the clocking blocks), or is it just +// observing some signals from the wider simulation? +// +// The flag is defined as a wire with a weak pull-up. This ensures that a testbench that doesn't +// customise is_active will see the interface be driven actively, but allows a testbench that +// *does* want to customise the signal to pull it low. +wire is_active; +assign (weak0, weak1) is_active = 1'b1; + +// Should this interface generate a local tck signal? To enable that, set tck_en as well as +// is_active. +bit tck_en; + +// Output-enable flags for tms, tdi, tdo (which only have an effect if is_active is true). The +// default configuration enables tms and tdi, so acts as the root of the JTAG tree plus the +// "previous device in the scan chain". +bit tms_oe = 1'b1; +bit tdi_oe = 1'b1; +bit tdo_oe = 1'b0; + +logic _tck_internal, _trst_n_internal, _tms_internal, _tdi_internal, _tdo_internal; +assign tck = (is_active === 1'b1) ? _tck_internal : 'z; +assign trst_n = (is_active === 1'b1) ? _trst_n_internal : 'z; +assign tms = ((is_active === 1'b1) && tms_oe) ? _tms_internal : 'z; +assign tdi = ((is_active === 1'b1) && tdi_oe) ? _tdi_internal : 'z; +assign tdo = ((is_active === 1'b1) && tdo_oe) ? _tdo_internal : 'z; + +// Use negedge to drive jtag inputs because design also use posedge clock edge to sample. +clocking host_cb @(negedge tck); + default output #1ns; + output tms = _tms_internal; + output tdi = _tdi_internal; + input tdo; +endclocking +modport host_mp(clocking host_cb, output trst_n); + +clocking device_cb @(posedge tck); + input tms; + input tdi; + output tdo = _tdo_internal; +endclocking +modport device_mp(clocking device_cb, input trst_n); + +clocking mon_cb @(posedge tck); + input tms; + input tdi; + input tdo; +endclocking +modport mon_mp (clocking mon_cb, input trst_n); + +// Signals for local tck +int unsigned _tck_period_ps = JtagDefaultTckPeriodPs; +int unsigned _clk_hi_ps, _clk_lo_ps; +assign _clk_hi_ps = _tck_period_ps / 2; +assign _clk_lo_ps = _tck_period_ps - _clk_hi_ps; + +// Sets the TCK frequency. +function automatic void set_tck_period_ps(int unsigned value); + _tck_period_ps = value; +endfunction + +function automatic int unsigned get_tck_period_ps(); + return _tck_period_ps; +endfunction + +// Wait for one TCK cycle +// +// This waits for TCK to clear and then be asserted (so is waiting for the next posedge), but +// bounds the wait by _tck_period_ps (in case the clock has stopped). +// +// Waiting for !tck, then for tck ensures that we don't get any strange races when the clock is +// enabled: no matter what the relative phase, we will definitely wait at least a half cycle. +task automatic wait_one_tck(); + fork : isolation_fork begin + fork + begin + wait(!tck); + wait(tck); + end + #(_tck_period_ps * 1ps); + join_any + disable fork; + end join +endtask + +// Wait for the given number of cycles of TCK +task automatic wait_tck(int cycles); + repeat (cycles) wait_one_tck(); +endtask + +// Start asserting a test reset through trst_n (no effect if the interface is not active) +function automatic void assert_test_reset(); + _trst_n_internal <= 1'b0; +endfunction + +// Clear any test reset asserted through trst_n (no effect if the interface is not active) +function automatic void clear_test_reset(); + _trst_n_internal <= 1'b1; +endfunction + +// Assert a test reset through trst_n (no effect if the interface is not active) +task automatic do_trst_n(int cycles = $urandom_range(5, 20)); + assert_test_reset(); + wait_tck(cycles); + clear_test_reset(); +endtask + +// Drive _tck_internal with period _tck_period_ps whenever tck_en is high. If active is true, this +// gets used to drive the tck signal. +task automatic _drive_active(); + forever begin + wait(tck_en); + fork : isolation_fork begin + fork + wait(!tck_en); + forever begin + _tck_internal = 1'b1; + #(_clk_hi_ps * 1ps); + _tck_internal = 1'b0; + #(_clk_lo_ps * 1ps); + end + join_any + disable fork; + end join + end +endtask + +initial begin + _tck_internal = 1'b1; + forever begin + wait(is_active === 1'b1); + fork : isolation_fork begin + fork + wait(is_active !== 1'b1); + _drive_active(); + join_any + disable fork; + end join + end +end + +endinterface diff --git a/crates/vlog_parser/src/ast/decl.rs b/crates/vlog_parser/src/ast/decl.rs index 9903360..5f39885 100644 --- a/crates/vlog_parser/src/ast/decl.rs +++ b/crates/vlog_parser/src/ast/decl.rs @@ -235,12 +235,30 @@ pub struct ParamDecl { pub declarators: Vec, } +/// A net delay and the side of the data type it was written on. +/// +/// IEEE 1800 §6.7 puts `delay3` *after* the type — +/// `wire [31:0] #0.1 x = y;`, which is how +/// `pulp_riscv_dbg/tb/unused/SimDTM.sv:38` writes it — while the spelling +/// the rest of the corpus uses puts it between the net keyword and the type. +/// Both are read, never both at once, and printed back where they were +/// written: moving a delay across the type reorders tokens, which +/// `verify.rs` rightly refuses. +#[derive(Debug)] +pub struct NetDelay { + /// The delay itself: the `5` of `wire #5 w;`. + pub expr: Expr, + /// True when it stood between the data type and the declarators. + pub after_type: bool, +} + #[derive(Debug)] pub struct DataDecl { /// Net type (`wire`, `tri`, ...) if any. pub net: Option, - /// Net delay: the `5` in `wire #5 w;` - pub delay: Option, + /// Net delay, if any: the `5` in `wire #5 w;` or the `0.1` in + /// `wire [31:0] #0.1 x = y;`. + pub delay: Option, /// Qualifiers written before the type, in source order: `var`, /// `automatic`, `static`, `const`, and — inside a class body — `rand`, /// `randc`, `local`, `protected`, and the `virtual [interface]` of a diff --git a/crates/vlog_parser/src/parser/decl.rs b/crates/vlog_parser/src/parser/decl.rs index 2e63cbb..54e9d54 100644 --- a/crates/vlog_parser/src/parser/decl.rs +++ b/crates/vlog_parser/src/parser/decl.rs @@ -249,12 +249,7 @@ impl<'a> Parser<'a> { break; } } - let delay = if net.is_some() && self.cur().is_sym("#") { - self.bump(); - Some(self.parse_delay_value()?) - } else { - None - }; + let before = self.parse_net_delay(net.is_some(), false)?; // A declaration reaches here with its `virtual` already in // `qualifiers`, so `parse_opt_data_type`'s own modport branch cannot // fire: `virtual spi_if.tb tb_sif = sif.tb;` @@ -265,11 +260,34 @@ impl<'a> Parser<'a> { } else { self.parse_opt_data_type()? }; + // IEEE 1800 §6.7 writes the delay *here*, after the data type + // (`wire [31:0] #0.1 x = y;`, `pulp_riscv_dbg/tb/unused/SimDTM.sv:38`); + // everything else in the corpus writes it before. Either is read and + // printed back where it stood, but a declaration with one on each + // side is not a shape the LRM has. + let after = self.parse_net_delay(net.is_some(), true)?; + let delay = match (before, after) { + (Some(_), Some(_)) => { + return self.error("a net delay is written before or after the type, not both") + } + (before, after) => before.or(after), + }; let declarators = self.parse_declarators()?; self.expect_sym(";")?; Ok(DataDecl { net, delay, qualifiers, ty, declarators }) } + /// The net delay at the cursor, if one is written there: `#5`, `#0.1`, + /// `#(1:2:3)`. Only a net declaration may carry one, so `is_net` gates + /// the whole read — a `#` anywhere else belongs to whoever comes next. + fn parse_net_delay(&mut self, is_net: bool, after_type: bool) -> PResult> { + if !is_net || !self.cur().is_sym("#") { + return Ok(None); + } + self.bump(); + Ok(Some(NetDelay { expr: self.parse_delay_value()?, after_type })) + } + pub(super) fn parse_port_decl(&mut self) -> PResult { let dir = self.bump().text; let net = { diff --git a/crates/vlog_parser/src/parser/module.rs b/crates/vlog_parser/src/parser/module.rs index 2a294ed..a3ead93 100644 --- a/crates/vlog_parser/src/parser/module.rs +++ b/crates/vlog_parser/src/parser/module.rs @@ -2,6 +2,7 @@ //! belong only to them: parameter ports, ports (ANSI and non-ANSI), //! modports and clocking blocks. +use super::split::UnitHead; use super::*; /// The three pieces a `#( parameter ... )` port list yields, so module and @@ -21,6 +22,7 @@ impl<'a> Parser<'a> { /// one header grammar (IEEE 1800 §23.2.1, §25.3) and one body item list — /// only the closing keyword differs, so `end_kw` is the whole difference. pub(super) fn parse_module(&mut self, end_kw: &str) -> PResult { + let conds = self.open_conds; let kw = self.bump().text; let before_name = self.take_gap(); let Name { text: name, span: name_span } = self.expect_name()?; @@ -47,8 +49,18 @@ impl<'a> Parser<'a> { // behind it is what the module is for. self.expect_after_recovery(";", self.recovered_since(mark))?; let mut items = Vec::new(); + let mut head = UnitHead { kw: &kw, name: &name, conds, floor: conds }; while !self.at_body_end(end_kw) { + // Two rival headers written across the arms of one `ifdef region + // are bracket-balanced, so nothing else in the grammar objects + // until this unit runs out of file looking for its `end` keyword. + // Failing here instead routes the whole unit into the split + // recovery; see `docs/features/parser-skips/README.md`. + if self.at_rival_header(&head) { + return self.error(format!("rival header for `{name}` in a conditional region")); + } items.push(self.item_or_recover()?); + head.floor = head.floor.min(self.open_conds); } let dangling = self.take_dangling(); self.expect_closer(end_kw)?; diff --git a/crates/vlog_parser/src/parser/split.rs b/crates/vlog_parser/src/parser/split.rs index fb66ae5..d668f39 100644 --- a/crates/vlog_parser/src/parser/split.rs +++ b/crates/vlog_parser/src/parser/split.rs @@ -10,8 +10,10 @@ //! The recovery is deliberately hard to reach. It fires only after a real //! parse failure, and only when that failure is the grammar refusing a //! `else / `elsif / `endif that closes a region which is genuinely open -//! and which the failed item did not open, with a bracket the arm left -//! open. Everything else — a plain syntax error that merely sits near a +//! and which the failed item did not open — with a bracket the arm left +//! open, or with the arm behind the directive re-writing the very header +//! the failed item began with (`docs/features/parser-skips/README.md`). +//! Everything else — a plain syntax error that merely sits near a //! directive, a garbage token run with directives in it, an unterminated //! region, a stray closer with nothing open — still refuses. //! See `docs/features/directive-split/README.md`. @@ -106,7 +108,92 @@ fn construct_end(head: &[Token]) -> ConstructEnd { ConstructEnd::Unknown } +/// The unit whose body a loop is reading, as [`Parser::at_rival_header`] +/// needs it. +pub(super) struct UnitHead<'h> { + /// The unit's keyword, as written: `module`, `macromodule`, `interface` + /// or `program`. + pub(super) kw: &'h str, + /// The unit's name. + pub(super) name: &'h str, + /// Item-scope conditional regions open at the unit's own first token. + pub(super) conds: u32, + /// The lowest item-scope nesting the body has reached since it started. + /// Below `conds` means the region that stood open at the header was + /// closed inside the body, so a directive at the cursor continues some + /// later region rather than that one. + pub(super) floor: u32, +} + +/// The keyword that closes a unit, given its opening keyword — or `None` for +/// a keyword that opens no unit. `interface class` is a class and closes with +/// `endclass`; the caller rules it out by requiring a name after the keyword. +fn unit_end_kw(t: &Token) -> Option<&'static str> { + if t.kind != TokenKind::Keyword { + return None; + } + match t.text.as_str() { + "module" | "macromodule" => Some("endmodule"), + "interface" => Some("endinterface"), + "program" => Some("endprogram"), + _ => None, + } +} + +/// True when `t` opens a unit that `close` ends. Its own test, so a unit +/// *nested* in a captured body cannot end the extent scan on its closer. +fn opens_unit(t: &Token, close: &str) -> bool { + unit_end_kw(t) == Some(close) +} + impl<'a> Parser<'a> { + /// True when the cursor stands on the `` `else `` / `` `elsif `` of a + /// region opened *before* `head` was written, and the arm behind it + /// re-writes `head`'s own keyword and name. + /// + /// That is one header written twice across the arms of a region — the + /// `jtag_if.sv` shape — not a unit nested inside another one. Both + /// spellings are bracket-balanced, so nothing fails until the outer unit + /// reaches EOF looking for its closer; the body loop asks this before + /// each item instead, and fails where the evidence is. + /// See `docs/features/parser-skips/README.md`. + pub(super) fn at_rival_header(&self, head: &UnitHead) -> bool { + if !continues_conditional(self.cur()) { + return false; + } + // A region must have been open at the header, must still be the live + // one (nothing opened since is still open) and must never have been + // closed inside the body. + if head.conds == 0 || self.open_conds != head.conds || head.floor != head.conds { + return false; + } + self.nth(1).is_kw(head.kw) + && self.nth(2).kind == TokenKind::Ident + && self.nth(2).text == head.name + } + + /// The closing keyword of the unit a rival header opened, or `None` when + /// the item that failed at `mark` is not one. + /// + /// The mirror of [`Parser::at_rival_header`], read from the tokens rather + /// than from a flag on the error: [`ParseError`] is public and carries + /// only a message and a position, and every other condition of this + /// trigger is already read from the mark and the cursor — so all of the + /// evidence stays in one place and no error path can set the flag by + /// accident. + fn rival_end_kw(&self, mark: &ItemMark) -> Option<&'static str> { + let head = self.tokens.get(mark.pos)?; + let end = unit_end_kw(head)?; + let name = self.tokens.get(mark.pos + 1)?; + if name.kind != TokenKind::Ident { + return None; + } + let rival = self.nth(1).is_kw(&head.text) + && self.nth(2).kind == TokenKind::Ident + && self.nth(2).text == name.text; + rival.then_some(end) + } + /// Count the conditional-compilation directive standing at the cursor, /// which the caller is about to consume as an `ItemKind::Directive`. /// @@ -150,7 +237,9 @@ impl<'a> Parser<'a> { err: ParseError, ) -> PResult { if self.at_split_conditional(mark) { - if let Some((end_pos, conds_after)) = self.scan_split_extent(mark) { + if let Some((end_pos, conds_after)) = + self.scan_split_extent(mark, self.rival_end_kw(mark)) + { // The block swallowed the region's own `else / `endif, which // *are* item-scope nesting even though they now sit inside // opaque bytes. The extent scan already worked out what they @@ -202,9 +291,12 @@ impl<'a> Parser<'a> { /// and ends nothing: it is broken input, and the parse error stands; /// 3. the item's own conditional nesting is back to zero there, so the /// live region is one opened *before* the item rather than by it; - /// 4. the arm left a bracket open, i.e. it is structurally a fragment. - /// A missing `;` leaves nothing open and is indistinguishable from a - /// typo, so it is refused. + /// 4. the arm is structurally a fragment. Two spellings qualify: it left + /// a bracket open (`(`, `[` or `{` unmatched), or it is a **unit + /// header the next arm writes again** ([`Parser::rival_end_kw`]) — a + /// header written twice is as much a fragment as an unclosed bracket, + /// and it is the only bracket-balanced shape allowed in. A missing `;` + /// leaves neither, is indistinguishable from a typo, and is refused. fn at_split_conditional(&self, mark: &ItemMark) -> bool { let at = self.cur(); if !continues_conditional(at) && !closes_conditional(at) { @@ -228,7 +320,7 @@ impl<'a> Parser<'a> { brackets -= 1; } } - cond == 0 && brackets > 0 + cond == 0 && (brackets > 0 || self.rival_end_kw(mark).is_some()) } /// One past the last token of the construct the split region belongs to, @@ -248,13 +340,25 @@ impl<'a> Parser<'a> { /// no region live is a stray closer, not a split, and gives up — the same /// refusal the trigger makes, repeated here because the scan walks past /// the point the trigger looked at. - fn scan_split_extent(&self, mark: &ItemMark) -> Option<(usize, u32)> { + /// + /// `unit_end` is `Some(closing keyword)` for a rival unit header, whose + /// `;` closes only its *header*: the block is the whole unit, so the scan + /// runs to the matching `endmodule` / `endinterface` / `endprogram` + /// instead — counting units of the same kind on the way, so one nested in + /// the body cannot end it early. (An `interface class` nested in a + /// captured `interface` closes with `endclass`, leaves the count above + /// zero and makes the scan give up: the parse error stands, which is the + /// safe side.) + fn scan_split_extent(&self, mark: &ItemMark, unit_end: Option<&str>) -> Option<(usize, u32)> { // Regions this scan opened, and regions that were already open when // it started. A directive at scan level zero belongs to the latter. let mut cond = 0i32; let mut live = mark.conds; let mut closed_outer = false; let mut brackets = 0i32; + // Units of the head's kind open at `i`, counted only in `unit_end` + // mode. The head at `mark.pos` is itself the first one. + let mut units = 0i32; let mut i = mark.pos; while let Some(t) = self.tokens.get(i) { if t.kind == TokenKind::Eof { @@ -283,6 +387,15 @@ impl<'a> Parser<'a> { if brackets < 0 { return None; } + } else if let Some(close) = unit_end { + if opens_unit(t, close) { + units += 1; + } else if t.is_kw(close) { + units -= 1; + if units == 0 && cond == 0 && closed_outer { + return Some((self.past_end_label(i + 1), live)); + } + } } else if t.is_sym(";") && brackets == 0 && cond == 0 && closed_outer { return Some((i + 1, live)); } diff --git a/crates/vlog_parser/src/parser/tests/decl.rs b/crates/vlog_parser/src/parser/tests/decl.rs index 0270bb4..eeab05e 100644 --- a/crates/vlog_parser/src/parser/tests/decl.rs +++ b/crates/vlog_parser/src/parser/tests/decl.rs @@ -290,3 +290,58 @@ fn a_struct_member_may_be_declared_rand() { assert!(s.members[2].qualifiers.is_empty()); assert_eq!(s.members[0].declarators[0].name, "cpol"); } + +// ------------------------------------------------------------------ +// Net delays on either side of the data type (TODO §38.2, +// `docs/features/parser-skips/README.md`) +// ------------------------------------------------------------------ + +/// The net delay of a single-declaration module, with the side of the data +/// type it was written on. +fn net_delay_of(src: &str) -> (String, bool) { + let f = parse_ok(src); + let d = match &module_of(&f).items[0].kind { + ItemKind::DataDecl(d) => d, + _ => panic!("expected a declaration"), + }; + let delay = d.delay.as_ref().expect("a net delay"); + (src[delay.expr.span.as_range()].to_string(), delay.after_type) +} + +#[test] +fn a_net_delay_is_read_on_either_side_of_the_data_type() { + // Before the type is what the corpus writes; after it is where IEEE + // 1800 §6.7 puts `delay3`, and where + // `pulp_riscv_dbg/tb/unused/SimDTM.sv:38` writes it. + assert_eq!(net_delay_of("module m;\n wire #5 w;\nendmodule\n"), ("5".into(), false)); + assert_eq!( + net_delay_of("module m;\n wire [31:0] #0.1 x = y;\nendmodule\n"), + ("0.1".into(), true) + ); + // After a plain `logic`-typed net, and after a signed keyword run. + assert_eq!(net_delay_of("module m;\n wire logic #3 a;\nendmodule\n"), ("3".into(), true)); + assert_eq!( + net_delay_of("module m;\n wire signed [7:0] #(1:2:3) b;\nendmodule\n"), + ("(1:2:3)".into(), true) + ); + // The before position is unmoved by any of it. + assert_eq!( + net_delay_of("module m;\n wire #(1:2:3) signed [7:0] c;\nendmodule\n"), + ("(1:2:3)".into(), false) + ); +} + +#[test] +fn a_net_delay_written_on_both_sides_is_an_error() { + let msg = parse_err("module m;\n wire #5 [31:0] #6 x;\nendmodule\n"); + assert!(msg.contains("before or after the type, not both"), "{msg}"); +} + +#[test] +fn only_a_net_declaration_reads_a_delay() { + // A variable has no `delay3`, so the `#` is not swallowed here — it is + // an ordinary syntax error, exactly as it was before either position + // was accepted. + assert!(parse_err("module m;\n logic #5 x;\nendmodule\n").contains("expected")); + assert!(parse_err("module m;\n logic [7:0] #5 x;\nendmodule\n").contains("expected")); +} diff --git a/crates/vlog_parser/src/parser/tests/split.rs b/crates/vlog_parser/src/parser/tests/split.rs index 3f463af..92664d9 100644 --- a/crates/vlog_parser/src/parser/tests/split.rs +++ b/crates/vlog_parser/src/parser/tests/split.rs @@ -628,3 +628,158 @@ fn an_opening_split_that_is_the_last_item_does_not_eat_the_closing_keyword() { "a directive starting a statement list is pass-through, not a split" ); } + +// ------------------------------------------------------------------ +// Rival unit headers written across the arms of one region +// (`docs/features/parser-skips/README.md`) +// ------------------------------------------------------------------ + +/// The `jtag_if.sv` shape, in the four spellings that differ only in the +/// header: `interface`/`module`, with and without `#( ... )`, with `()` and +/// with a real port list. Every one of them is one verbatim item running +/// from the first header to the unit's own closing keyword. +#[test] +fn rival_unit_headers_across_one_region_become_one_verbatim_item() { + for (why, src, ends) in [ + ( + "interface, `#( ... ) ()` — hw/dv/sv/jtag_agent/jtag_if.sv:6", + "`ifdef GATE_LEVEL\n interface jtag_if #(parameter int unsigned P = 41_664) \ + ();\n`else\n interface jtag_if #(parameter int unsigned P = 20_000) \ + ();\n`endif\n wire tck;\nendinterface\nparameter int AFTER = 1;\n", + "endinterface", + ), + ( + "interface, no parameter list", + "`ifdef A\ninterface i ();\n`else\ninterface i ();\n`endif\n wire \ + tck;\nendinterface\nparameter int AFTER = 1;\n", + "endinterface", + ), + ( + "module, a real port list", + "`ifdef A\nmodule m (input a, output b);\n`else\nmodule m (input a, output \ + b);\n`endif\n wire x;\nendmodule\nparameter int AFTER = 1;\n", + "endmodule", + ), + ( + "module, a closing label", + "`ifdef A\nmodule m #(parameter int W = 1) ();\n`else\nmodule m #(parameter int W = \ + 2) ();\n`endif\n wire x;\nendmodule : m\nparameter int AFTER = 1;\n", + "endmodule : m", + ), + ] { + let f = parse_ok(src); + let kinds = split_items(&f); + assert_eq!(kinds.len(), 3, "{why}: {kinds:?}"); + assert!(kinds[0].starts_with("directive:`ifdef"), "{why}: {kinds:?}"); + assert_eq!(kinds[2], "param", "{why}: the item after the unit was not swallowed"); + let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("{why}: expected verbatim") }; + assert_eq!(raw.text, src[raw.span.as_range()], "{why}"); + assert!(raw.text.ends_with(ends), "{why}: {:?}", raw.text); + assert!(raw.text.contains("`else") && raw.text.contains("`endif"), "{why}: {:?}", raw.text); + // The whole unit is inside the block, its body included. + assert!(raw.text.contains("wire"), "{why}: {:?}", raw.text); + assert_eq!(open_conds_after(src), 0, "{why}: the region's own `endif was accounted for"); + } +} + +#[test] +fn rival_headers_produce_the_same_tree_in_both_modes() { + let src = "`ifdef GATE_LEVEL\n interface jtag_if #(parameter int unsigned P = 41_664) \ + ();\n`else\n interface jtag_if #(parameter int unsigned P = 20_000) \ + ();\n`endif\n wire tck;\nendinterface\n"; + let strict = parse_ok(src); + let toks = tokenize(src).expect("lex error"); + let (tolerant, diags) = parse_tolerant(toks, src); + assert!(diags.is_empty(), "{diags:?}"); + assert_eq!(split_items(&strict), split_items(&tolerant)); +} + +#[test] +fn comments_written_around_a_rival_header_are_kept() { + // The real file writes a comment inside each arm and one before the + // region; none of them may be dropped. + let src = "// head\n`ifdef GATE_LEVEL // which\n // 24MHz for GLS\n interface jtag_if \ + ();\n`else\n // 50MHz for DV\n interface jtag_if ();\n`endif\n // pins\n wire \ + tck;\nendinterface // done\n"; + let f = parse_ok(src); + assert_eq!(texts(&f.items[0].meta.leading), ["// head"]); + assert_eq!(f.items[0].meta.trailing.as_ref().expect("the `ifdef's comment").text, "// which"); + // The capture starts at the item's *first token*, so the comment written + // in front of the header is the item's own leading comment — the same + // place every other split puts it — and the rest are inside the block. + assert_eq!(texts(&f.items[1].meta.leading), ["// 24MHz for GLS"]); + let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") }; + for c in ["// 50MHz for DV", "// pins"] { + assert!(raw.text.contains(c), "{c} was dropped from {:?}", raw.text); + } + assert!(!raw.text.contains("// done"), "the trailing comment was swallowed"); + assert_eq!(f.items[1].meta.trailing.as_ref().expect("the comment survived").text, "// done"); +} + +#[test] +fn a_unit_nested_in_a_captured_body_does_not_end_the_scan_early() { + // The extent scan counts units of the head's kind, so the *inner* + // `endmodule` cannot be mistaken for the rival unit's own. + let src = "`ifdef A\nmodule m ();\n`else\nmodule m ();\n`endif\n module inner ();\n \ + endmodule\n wire x;\nendmodule\nparameter int AFTER = 1;\n"; + let f = parse_ok(src); + let kinds = split_items(&f); + assert_eq!(kinds.len(), 3, "{kinds:?}"); + let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") }; + assert!(raw.text.contains("module inner"), "{:?}", raw.text); + assert!(raw.text.ends_with("endmodule"), "{:?}", raw.text); + assert_eq!(kinds[2], "param", "{kinds:?}"); +} + +// -- the three negatives ---------------------------------------------- + +#[test] +fn a_second_unit_in_an_arm_of_a_region_opened_inside_the_body_is_still_an_error() { + // Two nested units, which is illegal: the region the `else belongs to + // was opened *by the body*, not before the header, so the arm is not a + // rival spelling of anything. + let msg = parse_err( + "`ifdef OUTER\nmodule m;\n`ifdef A\n wire a;\n`else\nmodule m;\n`endif\n wire \ + b;\nendmodule\n", + ); + assert!(msg.contains("endmodule"), "{msg}"); + // The same shape with no region open at all around the outer unit. + let msg = parse_err( + "module m;\n`ifdef A\n wire a;\n`else\nmodule m;\n wire \ + b;\n`endif\nendmodule\n", + ); + assert!(msg.contains("endmodule"), "{msg}"); +} + +#[test] +fn a_different_name_after_the_else_is_not_a_rival_header() { + let msg = parse_err( + "`ifdef A\ninterface i ();\n`else\ninterface j ();\n`endif\n wire \ + x;\nendinterface\n", + ); + assert!(msg.contains("endinterface"), "{msg}"); + // Nor is a different keyword for the same name. + let msg = parse_err( + "`ifdef A\ninterface i ();\n`else\nmodule i ();\n`endif\n wire x;\nendinterface\n", + ); + assert!(msg.contains("endinterface"), "{msg}"); +} + +#[test] +fn a_region_closed_before_the_header_leaves_the_else_stray() { + // The region opened at the top of the file is closed before the + // interface begins, so the `else below closes nothing: broken input, + // and the parse error stands. + let msg = parse_err( + "`ifdef A\n wire a;\n`endif\ninterface i ();\n`else\n interface i ();\n`endif\n wire \ + x;\nendinterface\n", + ); + assert!(msg.contains("endinterface"), "{msg}"); + // And a region closed *inside* the body before the `else: the header's + // region is gone, so the live one is not the one it was written under. + let msg = parse_err( + "`ifdef OUTER\ninterface i ();\n`endif\n`ifdef B\n wire a;\n`else\n interface i \ + ();\n`endif\nendinterface\n", + ); + assert!(msg.contains("endinterface"), "{msg}"); +} diff --git a/crates/vlog_semantic/src/bind/decl.rs b/crates/vlog_semantic/src/bind/decl.rs index 42eea8c..53a27fe 100644 --- a/crates/vlog_semantic/src/bind/decl.rs +++ b/crates/vlog_semantic/src/bind/decl.rs @@ -179,7 +179,7 @@ impl<'a> Binder<'a> { pub(super) 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); + self.bind_opt_expr(d.delay.as_ref().map(|n| &n.expr), scope); self.bind_declarators(&d.declarators, kind, &d.ty, span, scope); } diff --git a/docs/features/directive-split/README.md b/docs/features/directive-split/README.md index fbedeb2..e7ad52c 100644 --- a/docs/features/directive-split/README.md +++ b/docs/features/directive-split/README.md @@ -300,6 +300,15 @@ trigger is not too loose. `Fmt::raw_text`'s `crosses_line_inside_string` path emits a `Doc::Text` with embedded newlines and leaves the printer's column stale. Pre-existing (assertions round), no corruption. See Handshakes → Consumed. +- [x] **Two of the "not done, deliberately" items above were delivered by + TODO §38.1** (2026-09-04, `docs/features/parser-skips/README.md`): a + split whose shared tail ends in a **keyword** rather than a `;`, and the + one **bracketless** shape that is not indistinguishable from a missing + terminator — a unit header the next arm writes again (`jtag_if.sv`). + `at_split_conditional`'s fourth condition now reads "bracket open **or** + rival header", and `scan_split_extent` takes the unit's closing keyword. + The rest of the bracketless family stays refused, and the inside of a + split region is still byte-for-byte. ## Work log diff --git a/docs/features/parser-skips/README.md b/docs/features/parser-skips/README.md new file mode 100644 index 0000000..7d3cb9c --- /dev/null +++ b/docs/features/parser-skips/README.md @@ -0,0 +1,413 @@ +# 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.