127 lines
20 KiB
Markdown
127 lines
20 KiB
Markdown
<!-- Author: Guoliang Chen, a Senior Digital Design Engineer -->
|
|
|
|
# Parser Syntax Fixes & Parse-Once `--style auto` / Multi-Instance Layout (Round 5B)
|
|
|
|
## Goal
|
|
|
|
Deliver the Round 5B parser and formatter accuracy, throughput, and hygiene fixes across `vlog_parser` and `vlog_formatter`:
|
|
|
|
1. **Parse-once `--style auto` (`crates/vlog_formatter/src/{auto.rs, format/mod.rs, verify.rs, selection/mod.rs}`):** Lex/parse `source` and collect fenced regions once across all `PRESETS`, reuse the verified output AST/fences in `resolve_style`'s `canonical` lookup, avoid redundant re-parses in `format_range` / `format_selection`, preserve full `verify.rs` equivalence and convergence invariants, and preserve byte-identical outputs.
|
|
2. **Parser & formatter edge fixes:**
|
|
- **`#44`:** Support comments (including trailing `//` / `/* ... */ // ...` after labelled generate `end : label`) between generate `end` and `else` / `else if`.
|
|
- **`#45`:** Support `` `ifdef `` / conditional directives between `end` and `else` in both procedural `if` and generate `if` (both balanced intervening directives and conditional `else` arms).
|
|
- **`#46`:** Support SystemVerilog attributes (`(* keep *)`, multiple attributes, interleaved comments, directionless/typed/modport ANSI ports) on ANSI ports and round-trip cleanly.
|
|
- **`#42`:** Tighten parser leniency on invalid constructs (`{d,, d}`, `{, d}`, `{d,}`, `{N{a,, b}}`, `'{N{a,, b}}`, `{<<{a,, b}}`, `case a,, b:`, `f(.a(x),)`), and verify `#42a` trailing `,` in named connection lists and `#42c` `type(x)'(y)` against `scripts/score.sh` and OpenTitan `hw/` without regressing `814` corpus or `4,039/4,046` OpenTitan pass counts.
|
|
- **`#47`:** Format multi-instance declarations (`p1 u8 (...), u9 (...);`) symmetrically under `PortLists::OnePerLine` styles (`google`, `lowrisc`, `microsoft`, `nxp`) so every instance opens and closes at the same indented column instead of falling back to the asymmetric hanging layout, while preserving `PortLists::Fit` (`lucisv`, `ansi`) default output.
|
|
3. **Production safety & size hygiene:** Zero `.unwrap()`, `.expect()`, `panic!()`, or `unsafe` in non-test production code of `vlog_parser/src/**` and `vlog_formatter/src/**`, and keep all modified/added production files `<= 600` non-blank non-comment lines before `#[cfg(test)]` / `mod tests`.
|
|
|
|
## Assumptions
|
|
|
|
- Downstream crates (`vlog_semantic`, `vlog_refactor`, `vlog_linter`, `lucisv_server`, `lucisv_mcp`) pattern-match `GenElse::If(_, _)` and `GenElse::Block(_)`; keeping `GenElse`'s two tuple/struct-free signatures unchanged and adding fields to `GenIf` (`then_trailing`, `else_directives`, `else_comments`) preserves cross-crate compatibility.
|
|
- Under `PortLists::OnePerLine`, ordered/empty multi-instance declarations (`p1 u8 (), u9 ();`, `p1 u8 (a), u9 (b);`) stay flat on one line when they fit and break symmetrically (`p1\n u8 ...,\n u9 ...;`) whenever any instance's named connection list or line width breaks the declaration.
|
|
- Positional call omitted arguments (`f(a, , b)`, OpenTitan `flash_ctrl_default_region_cfg(,,,scr_en, ecc_en)`) and ordered instance trailing commas (`u(a, b,)`) are preserved per IEEE 1800 and `qa_port_entry_grace`.
|
|
|
|
## Handshakes
|
|
|
|
- `vlog_parser::ast::{GenIf, StmtKind::If}` ↔ `vlog_formatter::format::{branch, stmt}`: `GenIf` adds `then_trailing`, `else_directives`, and `else_comments`; `StmtKind::If` adds `else_directives` (staying within `ast::size_pins` bounds: `StmtKind <= 392`, `Stmt <= 552`).
|
|
- `vlog_formatter::verify` ↔ `vlog_formatter::{auto, format/mod.rs, selection/mod.rs}`: `verify::stream_from_tokens` and `verify::verify_equivalence_items` reuse pre-lexed token streams without altering `pub fn verify_equivalence`.
|
|
- `vlog_refactor::check::qa_implicit` ↔ `vlog_parser`: Tolerant error-element recovery for `.d(type(q)'(q))` and strict/tolerant trailing-comma rules from `port_entry_recovery` (`14213f6`) stay intact.
|
|
- Strict disjoint file ownership maintained: touched only `crates/vlog_parser/{src,tests}/**`, `crates/vlog_formatter/{src,tests}/**`, and `docs/features/parser-formatter-r5/README.md`.
|
|
|
|
## Status / TODO
|
|
|
|
- [x] Refactor `auto.rs` / `format/mod.rs` / `verify.rs` / `selection/mod.rs` for parse-once `--style auto`, `resolve_style`, `format_range`, and `format_selection`
|
|
- [x] Fix `#44` comments (including trailing `//` after labelled generate `end : label`) between generate `end` and `else`
|
|
- [x] Fix `#45` `` `ifdef `` and conditional directives between `end` and `else` (procedural and generate `if`)
|
|
- [x] Fix `#46` attributes on ANSI ports in `vlog_parser` and `vlog_formatter`
|
|
- [x] Tighten `#42b` empty brace/case elements + `f(.a(x),)` and verify `#42a`/`#42c` against corpus and OpenTitan `hw/`
|
|
- [x] Fix `#47` multi-instance declarations under `PortLists::OnePerLine`
|
|
- [x] Eliminate remaining non-test `.unwrap()` calls in `format/decl.rs` and `format/item.rs` and verify `<= 600` production line counts
|
|
- [x] Add regression suites `crates/vlog_parser/tests/parser_r5.rs` and `crates/vlog_formatter/tests/formatter_r5.rs` and pass all CI/OpenTitan gates
|
|
|
|
## Work log
|
|
|
|
### 2026-11-26 — dev (Round 5B)
|
|
|
|
- **Baseline (`6d1c689`):**
|
|
- OpenTitan `/Users/lucio/repo/opentitan/hw` (4,046 files, `--style auto --check --no-cache`): `5.040 s` wall (`39.06 s` user, `3.03 s` sys, `835%` CPU); `3967` would reformat, `72` unchanged, `7` failed (4,039 passing, 0 verification failures).
|
|
- OpenTitan default (`--style lucisv`): `0.981 s` wall (`6.80 s` user, `0.63 s` sys); `3967` reformatted, `72` unchanged, `7` failed. Snapshotted all 4,039 formatted outputs to `/tmp/r5b_base_ot_default` before editing.
|
|
- Corpus (`./tools/gates.sh --only corpus`): `PASS` (`814/6`, `2 s`).
|
|
- **Parse-once `--style auto` (`auto.rs`, `format/mod.rs`, `verify.rs`, `selection/mod.rs`):**
|
|
- Added `format::parse_once`, `format::render_parsed`, `format::verify_rendered`, `verify::stream_from_tokens`, and `verify::verify_equivalence_items`; switched `Fmt::{regions, splits}` to borrowed slices.
|
|
- Updated `auto::closest_inner` to lex/parse `source` once, render all 6 `PRESETS` on the shared `(file, regions)`, short-circuit on `output == source`, rank remaining candidates using reusable `LineCounter` (`total_a + total_b - 2*matched`), verify only the winning candidate (preserving earliest-preset error priority if all fail), and reuse `(out_file, out_regions)` in `canonical_parsed`.
|
|
- Updated `format_range` and `format_selection` via `auto::resolve_concrete` to reuse the parsed input AST under `auto`.
|
|
- Post-change OpenTitan `--style auto --check --no-cache` benchmark (3 runs): `2.991 s`, `2.758 s`, `2.660 s` (`17.55 s` user, `1.81 s` sys, `727%` CPU) — **~1.9x wall / ~2.2x user CPU faster** than `6d1c689` (`5.040 s` / `39.06 s`) and **~2.05x faster** than historical `5.46 s`, with **0 diff lines** on stdout/stderr vs `6d1c689`.
|
|
- **`#44` & `#45` (`ast/{module,stmt}.rs`, `parser/{directive,item,stmt,split}.rs`, `format/{branch,stmt}.rs`):**
|
|
- Added `GenIf::{then_trailing, else_directives, else_comments}` and `StmtKind::If::else_directives`; added `Parser::take_else_preamble`, `has_else_past_directives`, and `take_else_directives` in `directive.rs`.
|
|
- Added `Parser::{at_conditional_else_ahead, at_conditional_else_split, scan_if_conditional_else_extent}` in `split.rs` to capture conditional `else` inside `` `ifdef `` / `` `ifndef `` (balanced blocks/brackets/`` `endif ``s, rival `` `else `` arms, optional trailing unconditional `else`) verbatim while leaving unterminated/unbalanced cases rejected and non-`else` `` `ifdef ``s separate.
|
|
- Updated `format/branch.rs` with shared `push_else_keyword` and `gen_then_branch` (detecting merged `/* a */ // b` line-ending trailing comments on generate blocks).
|
|
- **`#46` (`parser/{cursor,decl,module,item,stmt,instance}.rs`, `format/module.rs`):**
|
|
- Extracted `Parser::take_attrs` (draining both same-line `pending_trailing` and next-line `tok.leading` into `meta.leading`), reused across `item`, `stmt`, `instance`, and `parse_ansi_port`.
|
|
- Added `at_typed_declarator_at` and `at_modport_port_at` so `parse_port_list` skips leading `(* ... *)` attributes when detecting ANSI port lists (including directionless, `pkg::type`, and `intf.modport` ports).
|
|
- Updated `format/module.rs` (`ansi_port_item`, `ansi_port_cells`, `ansi_port_plain`) to render ANSI port attributes and preserve any comments interleaved between/after attributes without breaking token order or joining alignment groups.
|
|
- **`#42` (`parser/{primary,instance,randsequence}.rs`):**
|
|
- **#42b:** Tightened `Parser::parse_expr_item` / `parse_expr_list` via `parse_expr_item_with(allow_omitted: bool)` so empty elements are accepted only in parenthesized argument lists (`close == ")"` and not after `NamedArg`), rejecting `{d,, d}`, `{, d}`, `{d,}`, `{4{d,, d}}`, `{<<{d,, d}}`, `'{4{d,, d}}`, `case a,, b:`, and `f(.a(x),)` while preserving `{}` and omitted positional call args (`f(a, , b)`).
|
|
- **#42a:** Confirmed named port/override trailing commas (`.a(x),)`, `#(.W(1),)`) are already refused strictly and reported tolerantly by `note_trailing_comma` (`port_entry_recovery.rs`); tightened `f(.a(x),)` named call trailing commas, keeping `directives_in_lists` `,` before `` `ifdef `` and IEEE 1800 positional `u(a, b,)` untouched (`0` matches in OpenTitan/corpus for dangling `,` before `` `ifdef ... `endif ) ``).
|
|
- **#42c:** Confirmed malformed `type(x)'(y)` in connections, overrides, and expressions (`sub u (.a(type(x)'(y)))`, `sub #(.T(type(x)'(y)))`, `assign w = type(x)'(y)`) is already rejected strictly (`unexpected keyword 'type' in expression`) and diagnosed tolerantly (`qa_implicit.rs` pins `.d(type(q)'(q))` recovery).
|
|
- **`#47` (`format/instance.rs`):**
|
|
- Under `PortLists::OnePerLine`, placed multi-instance declarations inside `group(vec![indent(inner)])` starting with `Doc::Line` (`!on_fresh_line`), so broken multi-instance statements indent every instance (`u8`, `u9`, ...) uniformly and align each instance's closing `)` with its own opening line (`google` 2/4/8, `lowrisc`/`nxp` 2/4/6, `microsoft` 4/8/12) while keeping `PortLists::Fit` (`lucisv`, `ansi`) byte-identical.
|
|
- **Safety & file-size audit:** Eliminated the remaining 2 non-test `.unwrap()` calls in `format/decl.rs` and `format/item.rs` using `TryFrom<[ListItem; 1]>` and `saturating_sub`; verified `0` `.unwrap()`, `.expect()`, `panic!()`, or `unsafe` in non-test production code across `vlog_parser/src/**` and `vlog_formatter/src/**`, and verified all production files remain `<= 600` non-blank non-comment lines (`item.rs` 589, `module.rs` 568, `instance.rs` 565, `stmt.rs` 564).
|
|
|
|
### 2026-11-26 — dev QA-fix (Round 5B)
|
|
|
|
- Fixed QA `#45` defect 1 (`crates/vlog_parser/src/parser/split.rs` + `directive.rs`): unified `else_past_directives_at` in `directive.rs`, changed `scan_uncond_branch` to return `(usize, bool /* is_if */)`, and made `scan_if_conditional_else_extent` loop across `cond_else_at(i)`, optional balanced directives before `else`, and any chained `else if (...) ... else ...` branches while stopping cleanly on non-`else` `` `ifdef ``s or a non-`if` `else` terminator.
|
|
- Fixed QA `#45` defect 2 (`crates/vlog_parser/src/parser/split.rs::scan_cond_else_region`, `scan_uncond_branch`): added explicit `outer_open: bool` state (distinct from nested `cond` depth) and nested `` `else `` / `` `elsif `` skipping at `cond > 0` so balanced nested `` `ifdef ... `endif `` directives inside a shared `else` tail scan cleanly through the closing `end` / `;` instead of exiting prematurely when nested `cond` returns to `0`.
|
|
- Added regression tests covering both procedural and generate variants, balanced intervening directives inside `else if ... else` chains, nested `` `ifdef ... `else ... `endif `` inside shared tails, and negative/unterminated bounds in `crates/vlog_parser/tests/parser_r5.rs` and `crates/vlog_formatter/tests/formatter_r5.rs`.
|
|
|
|
## QA log
|
|
|
|
### 2026-11-26 — dev verification (self-check)
|
|
|
|
- `crates/vlog_parser/tests/parser_r5.rs`: 6/6 passed (`#44`, `#45` directives + conditional `else` + negatives, `#46`, `#42a/b/c`).
|
|
- `crates/vlog_formatter/tests/formatter_r5.rs`: 5/5 passed (all 6 presets + `auto` verification/idempotency/layout pins + `resolve_style`/`format_range`/`format_selection`).
|
|
- `auto_sweep` over `/Users/lucio/repo/opentitan/hw`: `4,047` files scanned, `7` refused (pre-existing parse errors), `0` crashes, `0` non-idempotent, `0` second-run preset renames (`lucisv: 3379`, `lowrisc: 526`, `microsoft: 80`, `google: 30`, `nxp: 21`, `ansi: 4`).
|
|
- Default-style (`--style lucisv`) OpenTitan diff against pre-edit snapshot (`/tmp/r5b_base_ot_default` vs `/tmp/r5b_new_ot_default`): `0` differing files across all 4,039 passing files; `--style auto` output `0` diff lines vs baseline.
|
|
- `./tools/gates.sh --only corpus`: `PASS` (`814/6`, `2 s`).
|
|
- `cargo fmt --all -- --check`, `python3 tools/stamp_author.py --check`, `cargo clippy -p vlog_parser -p vlog_formatter --all-targets -- -D warnings`, `./tools/guard.sh -m 8 -t 600 -- cargo test -p vlog_parser -p vlog_formatter -p vlog_semantic -p vlog_refactor -p vlog_linter --all-targets`: see final gate run after README addition.
|
|
|
|
### 2026-11-26 — Round 5 Lane 5B QA audit (`FAIL`)
|
|
|
|
- **Verdict: `FAIL`** (two edge-case defects found in `#45` conditional-`else` extent scanning in `crates/vlog_parser/src/parser/split.rs`; all invariants, gates, OpenTitan/corpus benchmarks, parse-once `--style auto`, `#44`, `#46`, `#42`, and `#47` passed).
|
|
- **Defects found in `crates/vlog_parser/src/parser/split.rs`:**
|
|
1. `scan_if_conditional_else_extent` (`split.rs:640-655`): When a conditional `` `ifdef ``/`` `ifndef `` `else` arm is followed by an unconditional `else if (...)` branch that is itself followed by an unconditional `else` (either generate `if` or procedural `if`), `scan_uncond_branch` stops after the `else if` branch at the trailing `else`, and `scan_if_conditional_else_extent` only continues the loop when `self.cond_else_at(i)` is true, leaving the trailing `else` orphaned and failing with `unsupported construct/statement starting with keyword 'else'`.
|
|
2. `scan_cond_else_region` (`split.rs:657-698`): When a conditional `else` region opens a block/bracket in its first arm and hits `` `else ``/`` `elsif `` with `blocks > 0` or `brackets > 0` (setting `cond = 0` at `split.rs:683` to scan past `` `endif `` to the closing `end`/`;`), any nested balanced `` `ifdef ... `endif `` inside that shared tail increments `cond` to `1` and decrements back to `0`, hitting `if cond == 0 { return (brackets == 0 && blocks == 0).then_some(i + 1); }` (`split.rs:675-677`) and returning `None` prematurely instead of continuing to the branch closer (failing cleanly with `conditional 'else' after 'if'`).
|
|
- **Checks verified in worktree (HEAD `6d1c689`):**
|
|
- Ownership & invariants: Only Lane 5B paths modified/created (`crates/vlog_parser/{src,tests}/**`, `crates/vlog_formatter/{src,tests}/**`, `docs/features/parser-formatter-r5/README.md`). All 23 changed library `.rs` files are `<= 600` non-blank non-comment production lines before `#[cfg(test)]`/`mod tests` (max `589` in `crates/vlog_parser/src/parser/item.rs`). `0` occurrences of `.unwrap()`, `.expect()`, `panic!`, or `unsafe` in non-test production code across `crates/vlog_parser/src/**` and `crates/vlog_formatter/src/**`.
|
|
- `cargo fmt --all -- --check`: PASS.
|
|
- `python3 tools/stamp_author.py --check`: PASS (`would stamp 0 files; left 249 untouched`).
|
|
- `cargo clippy -p vlog_parser -p vlog_formatter --all-targets -- -D warnings`: PASS.
|
|
- `./tools/guard.sh -m 8 -t 600 -- cargo test -p vlog_parser -p vlog_formatter -p vlog_semantic -p vlog_refactor -p vlog_linter --all-targets`: PASS (`2,787` passed, `0` failed, `12` ignored — `vlog_formatter`: `381`, `vlog_linter`: `672`, `vlog_parser`: `527` + `2` ignored, `vlog_refactor`: `769` + `6` ignored, `vlog_semantic`: `438` + `4` ignored).
|
|
- `./tools/gates.sh --only corpus`: PASS (`814/820`, `0` verification errors, `0` crashes, `3 s`).
|
|
- OpenTitan `/Users/lucio/repo/opentitan/hw` (`target/release/lucisv`): default `--check --no-cache` (`3,967` would reformat, `72` unchanged, `7` pre-existing lex/parse failures = `4,039/4,046` pass, `0` verification failures); `--style auto --check --no-cache` (`3,967` would reformat, `72` unchanged, `7` pre-existing lex/parse failures = `4,039/4,046` pass, `0` verification failures); `auto_sweep` (`4,047` files, `7` refused, `0` crashes, `0` non-idempotent, `0` second-run renames; `lucisv: 3379, lowrisc: 526, microsoft: 80, google: 30, nxp: 21, ansi: 4`). `/Users/lucio/repo/opentitan` `git status --porcelain` is empty.
|
|
- Parse-once `--style auto`, `#44`, `#46`, `#42`, `#47`: All explicit requirements and adversarial stdin probes passed (apart from the two `#45` `split.rs` edge cases above).
|
|
|
|
### 2026-11-26 — Round 5 Lane 5B QA re-audit (`PASS`)
|
|
|
|
- **Verdict: `PASS`** (both prior `#45` defects in `crates/vlog_parser/src/parser/split.rs` and `directive.rs` are fixed and verified; all invariants, tests, corpus, and OpenTitan gates pass).
|
|
- **Re-audit of `#45` fixes (`crates/vlog_parser/src/parser/{split.rs,directive.rs}`, `crates/vlog_parser/tests/parser_r5.rs`, `crates/vlog_formatter/tests/formatter_r5.rs`):**
|
|
- `scan_if_conditional_else_extent` (`split.rs:640-660`) + `else_past_directives_at` (`directive.rs:218-247`) + `scan_uncond_branch` (`split.rs:720-779`): Confirmed unconditional `else if (...) ... else ...` chains (with or without balanced directives before `else`) after conditional `` `ifdef `` / `` `ifndef `` `else` arms parse and format idempotently across both procedural and generate `if`, while outer `else` branches (`if (outer) if (inner) ...`) and trailing non-`else` `` `ifdef `` blocks remain unswallowed.
|
|
- `scan_cond_else_region` (`split.rs:662-718`): Confirmed `outer_open` tracking and nested `` `else `` / `` `elsif `` skipping at `cond > 0` allow balanced nested `` `ifdef ... `else ... `endif `` inside shared `else` tails to scan cleanly through the closing `end` / `;` while rejecting stray `` `else `` / `` `endif ``, unbalanced directives, and unmatched `end`/`else`.
|
|
- **Invariants & gates verified in worktree (HEAD `6d1c689`):**
|
|
- Ownership & sizes: Strictly Lane 5B files (`crates/vlog_parser/{src,tests}/**`, `crates/vlog_formatter/{src,tests}/**`, `docs/features/parser-formatter-r5/README.md`). All 23 changed library `.rs` files remain `<= 600` production LOC (`item.rs` 589, `stmt.rs` 570, `module.rs` 568, `instance.rs` 565, `split.rs` 554, `directive.rs` 265). `0` non-test `.unwrap()`, `.expect()`, `panic!`, or `unsafe` across `crates/vlog_parser/src/**` and `crates/vlog_formatter/src/**`.
|
|
- `cargo fmt --all -- --check`: PASS.
|
|
- `python3 tools/stamp_author.py --check`: PASS (`would stamp 0 files; left 249 untouched`).
|
|
- `cargo clippy -p vlog_parser -p vlog_formatter --all-targets -- -D warnings`: PASS.
|
|
- `./tools/guard.sh -m 8 -t 600 -- cargo test -p vlog_parser -p vlog_formatter -p vlog_semantic -p vlog_refactor -p vlog_linter --all-targets`: PASS (`2,787` passed, `0` failed, `12` ignored — `vlog_formatter`: `381`, `vlog_linter`: `672`, `vlog_parser`: `527` + `2` ignored, `vlog_refactor`: `769` + `6` ignored, `vlog_semantic`: `438` + `4` ignored).
|
|
- `./tools/gates.sh --only corpus`: PASS (`814/820`, `0` verification errors, `0` crashes, `3 s`).
|
|
- OpenTitan `/Users/lucio/repo/opentitan/hw` (`target/release/lucisv --style auto --check --no-cache`): `3,967` would reformat, `72` unchanged, `7` failed (pre-existing lex/parse errors = `4,039/4,046` pass, `0` verification failures); `/Users/lucio/repo/opentitan` `git status --porcelain` is empty.
|
|
|
|
## Review
|
|
|
|
**Lead Self-Inspect (2026-11-26): APPROVED for trunk commit.**
|
|
- Merged Lane 5B onto trunk after Round 5B QA Re-Audit PASS (including `#45` `split.rs` conditional-`else` fixes for trailing `else if ... else ...` chains and nested `` `ifdef `` inside shared tails).
|
|
- Verified parse-once `--style auto` (`~2.66-3.01 s` vs `5.04-5.46 s` baseline across 4,046 OpenTitan `hw/` files, `0` verification failures, default `--style lucisv` byte-identity on all `4,039` passing OpenTitan files, `0` non-test `.unwrap()` calls across `vlog_parser` & `vlog_formatter`, and `814/6` corpus PASS).
|
|
- Updated `crates/lucisv_mcp/src/tools/place.rs` test `what_a_placement_cannot_see_or_would_change_is_refused` after `#46`: `(* keep *) b` now parses cleanly as an attributed port inheriting direction from `a`, while `123 b` exercises the unreadable `ListElem::Error` refusal path.
|
|
|
|
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->
|