# expressions-2 ## Goal Empty the corpus's `expressions` bucket — 21 files, every one of them blocked on a piece of expression grammar lucisv did not have — plus the one `other` file blocked on a `const ref` argument. Eight independent shapes, each taken from a real corpus file and cited below. All eight are **structural**: real AST nodes with a canonical layout, no new verbatim pass-through and no new normalization, so `verify.rs` is untouched. | # | shape | corpus evidence | |---|---|---| | 1 | cast over a non-simple base: `(NumLevels)'(unsigned'(j))`, `(DepthW + 3)'(1'b1)`, `lc_ctrl_pkg::TxWidth'(x)`, `prim_mubi_pkg::mubi4_t'(de ? d : q)` | `common_cells/src/lzc.sv:67`, `.../prim_fifo_sync_assert_fpv.sv:33`, `.../prim_fifo_async.sv:230`, `.../prim_fifo_async_sram_adapter.sv:346`, `.../prim_lc_sender.sv:32`, `.../prim_lc_sync.sv:42`, `.../prim_subreg_arb.sv:63` | | 2 | streaming concatenation `{<<8{v}}`, `{<` / `<->` implication as a binary operator | `ibex/dv/formal/check/peek/compare_helper.sv:42`, `.../follower.sv:168`, `ibex/dv/formal/check/top.sv:432` | | 4 | drive strength on a continuous assign: `assign (weak0, pull1) x = ...;` | `.../prim_usb_diff_rx.sv:39`, `.../prim_pad_wrapper.sv:71`, `.../common_ifs/pins_if.sv:97` | | 5 | `(* attribute *)` in front of a named port connection | `common_cells/src/cdc_fifo_gray.sv:140`, `.../cdc_fifo_gray_clearable.sv:182`, `.../cdc_reset_ctrlr.sv:158` | | 6 | assignment-pattern replication `'{NumRegs{0}}`, `'{uart_reg_pkg::NumRegs{0}}` | `opentitan/hw/ip/uart/rtl/uart.sv:17`, `.../uart_reg_top.sv:14` | | 7 | `x inside `MACRO` — the set is a macro invocation | `opentitan/hw/ip/uart/dv/env/uart_scoreboard.sv:155` | | 8 | `const ref` task/function argument | `ibex/vendor/lowrisc_ip/dv/sv/dv_utils/dv_utils_pkg.sv:104` | Beyond the cited shapes, the same grammar rules were taken where they cost nothing: `{>>{a, b}}` and `{<<{x}}` (no slice size), `{<< byte {x}}` (a type slice size), a streaming concatenation as an assignment *target*, `<->`, `(highz0, strong1)` and the other strength keywords in either order, a strength followed by a delay, and a `.name` / `.*` connection carrying an attribute. ## Layout Everything in this round is written tight, the way the constructs it extends already are: ```systemverilog assign a = (NumLevels)'(unsigned'(j)); // cast: no space anywhere assign b = {<<8{v}}; // stream: like a replication assign c = a -> b; // implication: like any binary op assign (weak0, pull1) d = e; // strength: one space after `)` parameter sel_t V [N] = '{NumRegs{0}}; // pattern replication return x inside `TX_IGNORED_PERIOD; // macro set, verbatim function automatic int max(const ref int q [$]); sub u ( (* async *) .a(x), // attribute, then the connection .bbbbbb (y), .c (z) ); ``` ## Assumptions - **`->` after an operand is always the implication operator.** The event trigger `-> ev;` is taken by `parse_stmt_kind` before any expression is parsed, so the two never compete. The non-blocking trigger `->>` still lexes as `->` `>` and is still unsupported, exactly as before. - **`->`/`<->` bind looser than `? :` and associate right** (IEEE 1800 §11.3.2), which is why they sit in their own `parse_implication` layer above `parse_ternary` rather than in the precedence-climbing table — everything in that table binds tighter than `? :`. - **A `(` right after `assign` opens a drive strength only when a strength keyword follows it.** Any other `(` is left to the left-hand side, so no existing assignment changes meaning. - **The casting type is a `constant_primary`** (IEEE 1800 §6.24.1). Accepted bases: a name, a `pkg::name` or `a.b` name, a number, and a parenthesized expression. Anything else (`f(1)'(x)`, `a[0]'(x)`) still gets the old `unsupported cast base expression` error — no corpus file needs it and guessing is how a formatter starts inventing grammar. - **`'{` opens the replication form when the first delimiter reached at bracket depth zero is a `{` that is not the very first token.** `'{a: 0}` (keyed), `'{x, y}` (positional), `'{default: 0}` and `'{{a, b}}` (one element, a concatenation) are all still the ordinary pattern. The decision is a token lookahead rather than a parse-then-look, because parsing the first element harvests its leading comments and there is nowhere to put them back. - **The `with [range]` form of a stream expression is not supported.** No corpus file writes it; a file that does keeps its old `expected expression` error rather than getting a half-modelled node. - **A `` `MACRO`` on the right of `inside` is passed through verbatim.** lucisv does not expand macros, so it cannot know the set the macro produces; the invocation is one token and is printed back as that token. - **A comment written immediately before a replication count is not kept.** `'{ /* c */ N{0}}` (and, unchanged from before this round, `{ /* c */ N{0}}`) makes the safety net reject the output and lucisv reports a clean error — never a dropped comment in a written file. The count has no comment slot in either AST node; adding one is the same fix for both and is left for whoever needs it. ## Handshakes **Consumed** - `vlog_parser::lexer` — `TokenKind::Attribute` for `(* ... *)`, and `Token::is_macro()` for the `` `MACRO`` on the right of `inside`. - `Meta::attrs`, which already existed for items and statements, is what a connection's attributes are stored in; `Fmt::list_breaks` already treats a non-empty `attrs` as an alignment-group boundary, so no alignment code needed changing. **Promised / changed** - `ast::ExprKind::Cast::ty` changed from `String` to `Box`. Consumers updated: `vlog_formatter::format` (prints the base as an expression), `vlog_semantic::bind` (unchanged behaviour — the casting type names a type and is still not bound), `vlog_parser/tests/spans.rs` (walks it). - Three new `ExprKind` variants: `Stream`, `AssignPatternRepl`, `InsideMacro`. Minimal arms added in `vlog_semantic/src/bind.rs` and `vlog_parser/tests/spans.rs`. `vlog_linter` matches no `ExprKind` and needed nothing. - New `ast::DriveStrength` and `ContAssign::strength`. - `lexer.rs`: `<->` added to `OPERATORS`. It is strictly widening — `<->` was previously two tokens that no rule accepted — and `a<-b` / `a<--b` still lex as `<` `-` / `<` `--`. - `verify.rs`: **untouched.** **Requests to other features** - `corpus/ibex/dv/formal/check/peek/compare_helper.sv` advanced past its `->` blocker and now fails at line 69, `assign csrs_match = `X_EACH_CSR 1;` — a macro invocation followed by an operand in expression position. The score script now classifies it as **macro-items**, not `expressions`. Left for that feature: reading `` `MACRO expr`` as anything other than two adjacent primaries needs the macro's definition, which lucisv does not have. - `corpus/picorv32/scripts/smtbmc/mulcmp.v` (`other`) is a trailing comma in a connection list — invalid Verilog. Left alone, as briefed. ## Status / TODO - [x] Baseline score saved and diffed against the final run (no file that passed before fails now). - [x] 1. Casts with a parenthesized / scoped / member base. - [x] 2. Streaming concatenations, including as an assignment target and with a type slice size. - [x] 3. `->` / `<->` implication, with the event trigger kept intact. - [x] 4. Drive strengths on continuous assignments. - [x] 5. `(* attribute *)` before a named port connection, alignment groups broken at it. - [x] 6. `'{N{0}}` assignment-pattern replication. - [x] 7. `inside` a macro invocation. - [x] 8. `const ref` task/function arguments. - [x] Cases in `crates/vlog_formatter/tests/cases/expressions_2.cases`: one per corpus shape, plus the fenced, commented and line-length-boundary edges and the negative forms of every ambiguity. - [x] Parser unit tests for the ambiguities: `-> ev;` stays a trigger, `'{a: 0}` stays a keyed pattern, an unsupported cast base still errors, a `(` after `assign` is only a strength when a strength keyword follows. - [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test` clean. - [x] README "Supported syntax" and roadmap item 9 updated; TODO.md item checked. - [ ] Not taken: `wire (pull1, weak0) w = 1;` — a drive strength on a *net declaration*. Same grammar, different item; no corpus file needs it, so it is left rather than written on spec. - [ ] Not taken: `{<<{a with [1:2]}}`. See Assumptions. - [ ] Not taken: a comment slot for a replication count. See Assumptions. ## Work log **2026-08-21 — dev** Baseline, before any change: ``` {"passing":751,"total":820,"pct":91.6,"failures_by_category":{"dv-statements":26,"expressions":21,"directive-split":14,"invalid-or-fragment":3,"lex-macro-number":2,"other":2,"not-verilog":1}} ``` After: ``` {"passing":772,"total":820,"pct":94.1,"failures_by_category":{"dv-statements":26,"directive-split":14,"invalid-or-fragment":3,"lex-macro-number":2,"macro-items":1,"not-verilog":1,"other":1}} ``` +21 files, and the pass set is a strict superset of the baseline's (checked with `comm` over both TSVs — zero regressions). All 20 remaining `expressions` files and the `dv_utils_pkg.sv` `other` file pass; the 21st `expressions` file, `compare_helper.sv`, advanced to a macro-items blocker and is now classified there (see Handshakes). Decisions worth recording: - **`Cast::ty` became an expression.** The alternative was to keep it a `String` and slice the source for the base, but then `(DepthW+3)'(1)` would print its base unformatted while everything around it was normalized. As an expression the base goes through `Fmt::expr` like any other, and `(DepthW+3)'(1'b1)` comes out `(DepthW + 3)'(1'b1)`. - **`parse_implication` gates only its recursion, not its entry.** The first cut wrapped the whole function in `enter()`/`leave()`, which put one nesting level on *every* expression in the language and halved the depth limit — the `deep_nesting` tests caught it immediately. Now only the right-associative `a -> b -> c` chain costs budget, which is the only part that recurses. - **The `'{N{...}}` decision is a lookahead, not a parse-and-look.** Parsing the first element first would have been shorter, but `parse_expr_item` harvests the element's leading comments into a `Meta` that the replication branch has nowhere to store — dropping them breaks a hard invariant, so the branch is chosen before any token is consumed. - **An attributed connection never joins an alignment group.** `Fmt::list_breaks` already ends a group at an element with attributes, and `connection_cells` now returns a single cell for one, so it cannot be measured into a neighbour's column either. The result is stable across passes, which the idempotency check in the case suite pins. - **The cast base is still not name-bound** in `vlog_semantic`. It now *has* a span, so binding it would have been one line, but `int'(x)` would then look up `int` as a lexical name and the linter would start reporting it. Type-name resolution is not something that crate does anywhere else; left alone deliberately, with the reason in the code comment. Files changed: - `crates/vlog_parser/src/ast.rs` — `Cast::ty` retyped; `Stream`, `AssignPatternRepl`, `InsideMacro` variants; `DriveStrength` and `ContAssign::strength`. - `crates/vlog_parser/src/lexer.rs` — `<->` in `OPERATORS`. - `crates/vlog_parser/src/parser.rs` — widened cast bases; `parse_stream_concat`; `parse_implication`; `parse_opt_drive_strength` and `is_drive_strength`/`DRIVE_STRENGTHS`; `at_assign_pattern_repl` / `parse_assign_pattern_repl`; the `` `MACRO`` arm of `inside`; `const ref` in `parse_tf_ports`; attributes in `parse_connection` and the `at_named_connection` peek; eight new unit tests. - `crates/vlog_formatter/src/format.rs` — printers for the four new/changed expression kinds, the drive strength, and a connection's attributes; `binary_prec` entry for `->`/`<->`; `connection_plain` split into itself and `connection_bare`. - `crates/vlog_semantic/src/bind.rs` — arms for the new variants. - `crates/vlog_parser/tests/spans.rs` — arms for the new variants. - `crates/vlog_formatter/tests/cases/expressions_2.cases` — new, 19 cases. - `README.md`, `TODO.md`. ## QA log ### 2026-08-21 — round-1 adversarial QA Verified: `cargo test --workspace`/clippy/fmt clean; corpus score 796/820; whole-corpus idempotency + comment-preservation sweep clean; 476-case mutation fuzz clean. Targeted attacks: - **`->` binary implication vs `-> ev;` event trigger vs `->>`.** `-> ev;`, `-> ev1; -> ev2;` (statement-position event trigger) and `x = (a -> b);`, `x = a ? (b -> c) : d;`, `if (a -> b) x = 1;` (expression implication) all format correctly. `a -> b;` and `a ->> b;` at bare statement position correctly error (there is no such statement form in real SV either — `->` needs to be a prefix event trigger or nested in an expression, never a bare infix statement). **Pre-existing gap, not introduced by this round:** `->>` (nonblocking event trigger, IEEE 1800 §15.5.2, e.g. `->> event_a;`) is not in the lexer's `OPERATORS` table at all (`crates/vlog_parser/src/lexer.rs:53-56`) — confirmed via `git diff` that this round only *added* `<->` to that table and did not touch (or regress) `->>`; it lexes today as `->` followed by a lone `>` and fails to parse in every context tried. Filing this as an out-of-round observation, not a finding against this diff. - **`a<-b` (no space) vs `<->`.** `x = a<->b;` and `x = a <-> b;` both format to `a <-> b` and are equivalent/idempotent; no case found where `<->` the new lexer entry mis-tokenizes an adjacent `<`/`-`/`>` combination. - **`parse_implication` recursion depth.** A 3000-deep `->` chain and a 500-deep `int'(...)` cast nest both hit the recursion-limit guard cleanly ("nesting too deep (limit 64)", exit 2) with no stack overflow — confirmed under a hard 10s wall-clock kill, no hang. - **`'{N{0}}` vs `'{a:0}` vs `'{ /*c*/ N{0}}`.** `'{N{0}}` and `'{a:0}` (→ `'{a: 0}`) format correctly. Confirmed the known case: a comment before the replication count — `'{ /*c*/ N{0}}` and `'{/*c*/N{0}}` — is rejected by the safety net with a clean `verification failed: token stream diverges` error (exit 2, zero bytes on stdout), **not corruption**, exactly as flagged. - `(* attr *)` on connections and `Cast::ty: Box` were exercised via the mutation fuzz on `expressions_2.cases` (delete paren, comment-in-gap, fence) with no panics or idempotency breaks; did not go deeper on alignment-inference interaction specifically. No BLOCKING findings for this cluster.