Round 5: CLI path/JSON/stdin and parser/formatter fixes (#1, #11, #42, #44-#47, #55)

This commit is contained in:
Guoliang Chen committed 2026-11-26 14:35:06 -08:00
1 parent 6d1c68994c
commit 4cf50a0b9c
40 files changed
+2767 -430

No files matched your search

+97
View File
@@ -0,0 +1,97 @@
<!-- Author: Guoliang Chen, a Senior Digital Design Engineer -->
# Core Path Normalization, CLI Stdin Config, JSON Format Output, and CLI Test Hardening (Round 5A)
## Goal
Deliver the Round 5A core path, CLI stdin config discovery, structured format JSON output, and CLI test hardening items (`#1`, `#11`, `#55`):
1. **Unified lexical path normalization (`#1`):** Extract `lucisv_core::path::{normalize, normalize_under}` in `crates/lucisv_core/src/path.rs` (re-exported via `crates/lucisv_core/src/lib.rs`) and replace the duplicate private normalization copies in `crates/lucisv_core/src/filelist.rs`, `crates/lucisv_core/src/config.rs`, `crates/lucisv_server/src/includes.rs`, and `crates/lucisv/src/main.rs` while preserving exact caller semantics across Unix and Windows prefixes/roots.
2. **CLI stdin config discovery & `#55`:** Ensure CLI stdin mode (`-` / `--stdin-filename <path>`) discovers and applies `lucisv.toml` / `.lucisv.toml` consistently in both `format` and `check` (including `[lint] select` and `[lint] ignore` precedence in `run_check_stdin`, rejecting empty `--stdin-filename ""`), and strengthen `a_stdin_buffer_reads_the_rule_options_too` in `crates/lucisv/tests/cli.rs` to assert explicit exit codes alongside stdout.
3. **Structured `--output-format json` for CLI format mode (`#11`):** Extend `--output-format <text|json>` to format mode (`lucisv` / `lucisv --check` / `lucisv format`), emitting a single-line JSON report with top-level `status`, `exit_code`, `summary`, and per-file `files` entries (`filename`, `status`, `cached`, `error: {category, line, column, message} | null`) while preserving existing text output and frozen `0`/`1`/`2` exit codes. Wire `tools/corpus_check.sh` and `scripts/score.sh` cleanly to consume `--output-format json` when `jq` is present (with text fallback), preserving identical TSVs and `814/6` corpus output.
## Assumptions
- Lexical normalization must never call `std::fs::canonicalize` so symlinks stay unfollowed and non-existent paths (`--stdin-filename`, rename targets) normalize identically to existing ones.
- Leading/excess `..` components on relative paths (and unrooted Windows drive-relative paths like `C:a\..\..`) are preserved, while `..` after a root directory (`/` or `C:\` or `\\server\share\`) clamps at the root.
- In format mode, `--output-format json` conflicts with `--diff`, `--stdout`, and stdin without `--check` (exiting `2`), matching `--diff` vs `--stdout` mutual exclusion so stdout is strictly one valid JSON document whenever JSON output is requested.
## Handshakes
- `crates/lucisv_core/src/path.rs` ↔ `crates/lucisv_core/src/{filelist.rs,config.rs}`, `crates/lucisv_server/src/includes.rs`, `crates/lucisv/src/main.rs`:
- `includes::normalize` re-exports `lucisv_core::path::normalize` so `crates/lucisv_server/src/file_ops.rs` continues using `crate::includes::normalize` without cross-lane edits.
- `filelist::Reader`, `config::Discovery`, and `lucisv::identity` call `lucisv_core::path::normalize_under`.
- `crates/lucisv/src/{args.rs,main.rs,lint.rs}` ↔ `tools/corpus_check.sh`, `scripts/score.sh`:
- Format JSON schema: `{"status":"ok|would-reformat|reformatted|error","exit_code":0|1|2,"summary":{"changed":N,"unchanged":N,"cached":N,"errors":N},"files":[{"filename":...,"status":"unchanged|cached|would-reformat|reformatted|error","cached":bool,"error":null|{"category":"parse-error|lex-error|verification-error|io-error|selection-error|panic","line":u32|null,"column":u32|null,"message":...}}]}`.
- Frozen `0`/`1`/`2` CLI exit codes, stderr error/summary formatting, and `corpus_check.sh` / `score.sh` TSV and stdout formats are preserved identically (`814/6`, byte-identical TSV rows).
- `crates/lucisv/tests/cli.rs`:
- `#55` closed by explicit exit-code assertions (`0` under matching config, `1` without config) in `a_stdin_buffer_reads_the_rule_options_too`, plus regression tests for stdin config discovery (`format` and `check`) and format `--output-format json`.
## Status / TODO
- [x] Implement `lucisv_core::path::{normalize, normalize_under}` and replace duplicate copies in `filelist.rs`, `config.rs`, `includes.rs`, and `main.rs`
- [x] Fix stdin `[lint] select`/`ignore` discovery and empty `--stdin-filename` handling; strengthen `#55` and add stdin format/check discovery tests
- [x] Implement format-mode `--output-format json` (`args.rs`, `main.rs`, sharing `lint::quote` / `lint::pick`), wire `tools/corpus_check.sh` and `scripts/score.sh`, and add CLI JSON tests
- [x] Enforce `<= 600` non-blank non-comment prod lines before `mod tests`, `0` `.unwrap()`/`.expect()`/`panic!`/`unsafe` in library code, author stamps, and full verification gates
## Work log
### 2026-11-26 — dev (Round 5A)
- Created `crates/lucisv_core/src/path.rs` (`normalize`, `normalize_under`) and exported `pub mod path` in `crates/lucisv_core/src/lib.rs`, with Unix, Windows prefix/root/drive-relative, and platform-independent unit tests.
- Replaced duplicate lexical normalization loops in `crates/lucisv_core/src/filelist.rs`, `crates/lucisv_core/src/config.rs`, `crates/lucisv_server/src/includes.rs` (`pub use lucisv_core::path::normalize`), and `crates/lucisv/src/main.rs` (`normalize_under`).
- Fixed `crates/lucisv/src/main.rs::run_check_stdin` to honor `[lint] select` / `[lint] ignore` via `lint::pick`, rejected empty `--stdin-filename ""` in `crates/lucisv/src/args.rs` (with `.filter(|s| !s.is_empty())` defense in `stdin_config`), and strengthened `a_stdin_buffer_reads_the_rule_options_too` (`#55`) plus new relative/`../` stdin config discovery tests in `crates/lucisv/tests/cli.rs`.
- Added `--output-format json` support to format mode (`crates/lucisv/src/{args.rs,main.rs,lint.rs}`), wired `tools/corpus_check.sh` and `scripts/score.sh` to consume `--output-format json` when `jq` is present (preserving text fallback and byte-identical TSV / `814/6` output), and added comprehensive CLI JSON tests (`unchanged`, `would-reformat`, `reformatted`, `cached`, `parse-error`, `lex-error`, `io-error`, stdin `--check`, and flag conflicts).
- Verified production line counts before `#[cfg(test)]`/`mod tests` (`path.rs` 39, `lib.rs` 7, `filelist.rs` 160, `config.rs` 313, `includes.rs` 342, `args.rs` 444, `main.rs` 550, `lint.rs` 495) and `0` `.unwrap()`/`.expect()`/`panic!`/`unsafe` in non-test production code.
### 2026-11-26 — dev (Round 5A QA fix)
- Fixed `tools/corpus_check.sh` exit-2 fallback when `use_json=1` (`jq` present) receives empty stdout (e.g. a pre-`process_file` `gather` error such as a broken `lucisv.toml`) or empty/unparseable JSON error detail: extracted shared `classify_text_error` and re-ran `"$lucisv" --check "$file" 2>&1` whenever `msg` is empty, aligning with `scripts/score.sh`.
- Verified broken `lucisv.toml` repro (`exit 2`, non-empty column-3 error message preserved) and corpus parity both with `jq` and with `jq` absent from `PATH`, plus `./tools/gates.sh --only corpus` (`814/6`), `bash -n tools/corpus_check.sh scripts/score.sh`, and `python3 tools/stamp_author.py --check`.
## QA log
### 2026-11-26 — QA (Round 5A)
**Verdict: FAIL** (one defect in `tools/corpus_check.sh` exit-2 fallback when `use_json=1` and stdout is empty).
1. **Ownership & invariants (PASS):**
- `git status --short` / `git diff --stat`: only Lane 5A files touched (`crates/lucisv_core/src/{lib.rs,path.rs,filelist.rs,config.rs}`, `crates/lucisv_server/src/includes.rs`, `crates/lucisv/src/{args.rs,lint.rs,main.rs}`, `crates/lucisv/tests/cli.rs`, `scripts/score.sh`, `tools/corpus_check.sh`, `docs/features/cli-path-r5/README.md`).
- Non-blank, non-comment production lines before `mod tests`: `path.rs` 38, `lib.rs` 7, `filelist.rs` 159, `config.rs` 312, `includes.rs` 341, `args.rs` 443, `lint.rs` 494, `main.rs` 549 (all `<= 600`), with `0` `.unwrap()`, `.expect()`, `panic!`, or `unsafe` in non-test production code.
2. **Adversarial requirement audit:**
- **`#1` (`lucisv_core::path` — PASS):** Verified `normalize` and `normalize_under` in `crates/lucisv_core/src/path.rs` (`.`/`..` folding without `canonicalize`, preserving leading/excess `..` on relative and Windows drive-relative paths like `C:a\..\..\b`, clamping `..` at Unix/Windows/UNC roots, `.`/`a/..` -> `.`, `""` -> `""`), and verified duplicate lexical loops were removed from `filelist.rs`, `config.rs`, `includes.rs` (re-exporting `lucisv_core::path::normalize`), and `main.rs` (`normalize_under`). `git grep "Component::" crates/` confirmed no remaining duplicate normalization loops in `lucisv_core`, `lucisv_server`, or `lucisv`.
- **Stdin config & `#55` (PASS):** Verified `run_check_stdin`, `stdin_config`, `args.rs`, `lint::pick`, and `crates/lucisv/tests/cli.rs` (`a_stdin_buffer_reads_the_rule_options_too` asserts explicit `0`/`1` exit codes; `stdin_discovers_config_relative_to_stdin_filename_across_cwd_and_subcommands` covers relative/`../` discovery for `format` and `check`, `[lint] select`/`ignore`, unknown config rule exit `2`, and empty `--stdin-filename ""` rejection). Adversarial binary probes confirmed CLI-over-config precedence (`--select`, `--ignore`, `--no-config`) in stdin `check` mode.
- **`#11` (`--output-format json` — FAIL on `tools/corpus_check.sh` fallback):**
- `args.rs` / `main.rs` / `tests/cli.rs`: single-line JSON schema (`status`, `exit_code`, `summary`, `files`) verified across clean (`exit 0`), dirty (`--check` `exit 1`), in-place (`reformatted`, `exit 0`), cached (`cached: true`, `exit 0`), `parse-error` / `lex-error` / `verification-error` / `io-error` / `selection-error` / `panic` (`exit 2`), stdin `--check`, and conflict rejections (`--diff`, `--stdout`, non-`--check` stdin).
- `scripts/score.sh` & `tools/corpus_check.sh` parity: on `~/.cache/lucisv-corpus` (820 files, `814/6`), both scripts produced byte-identical TSVs and outputs with `jq` vs text fallback (`PATH` without `jq`).
- **Defect (`tools/corpus_check.sh:57-102`):** When `use_json=1` (`jq` present) and `lucisv --check --output-format json "$file" 2>/dev/null` exits `2` with empty stdout (for example, a pre-`process_file` `gather` error such as a broken `lucisv.toml` in a directory), `if [ "$use_json" -eq 1 ] && [ -n "$out" ];` evaluates false and enters the `else` branch, grepping the empty `$out` instead of re-running `"$lucisv" --check "$file" 2>&1` (unlike `scripts/score.sh:184-193`). Verified with a broken `lucisv.toml` probe: `scripts/score.sh` recorded the full error message in column 4, while `tools/corpus_check.sh` emitted an empty column 3 (`other-error\t<file>\t`). Likewise, if `jq` succeeds with an empty `msg` or fails (`lines 86-92`), `corpus_check.sh` hardcodes `outcome=other-error` instead of classifying the fallback text output uniformly.
3. **Executed checks (all in worktree):**
- `python3 tools/stamp_author.py --check`: PASS (`would stamp 0 files; left 249 untouched`)
- `cargo fmt --all -- --check`: PASS
- `bash -n tools/corpus_check.sh scripts/score.sh`: PASS
- `cargo clippy -p lucisv_core -p lucisv -p lucisv_server --all-targets -- -D warnings`: PASS
- `cargo check --target x86_64-pc-windows-gnu --all-targets -p lucisv_core` (with `stable-aarch64-apple-darwin` rustup toolchain): PASS
- `./tools/guard.sh -m 8 -t 600 -- cargo test -p lucisv_core -p lucisv -p lucisv_server --all-targets`: PASS (`lucisv` unit 35 passed, `cli` 117 passed, `style_cli` 5 passed; `lucisv_core` 122 passed; `lucisv_server` unit 2082 passed / 47 ignored, `e2e` 106 passed / 3 ignored, `grammar` 3 passed, `ifdef_folding` 1 passed, `opentitan_references` 0 passed / 2 ignored)
- `./tools/gates.sh --only corpus,cross`: PASS (`corpus` `814/6`, `cross` Windows + Linux musl check pass)
### 2026-11-26 — QA re-verification (Round 5A)
**Verdict: PASS.**
- **Diff & ownership check:** Confirmed `git diff --stat` changed only `tools/corpus_check.sh` (+5 lines vs prior audit) and `docs/features/cli-path-r5/README.md`; all Rust files (`crates/lucisv_core/src/**`, `crates/lucisv_server/src/includes.rs`, `crates/lucisv/src/**`, `crates/lucisv/tests/cli.rs`) and `scripts/score.sh` are unchanged since the prior PASS checks.
- **Fix inspection (`tools/corpus_check.sh:40-108`):** Extracted `classify_text_error` and wired `if [ -z "$msg" ]; then` to re-run `"$lucisv" --check "$file" 2>&1` when `use_json=1` and classify via `classify_text_error` across empty `$out`, invalid JSON, and empty `msg`.
- **Repro & parity verification:**
- Broken `lucisv.toml` (`exit 2`, empty JSON stdout) with and without `jq` on `PATH`: both emitted identical TSV rows (`other-error .../a.sv .../lucisv.toml:1: unknown key \`bogus\` ...`), `diff -u` clean.
- Invalid-JSON fallback probe (`not-valid-json` with `exit 2`) with and without `jq` on `PATH`: both classified identically via `classify_text_error` (`parse-error .../a.sv parse error: 9:1: synthetic fallback error`), `diff -u` clean.
- **Re-executed gates:**
- `bash -n tools/corpus_check.sh scripts/score.sh`: PASS
- `python3 tools/stamp_author.py --check`: PASS (`would stamp 0 files; left 249 untouched`)
- `./tools/gates.sh --only corpus`: PASS (`814/6`, `corpus` pass)
## Review
**Lead Self-Inspect (2026-11-26): APPROVED for trunk commit.**
- Merged Lane 5A onto trunk after Round 5A QA PASS (including `tools/corpus_check.sh` `classify_text_error` fallback fix on exit 2 empty-stdout / bad-JSON cases).
- Verified `#1` (`lucisv_core::path::{normalize,normalize_under}` replacing `filelist`, `config`, `includes`, `main`), stdin config + `[lint] select/ignore` + `#55` exit codes, and `#11` (`--output-format json` + byte-identical `814/6` corpus TSV parity).
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->
+126
View File
@@ -0,0 +1,126 @@
<!-- 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 -->