diff --git a/.gitignore b/.gitignore index ea8c4bf..004de68 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ /target +/corpus +/corpus-check-results.tsv diff --git a/README.md b/README.md index 04201f9..149a4d6 100644 --- a/README.md +++ b/README.md @@ -97,11 +97,23 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset: assignment patterns (`'{...}`), `inside`, hierarchical and package-scoped names, macro usages in expression position -Not yet supported (parse errors, roadmap in order): -interfaces/modports, classes/constraints, concurrent assertions -(`assert property`), sequences, `case ... inside`, streaming operators, -DPI, specify blocks, `let`/`checker`. Like ruff, `vfmt` refuses to output -anything for a file it cannot fully parse, so it can never corrupt code. +Not yet supported (parse errors). Roadmap ordered by measured impact on +real RTL — see `docs/features/corpus-check/README.md` for the 820-file +corpus baseline this ordering comes from: + +1. Macro invocation at module-item / statement position + (`` `ASSERT_INIT(...) `` style) — ≈60% of RTL parse errors in the corpus +2. `bind` directives +3. Classes/constraints (mostly blocks DV/UVM code, not RTL) +4. Dynamic arrays and queues +5. Declarations with identifier (typedef'd) types in some positions + (`my_t [N-1:0] x;`) +6. DPI, concurrent assertions (`assert property`), non-simple casts +7. Interfaces/modports, `case ... inside`, streaming operators, specify + blocks, `let`/`checker`, sequences — rare in the corpus RTL + +Like ruff, `vfmt` refuses to output anything for a file it cannot fully +parse, so it can never corrupt code. ## Contributing / workflow diff --git a/TODO.md b/TODO.md index 88f930c..2ef95be 100644 --- a/TODO.md +++ b/TODO.md @@ -34,7 +34,11 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both. but `)` is unconditionally lexed as an attribute (`lexer.rs`), so a bare space inside `@( * )`-style spellings errors out. Make the attribute scan back off when the contents are just `*`. -- [ ] **Recursion-depth limit in the parser.** Found by cli-polish QA: +- [ ] **Recursion-depth limit in the parser.** (In progress: five gates + landed and the original repro is fixed, but QA found postfix chains + — `a.b.b...`, `x[0][0]...`, `p::q::...` — are parsed iteratively with + unbounded AST depth and crash the formatter's recursion; the gate must + also cover `parse_postfix` before this checks off.) Found by cli-polish QA: ~150 levels of expression nesting overflow the stack and abort the whole process — uncatchable by `catch_unwind`, so mid-batch files after the crash never get processed. Add an explicit depth counter in @@ -158,13 +162,16 @@ Adapt each: lint-clean and formatter-idempotent. - [ ] **[V] Error-case tests.** Table of inputs that must *fail* to parse with the expected error position — locks in the failsafe path. -- [ ] **[R] Real-world corpus check (ruff's "ecosystem check").** ruff +- [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, PULP cores, picorv32. Script: clone pinned revs, run vfmt over every `.sv/.v`, report parse-success rate + equivalence/convergence failures; fail CI on regression. Also the honest tracker for the "not yet supported" list in README. + → `tools/corpus_fetch.sh` + `tools/corpus_check.sh`, baseline and + findings in `docs/features/corpus-check/README.md`. CI wiring is the + one part left open (network access is a separate decision). - [ ] **[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. diff --git a/docs/features/corpus-check/README.md b/docs/features/corpus-check/README.md new file mode 100644 index 0000000..da464c4 --- /dev/null +++ b/docs/features/corpus-check/README.md @@ -0,0 +1,668 @@ +# corpus-check + +## Goal + +Run `vfmt` against real open-source RTL and report how much of it we can +parse, how much is already format-clean, and what is blocking the rest — +vfmt's version of ruff's "ecosystem check" (TODO.md §5). Two scripts: +`tools/corpus_fetch.sh` clones pinned revisions of permissively-licensed +Verilog/SystemVerilog projects into a gitignored `corpus/`, and +`tools/corpus_check.sh` runs the release binary over every `.v`/`.sv` +file in `--check` mode and prints a health summary. The point is an +*honest tracker*: the "Not yet supported" list in `README.md` is a guess +about what real code needs, and this feature measures it. Anything that +comes back as a verification failure or a crash is, by construction, a +formatter bug rather than unsupported syntax, so the report doubles as a +bug finder. + +## Assumptions + +- **One error per file is the right unit.** The parser stops at its first + error, so each file votes exactly once in the error breakdown. That + makes the ranking "how many files does this construct block", not "how + often does this construct occur". A construct that always co-occurs + with an earlier blocker is therefore invisible (see the caveat under + Baseline, where `assert property` and `case ... inside` are present in + the corpus but rarely surface as the *first* error). +- **Exit codes are the classification.** The script depends on the frozen + contract in `README.md`: 0 clean, 1 would-reformat, 2 error. Any other + status (including 128+signal) is treated as a crash. If that contract + moves, this script is wrong. +- **Error *kind* is classified from the diagnostic text**, not from a + machine-readable channel: a first stderr line containing "verification + failed" is a verification error, one starting `parse error:`/`lex + error:` is a parse error, anything else at exit 2 is `other-error` + (I/O, contained panics). This is a string dependency on + `vlog_formatter`'s `Display` impls — see Handshakes. +- **The corpus is read-only.** Only `--check` is ever invoked. Verified + after each run with `git -C corpus/ status --porcelain`. +- **File paths in the corpus contain no spaces or tabs.** The results + file is TSV and the `error: : ` prefix is stripped by literal + string match; both would need quoting otherwise. True for all four + pinned repos. +- **`corpus/` is disposable.** It is gitignored, never committed, and can + be deleted and re-fetched; the pins make that reproducible. +- **No new dependencies.** POSIX-ish shell plus `git`, `find`, `awk`, + `sed`, `sort`, `uniq` — all already required to work on this repo. + +## Handshakes + +**Consumed from `crates/vfmt` (CLI):** + +- The exit-code contract (0/1/2) documented in `README.md`. Frozen; if it + ever changes, `check_one()` in `tools/corpus_check.sh` must change with + it. +- Diagnostics on stderr in the form `error: : `. + +**Consumed from `crates/vlog_formatter` / `crates/vlog_parser`:** + +- The message prefixes `parse error:`, `lex error:` (from + `vlog_parser::Error`) and the substring `verification failed:` (from + `VerificationError`). These are matched textually. **Request to the + formatter/parser owners:** if you reword these, either keep those three + markers or tell this feature. A structured `--output-format json` would + remove the dependency entirely (see Status/TODO). + +**Promised to others:** + +- `tools/corpus_check.sh` exits 1 if any verification error or crash was + seen, 0 otherwise, so it can gate a future CI job without parsing its + output. +- The per-file TSV (`outcomepathmessage`, default + `corpus-check-results.tsv`) is the stable machine-readable artifact. + Slice it with `awk` for per-repo or per-directory views; the script + deliberately does not grow flags for those. + +**Not touched:** nothing under `crates/` was read for state or modified. +This feature is scripts + docs only. + +## Corpora and pins + +`tools/corpus_fetch.sh` pins every repo to an exact commit and fetches it +shallow (`--depth 1` at that SHA). Nothing tracks a branch, so the +numbers below are reproducible. Re-running the script is a no-op when the +recorded SHA in `/.vfmt-corpus-rev` already matches. + +| Project | License | Pinned commit | Why | +|---|---|---|---| +| [picorv32](https://github.com/YosysHQ/picorv32) | ISC | `a473fc8fca393771d83b0ffcf0b14db3393339d8` (master) | Small, classic Verilog-2001, no SV. The "does the boring case work" baseline. No release tags exist, so master is pinned by SHA. | +| [lowRISC/ibex](https://github.com/lowRISC/ibex) | Apache-2.0 | `7b5df75a041affe56e8c235260f98a09b3319008` (master) | Mainstream synthesizable SV core, plus a large vendored `lowrisc_ip` prim library and a UVM DV tree — good coverage of both RTL and testbench dialects. Its only tags are stale `pulpino`/`pulpissimo` ones, so master is pinned by SHA. | +| [pulp-platform/common_cells](https://github.com/pulp-platform/common_cells) | SHL-0.51 (permissive) | `1281545696eb3fcba50ec5b4275993476a3c710e` (tag `v1.40.0`) | A different SV house style from lowRISC: heavy `` `FF* `` register macros, parameterized types, generate-heavy. Pinned at a real release tag. | +| [lowRISC/OpenTitan](https://github.com/lowRISC/opentitan) | Apache-2.0 | `bc1910f4505346dbef000155530fd5a68c60e889` (master), sparse: `hw/ip/uart` + `hw/ip/gpio` only | Whole repo is far too large to clone. Fetched as a blobless partial clone (`--filter=blob:none`) with a cone-mode sparse checkout of just those two IP blocks — 35 files instead of thousands, at a fraction of the download. Represents "peripheral IP with heavy assertion macros". | + +820 `.v`/`.sv` files total: common_cells 131, ibex 613, opentitan 35, +picorv32 41. + +## Baseline (2026-08-19) + +- vfmt built from commit **`9f1a6cf1d2926358e2a804b33fb4de55bb9f04e7`** + (`cargo build --release`), working tree otherwise clean apart from this + feature's own files. Numbers will move once the recursion-limit and + `@(* )` lexer fixes in TODO.md §1 land — re-run and update this section + after they do. +- Command: `./tools/corpus_fetch.sh corpus && ./tools/corpus_check.sh corpus` + +``` +outcome files share +-------------------- ----- ------- +ok-unchanged 1 0.1% +would-reformat 264 32.2% +parse-error 531 64.8% +verification-error 24 2.9% +other-error 0 0.0% +crash 0 0.0% +-------------------- ----- ------- +total 820 100.0% + +parsed & formattable: 265/820 (32.3%) +already format-clean: 1/820 (0.1%) +``` + +Per repo: + +| Repo | files | clean | would-reformat | parse-error | verification-error | +|---|---|---|---|---|---| +| common_cells | 131 | 0 | 51 | 70 | 10 | +| ibex | 613 | 1 | 178 | 421 | 13 | +| opentitan | 35 | 0 | 4 | 31 | 0 | +| picorv32 | 41 | 0 | 31 | 9 | 1 | + +Splitting testbench/DV code (paths containing `/dv/`, `/tb/`, `/test(s)/`, +`/sim/`, `/fpv/`, `/pre_dv/`, `/uvm/`) from synthesizable RTL: + +| Slice | files | formattable | parse-error | verification-error | +|---|---|---|---|---| +| RTL | 474 | 195 (41.1%) | 260 (54.9%) | 19 | +| testbench/DV | 346 | 70 (20.2%) | 271 (78.3%) | 5 | + +Two rates, since they differ and both matter: + +- **parsed** = everything that reached the formatter = 289/820 (**35.2%**) + — `ok-unchanged` + `would-reformat` + `verification-error`. +- **formattable** = parsed *and* passed the runtime safety net = + 265/820 (**32.3%**). The 24-file gap is the bug list below. +- **format-clean** = 1/820 (0.1%), i.e. 0.4% of what is formattable. + +**The 0.1% "already clean" figure is expected, not alarming.** vfmt is an +opinionated reformatter and none of these projects were formatted with +it; "would-reformat" is the correct outcome for essentially all +third-party code. The number worth tracking over time is +*parse-success*, plus the absolute zero we want in the last two columns. + +### Top blocking constructs (all 820 files, one vote per file) + +Categorized from the first-error diagnostic plus the three source lines +around it (so a macro call spanning several lines is still recognized). + +| # | Construct | Files | On README's "Not yet supported" roadmap? | +|---|---|---|---| +| 1 | **Macro invocation as a module item / statement** (`` `ASSERT_INIT(...) ``, `` `FFARNC(...) `` — no trailing `;`) | ≥200 | **No — not on the list at all** | +| 2 | **Classes / UVM**, including parameterized class types (`extends`, `class foo #(...)`, `typedef uvm_sequencer#(T) x;`) | 182 | Yes — roadmap #2 | +| 3 | **`bind` statements** | 28 | **No** | +| 4 | **`interface` / `modport` / `clocking`** | 24 | Yes — roadmap #1 | +| 5 | **Dynamic arrays `[]` and queues `[$]`** | 20 | **No** | +| 6 | **User-defined type name in declaration position** (`T [1:0] mem_d;`, `omega_data_t [N-1:0] x;`) | ≈9 | **No** | +| 7 | **DPI import/export** (`import "DPI-C" ...`) | 7 | Yes — roadmap #7 | +| 8 | **Concurrent assertions / properties** (`assert property`, `assume`, `cover`) | 6 | Yes — roadmap #3 | +| 9 | **Casts with a non-simple base** (`T'('0)`, `(DepthW+3)'(1'b1)`) | 4 | **No** | +| 10 | **Lex errors** (`expected digits after number base`, and the `@(* )` attribute bug from TODO §1) | 3 | Partly — the `@(* )` bug is tracked in TODO §1 | + +Remaining long tail (~40 files): system-task calls as generate items +(`if (P < 3) $error("...");` at module level), `(* async *)` attributes in +positions we do not accept, `export`, `weak0` drive strengths, and a +handful of macro cases whose call spans more than three lines (so the +category-1 count is a floor, not a ceiling). + +### Does reality match the roadmap's priority order? + +**No — stated plainly:** + +1. **The single biggest blocker is not on the roadmap.** Macro + invocations used as module items or statements block ≥200 files (38% + of all parse errors; **60% of parse errors in synthesizable RTL**, 157 + of 260). Both lowRISC and PULP build their register and assertion + layers out of these (`` `ASSERT_KNOWN ``, `` `FF `` families), so this + single unsupported form gates most of the modern SV RTL in the corpus. + `README.md` claims macro usages are supported "in expression + position", which is exactly the wrong half: the item/statement + position is what real code needs. This should be the next parser item + by a wide margin — and it is cheap next to interfaces or classes, + because the macro call can stay opaque (a pass-through item, like + `` `define ``). +2. **Interfaces/modports — roadmap #1 — are nearly absent here** (24 + files, only *one* of them synthesizable RTL; only one file in the + whole corpus contains `modport`). That is a property of the corpus, + not proof the roadmap is wrong: ibex, common_cells and picorv32 use + plain ports. An interface-heavy project (e.g. `pulp-platform/axi`) is + the obvious addition before drawing a conclusion — see Status/TODO. +3. **Classes — roadmap #2 — rank second (182 files) but are almost + entirely testbench/DV code** (`ibex/dv/uvm`, `vendor/google_riscv-dv`). + If vfmt's target is synthesizable RTL, this is much lower value than + its rank implies (34 RTL files); if the target includes UVM + testbenches, it is the top item after macros. +4. **Three constructs missing from the roadmap outrank three that are on + it**: `bind` (28), dynamic arrays/queues (20), and identifier-typed + declarations (≈9) all beat DPI (7), concurrent assertions (6), and + everything below them. +5. **The bottom half of the roadmap is unmeasurable from this corpus.** + `case ... inside` (13 files contain it), streaming operators (3), + `let` (1), `checker` (13), `sequence` (51), `specify` (0) — these + constructs *are* present in the source, but the parser dies earlier in + those files, so they never surface as a first error. Do not read + "0 hits" as "unused"; read it as "blocked behind items 1–6". `specify` + is the one genuine zero: no file in the corpus contains it. + +Suggested roadmap reorder based on this corpus: **macro items/statements +→ identifier-typed declarations + non-simple casts (both small) → bind → +dynamic arrays/queues → interfaces → classes → the rest as listed.** + +## Findings: verification errors (24) — all are formatter bugs + +`format_source()` runs equivalence and convergence checks on every call, +so a file that reaches these checks has parsed fine and the formatter +produced output that is *not* token-equivalent to the input. Per the hard +invariants in `CLAUDE.md` (never corrupt code, never drop comments), each +of these is a bug. The safety net did its job — every one of these files +was left untouched on disk — but the underlying rules are wrong. They +fall into four root causes. + +**A. Event-list comma rewritten as `or` (10 files).** Input +`always_ff @(posedge clk_i, negedge rst_ni)` comes out with `or` in place +of the comma. Semantically identical, lexically not — and the equivalence +check is right to reject it, since a formatter should not rewrite tokens. + +- `corpus/common_cells/src/cdc_4phase.sv` — `input has symbol `,` at 172:28, output has keyword `or` at 170:29` +- `corpus/common_cells/src/deprecated/clock_divider_counter.sv` — `, at 110:27 → or at 100:27` +- `corpus/common_cells/src/deprecated/generic_LFSR_8bit.sv` — `, at 37:27 → or at 33:27` +- `corpus/common_cells/src/deprecated/pulp_sync.sv` — `, at 26:29 → or at 18:29` +- `corpus/common_cells/src/deprecated/pulp_sync_wedge.sv` — `, at 47:28 → or at 35:27` +- `corpus/common_cells/src/lossy_valid_to_stream.sv` — `, at 123:28 → or at 121:29` +- `corpus/common_cells/src/max_counter.sv` — `, at 67:30 → or at 65:29` +- `corpus/common_cells/src/sync.sv` — `, at 27:30 → or at 21:29` +- `corpus/common_cells/src/sync_wedge.sv` — `, at 47:28 → or at 35:27` +- `corpus/ibex/shared/rtl/ram_1p.sv` — `, at 46:28 → or at 44:29` + +**B. Comments dropped (9 files).** The diagnostic reads "input has +comment X, output has " — i.e. the comment is gone from the +output. This breaks hard invariant #3 directly. Two clusters: block +comments (`/* verilator ... */`) inside port/parameter lists and +expressions, and line comments attached to items inside `always` blocks +or parameter lists. + +- `corpus/common_cells/src/edge_propagator.sv` — `/* unused */` at 26:16 +- `corpus/ibex/rtl/ibex_alu.sv` — `// Comparator OPs` at 64:7 +- `corpus/ibex/rtl/ibex_prefetch_buffer.sv` — `// Current address + 4` at 171:25 +- `corpus/ibex/vendor/lowrisc_ip/ip/prim/pre_dv/prim_trivium/rtl/prim_trivium_tb.sv` — `// Clear back to zero upon staring a new reseed operation.` at 204:7 +- `corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_fifo_async_simple.sv` — `// (EnRzHs = 0) is used. Enable the RZ handshake protocol` at 13:44 +- `corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_filter_ctr.sv` — `// restart` at 75:74 +- `corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_subst_perm.sv` — `/* verilator split_var */` at 32:49 +- `corpus/ibex/vendor/lowrisc_ip/ip/prim_generic/rtl/prim_clock_buf.sv` — `/* verilator lint_on UNUSED */` at 13:3 +- `corpus/ibex/vendor/lowrisc_ip/ip/prim_generic/rtl/prim_clock_gating.sv` — `/* verilator clock_enable */` at 20:18 + +**C. Consecutive header imports merged (4 files).** A module header with +two `import` items before the port list — + +```systemverilog +module prim_alert_rxtx_tb + import prim_alert_pkg::*; + import prim_mubi_pkg::mubi4_t; +( +``` + +— comes out with the `;` replaced by `,` (the two imports are folded into +one comma-separated import declaration). Token-level rewrite again. + +- `corpus/ibex/vendor/lowrisc_ip/ip/prim/fpv/tb/prim_alert_rxtx_async_fatal_tb.sv` +- `corpus/ibex/vendor/lowrisc_ip/ip/prim/fpv/tb/prim_alert_rxtx_async_tb.sv` +- `corpus/ibex/vendor/lowrisc_ip/ip/prim/fpv/tb/prim_alert_rxtx_fatal_tb.sv` +- `corpus/ibex/vendor/lowrisc_ip/ip/prim/fpv/tb/prim_alert_rxtx_tb.sv` + +(all four: `input has symbol `;` at 9:27, output has symbol `,` at 8:27`) + +**D. Empty parameter override list dropped (1 file).** An instantiation +written `picorv32 #(\n) uut (` loses the `#()` entirely. + +- `corpus/picorv32/testbench_ez.v` — `input has symbol `#` at 47:11, output has identifier `uut` at 44:12` + +## Findings: crashes (0) + +**No crashes.** No file in the 820 produced an exit status other than +0, 1, or 2 — no signal deaths, no stack overflows, no uncontained +aborts. Two caveats for the recursion-limit work in TODO.md §1: + +- The corpus is real hand-written RTL, which does not nest expressions + ~150 deep; absence of crashes here is *not* evidence the recursion bug + is gone or unreachable. It only says production RTL does not trip it. +- `crash` is a first-class outcome in the script (any exit status outside + {0,1,2}), it is listed per-file like the verification errors, and the + script's own exit status goes to 1 if any appears — so a regression + will show up loudly. Re-running after the recursion limit lands should + stay at zero and may convert a handful of parse errors into a new + "expression nesting too deep" message. + +## Script design notes + +- **`corpus_fetch.sh`** (77 lines): a pipe-delimited table of + `name|url|commit|sparse-paths` drives a `git init` + `git fetch --depth 1 + origin ` + `checkout FETCH_HEAD` per repo. Pinning by SHA rather + than tag means `--depth 1` still works (GitHub allows fetching a + reachable SHA) while nothing can drift. A `.vfmt-corpus-rev` stamp file + makes re-runs a no-op. Only opentitan uses the sparse path — blobless + partial clone plus cone-mode sparse checkout — because it is the only + repo where a full shallow clone would be unreasonable. +- **`corpus_check.sh`** (138 lines): one `vfmt --check ` per file + (820 processes; the whole run is a few seconds, so batching was not + worth the loss of per-file attribution). Per-file classification lives + in one `check_one()` function; everything after it is reporting driven + by `awk`/`sort`/`uniq` over the TSV, so the report can be recomputed + from a saved TSV without re-running vfmt. +- **Why per-file rather than one `vfmt --check corpus/`**: a single + invocation cannot attribute a crash to a file, and its exit code + collapses "would reformat" and "error" into 2. Per-file also means one + pathological file cannot take the run with it. +- **Two error breakdowns, deliberately.** The message histogram + normalizes positions (`L:C:`) and double-quoted literals so the same + diagnostic from 300 files collapses to one row; the *blocking token* + histogram does the opposite and keeps the offending token, because that + is what names the unsupported construct. Backtick-quoted keywords are + never normalized in either. +- **Read-only by construction**: `--check` is the only mode invoked, and + no other vfmt flag is passed. +- **Exit status is meaningful**: 0 = no verification errors and no + crashes; 1 = at least one of either (formatter bug); 2 = usage/setup + error (missing binary, missing corpus, no files found). +- **shellcheck was not available** on this machine (`shellcheck: not + found`, and no package manager path to it without network installs), so + the scripts could not be linted. `bash -n` is clean on both. Both were + written to be shellcheck-friendly anyway: quoted expansions throughout, + no `ls` parsing, and the one intentional word-split carries an inline + `# shellcheck disable=SC2086` with a reason. **Please run shellcheck + once on a machine that has it.** + +## Status / TODO + +- [x] `tools/corpus_fetch.sh` — pinned, shallow, re-runnable clones of + picorv32 / ibex / common_cells / opentitan (uart+gpio sparse) +- [x] `corpus/` and the default `corpus-check-results.tsv` added to + `.gitignore` +- [x] `tools/corpus_check.sh` — per-file outcome classification, summary + table, message histogram, blocking-token histogram, explicit + per-file listing of verification errors and crashes +- [x] Baseline recorded above at vfmt `9f1a6cf` +- [x] Top-10 unsupported constructs mapped against `README.md`'s roadmap, + with an explicit verdict on the priority order +- [x] Every verification-error file listed individually, grouped by root + cause (24 files, 4 root causes) +- [x] Crash sweep — zero found; outcome is first-class in the script +- [x] Confirmed the corpus is unmodified after a run +- [x] TODO.md §5 corpus item checked off +- [ ] **Future: CI integration.** Deliberately not wired up here (network + access in CI is a separate decision, and this must not become part + of `cargo test`). When it happens, ruff's model is the one to copy: + run the check on PR and on base, diff the two TSVs, and fail on a + *regression* in parse-success or on any new verification + error/crash — not on the absolute numbers. The script's exit code + and stable TSV are already shaped for that. +- [ ] **Future: broaden the corpus.** The current four repos are all + lowRISC/PULP-flavoured and contain almost no interfaces, which + makes the interface roadmap item unmeasurable. Candidates: + `pulp-platform/axi` (interface/modport-heavy, SHL), + `chipsalliance/Cores-VeeR-EH1` or `openhwgroup/cva6` (Apache-2.0), + and one Verilog-2001-only project besides picorv32. +- [ ] **Future: per-repo / per-directory summary in the script.** Done + ad hoc with `awk` over the TSV for this report; add flags only if + someone asks twice. +- [ ] **Request to the CLI:** a `--output-format json` (already on + TODO.md §4 for the linter) would let this script classify outcomes + structurally instead of by matching diagnostic text. + +## Work log + +### 2026-08-19 — dev agent + +- Read `CLAUDE.md`, `README.md` (supported-syntax + exit-code table) and + `TODO.md` §5 before starting. Confirmed scope: `tools/**`, `corpus/`, + `.gitignore`, this README, one TODO.md checkbox. Nothing under + `crates/` was modified (another agent is working there); the parser and + formatter sources were read only to learn the exact diagnostic strings + the script matches on. +- Probed the CLI's actual behavior on three synthetic files before + writing anything, to confirm exit 0/1/2 and the `error: : ` + stderr shape rather than assuming them from the README. +- Pinned revisions by querying `git ls-remote` at authoring time. Chose + SHAs over tags for picorv32 and ibex because neither has usable release + tags (ibex's only tags are ancient `pulpino`/`pulpissimo` ones); + common_cells got its real `v1.40.0` tag SHA. OpenTitan was *not* + skipped — a blobless partial clone with a cone sparse checkout of + `hw/ip/uart` and `hw/ip/gpio` makes it cheap (35 files). +- Built vfmt at `9f1a6cf1d2926358e2a804b33fb4de55bb9f04e7` and ran the + check over all 820 files. Verified afterwards that all four corpus + working trees are clean. +- **Key decision — two histograms.** The first run's message histogram + had a useless top row (302 files under ``expected `;` (found "…")``) + because collapsing quoted literals also collapsed the token that + identifies the construct. Rather than un-collapse (which fragments the + buckets on identifiers), added a second histogram over just the `found` + token. That is what produced a usable ranking. +- **Key decision — context-aware categorization for this report.** The + raw token histogram still under-counts macro-item failures, because the + parser sometimes reports the *next* token (`end`, `endmodule`) after a + macro call it could not consume. For the README's category table the + errors were re-bucketed by also reading the three source lines around + each error position. That analysis is ad hoc (`awk` over the TSV), not + baked into the script — it is report-grade heuristics, and the script + stays simple and honest. Consequence: the macro count is reported as a + floor (≥200). +- Sampled and read the actual source line for every category before + naming it, rather than guessing from the token: confirmed `#` is + parameterized class types (`typedef uvm_sequencer#(T) x;`), `]` is + dynamic arrays, `$` is queues (`item_t mbox[$];`), the identifier cases + are user-defined types in declaration position + (`omega_data_t [N-1:0] x;`), and the `` ` `` cases are + `` `ASSERT_INIT(...) ``-style item-position macro calls. +- Inspected the source of one representative file per verification-error + cluster to state root causes rather than just echoing diagnostics; that + is where the four groups (A comma→`or`, B dropped comments, C merged + header imports, D dropped empty `#()`) come from. +- Fixed a real bug in `check_one()` while testing: `status` was a global + that persisted across files when vfmt exited 0 (`|| status=$?` simply + does not fire), so a clean file following an error would have inherited + the previous status. Now reset to 0 per call. +- Deviation from the task brief: none material. `shellcheck` is not + installed on this machine, so the "shellcheck-clean" requirement could + not be verified — noted under Script design notes and left for someone + with the tool. +- Did not run `git commit`/`git push`; did not touch `cargo` or any test. + +## QA log + +### 2026-08-19 — QA agent + +Scope: `tools/corpus_fetch.sh`, `tools/corpus_check.sh`, this README. Did +not touch `crates/` (a concurrent agent has in-flight recursion-limit +changes there — `crates/vlog_parser/src/parser.rs`, +`crates/vfmt/tests/cli.rs`, new `crates/vlog_formatter/tests/deep_nesting.rs`; +left alone, `cargo build --release` only). No commit/push. + +**Pins and corpus (claim 1) — PASS.** `git -C corpus/ rev-parse +HEAD` for all four repos matches the table exactly (picorv32 +`a473fc8f…`, ibex `7b5df75a…`, common_cells `12815456…`, opentitan +`bc1910f4…`). Licenses confirmed by reading the actual files: +`corpus/ibex/LICENSE` (Apache-2.0), `corpus/common_cells/LICENSE` +("SOLDERPAD HARDWARE LICENSE version 0.51"), `corpus/opentitan/LICENSE` +(Apache-2.0), `corpus/picorv32/COPYING` + README (ISC). File counts: +820 total, 41/613/131/35 per repo — exact match. Re-ran +`tools/corpus_fetch.sh corpus`: all four print "already at ``, +skipping", 0.1s wall, no network hit, corpus untouched — the no-op/ +re-runnable claim holds. + +**Re-run vs. baseline (claim 3) — PASS, zero delta.** Built +`target/release/vfmt` from the current tree (recursion-limit changes +in flight but not yet affecting this corpus) and re-ran +`tools/corpus_check.sh corpus`. Result is byte-identical to the +recorded baseline and to the pre-existing `corpus-check-results.tsv` +in the repo root: 1 ok-unchanged, 264 would-reformat, 531 parse-error, +24 verification-error, 0 other-error, 0 crash → 289/820 parsed +(35.2%), 265/820 formattable (32.3%), 1/820 clean. No delta to +investigate — expected, since the corpus is hand-written RTL that +doesn't hit deep expression nesting (README's own caveat under +"Findings: crashes"). + +**Root-cause buckets A–D (claim 4) — PASS, confirmed refusal not +corruption.** Ran `vfmt --check` directly on one file per bucket: +`corpus/common_cells/src/sync.sv` (A, comma→`or`), +`corpus/ibex/rtl/ibex_alu.sv` (B, `// Comparator OPs` dropped), +`corpus/ibex/vendor/lowrisc_ip/ip/prim/fpv/tb/prim_alert_rxtx_tb.sv` +(C, merged imports), `corpus/picorv32/testbench_ez.v` (D, empty `#()` +dropped). All four: exit 2, diagnostic text matches the README +verbatim, and `md5`/`git status --porcelain` before and after show the +file byte-for-byte unchanged on disk — the safety net is doing what +CLAUDE.md's invariant #1 requires. + +**Roadmap analysis (claim 5) — PASS, independently corroborated +(not exact, as expected).** Wrote a standalone script +(context-window heuristic: for each parse-error row, scan the +reported line and 3 lines above for a non-directive `` `NAME( `` +macro call) over the TSV + corpus source: +- Macro-item blocker: 194/531 files by this heuristic (36.5%) vs. the + README's claimed floor of ≥200 (38%); RTL-only 162/260 (62.3%) vs. + claimed 157/260 (60%). Same order of magnitude, same conclusion + (dominant, unlisted blocker); the gap is explained by the README's + own admission that its count used full source reading rather than a + fixed line window, so ≥200 is stated as a floor, not a reproducible + exact figure from the raw TSV. +- `bind`: **28/531 files** by an independent line-window regex + (`^\s*bind\s+\w`) — exact match to the claimed count. +- Dynamic arrays/queues: blocking-token histogram gives `]`=12 + `$`=8 + = 20 — exact match to the claimed count. +- `interface`: raw histogram shows 25 files with + `unsupported construct starting with keyword \`interface\`` as the + *first-error message*, vs. the README's claimed 24 for the combined + interface/modport/clocking category. Off by one — within the + precision the README itself claims for this row (ad hoc, manually + re-bucketed), not a contradiction, but flagging the exact number so + it isn't read as independently reproduced to the digit. + +**Script mechanics — PASS with one confirmed-and-fixed bug.** +- `status` reset (`tools/corpus_check.sh:39`): traced by constructing + a 3-file mini-corpus where a clean file (`b_clean.sv`, would exit 0) + immediately follows a parse-error file (`a_bad.sv`, exit 2) in sort + order. Output correctly shows `ok-unchanged` for `b_clean.sv` — the + `status=0` reset at the top of `check_one()` does fix the + cross-call persistence the work log describes. Confirmed correct. +- Exit-code bucketing (claim 2): would-reformat (exit 1) is correctly + folded into `formatted = ok + reformat` and reported as "parsed & + formattable", matching vfmt's own frozen 0/1/2 contract in the root + `README.md`. Confirmed by direct tests: missing binary → 2, missing + corpus dir → 2, empty corpus (0 files found) → 2, verification-error + present → script exit 1, crash present → script exit 1. +- Crash detection: simulated a SIGSEGV via `-b` pointing at a stub + script that self-signals. Correctly falls into the `*)` case in + `check_one()`, exit status 139, bucketed as `crash`, and the + script's own exit code goes to 1. Confirmed. +- **Gap (not a bug, a documented-but-worth-flagging design choice):** + `other-error` does **not** contribute to the script's own exit + code. Reproduced with a chmod-000 file: vfmt exits 2 with + `Permission denied (os error 13)` on stderr (no `parse error:`/`lex + error:`/`verification failed` marker), `check_one()` correctly + buckets it `other-error`, but `tools/corpus_check.sh`'s own exit + code is **0**. This matches what's written ("Exit status is + meaningful: 0 = no verification errors and no crashes"), so it's + not a bug against the stated contract — but the Assumptions section + also says `other-error` can be "contained panics", and CLAUDE.md's + invariant #1 makes any panic a bug worth CI catching. As written, a + future panic whose message doesn't start with one of the three + known prefixes would land in `other-error` and the script would + still exit 0, silently missing it in the "gate a future CI job" + handshake this script promises. Left as-is (this is a contract + decision for the dev agent / lead, not a QA-agent fix) — flagging + for the CI-integration TODO item. +- Top-20 dedup: confirmed paths are stripped before the message ever + reaches the TSV (in `check_one()`, not in the histogram stage), so + the histogram doesn't need to re-strip them — correct division of + labor. The position-normalizing `sed` in the "top N error messages" + block (`corpus_check.sh:108`) matches `parse error:`/`lex error:` + diagnostics (format `L:C: message`) but **not** + `verification failed: ...` diagnostics, whose embedded positions + read `at L:C,`/`at L:C` (comma or end-of-string, not `: `). Net + effect: the 10 root-cause-A verification errors (comma→`or`) each + show up as their own row in that histogram instead of collapsing + into one bucket of 10, even though they're the same bug. This is + cosmetic only — the dedicated "verification-error (N)" section + right below lists every one individually in full anyway, which is + where the README's own root-cause grouping (A–D) was actually done + from — so no numbers in the report are wrong, just an + opportunity the message histogram doesn't take for this + outcome kind. + +**TSV escaping — found and fixed a real bug (severity: medium).** +The brief specifically asked whether error messages with embedded +tabs/newlines could break the TSV; they can, and did, reproducibly. +Root cause: `impl fmt::Display for Item` in +`crates/vlog_formatter/src/verify.rs` (around line 88) writes the +comment/token text with `{}` (raw), not `{:?}` (Rust's usual +Debug-escaping, which `crates/vlog_parser/src/parser.rs:147` *does* +use for the "found" token — `format!("{} (found {:?})", ...)`, so +that path is already safe). `verify.rs`'s `trim_lines()` only trims +leading/trailing whitespace per comment line and joins with a real +`\n`; nothing escapes an internal tab. Reproduced two ways against a +synthetic 1-file mini-corpus (not the pinned corpus — none of the 24 +real verification errors happen to trip this): + 1. A block comment `/* ab */` in a port list produces a + Divergence diagnostic containing a literal tab. Before the fix, + `check_one()`'s `printf '%s\t%s\t%s\n'` wrote that tab straight + into the message field, producing a **4-field row** instead of + 3 (`awk -F'\t' '{print NF}'` → 4) — a genuine TSV corruption, + not just a display nit. + 2. A 3-line block comment produces a diagnostic with real embedded + newlines; `msg=$(printf '%s\n' "$out" | grep '^error: ' | head + -1)` silently truncates to the diagnostic's first physical line, + dropping the closing `*/`, the reported position, and the + entire "output has ..." half of the message. This one does + *not* corrupt the TSV's row/field count (the truncation happens + before the field is ever written), so it's information loss, not + structural corruption — left as a documented limitation rather + than fixed, since a real fix means deciding how a multi-line + diagnostic should be represented in a single TSV row (join with + literal `\n`? single space? truncate with a marker?), which is a + design call belonging to whoever owns this script's output + format, not a "small unambiguous fix". + Fix applied directly (`tools/corpus_check.sh:44`, in scope for this + feature, does not touch `crates/`): added + `msg=$(printf '%s' "$msg" | tr '\t\n' ' ')` after the existing + prefix-stripping, so any residual tab or newline in the message + becomes a space before the TSV row is printed. Verified: repro (1) + now produces NF=3 with the tab replaced by a space and the message + intact; re-ran the full 820-file corpus after the fix and the + output is **byte-identical** to the pre-fix run (none of the real + diagnostics in this corpus trip the bug), so the fix is safe and + non-disruptive. The underlying `verify.rs` escaping asymmetry is + out of this feature's scope (crates/) and is flagged separately as + a formatter-diagnostics bug, not fixed here. + +**Shellcheck / bash -n — matches documented state.** `shellcheck` is +still not installed on this machine (`which shellcheck` → not found); +`bash -n` is clean on both scripts, before and after the fix above. + +**CLAUDE.md / process compliance — PASS.** All seven required README +sections present (Goal/Assumptions/Handshakes/Status-TODO/Work +log/QA log/Review). `.gitignore` has `/corpus` and +`/corpus-check-results.tsv`. `TODO.md:161` is checked with an honest +inline caveat ("CI wiring is the one part left open") rather than +overclaiming the full original ask. `git status` confirms this +feature's changes are confined to `.gitignore`, `TODO.md`, +`docs/features/corpus-check/`, and `tools/` — nothing under `crates/` +was touched by this feature (the four modified/new `crates/` paths +belong to the concurrent recursion-limit agent). + +**Overall: all five claims PASS.** One real bug found and fixed +in-scope (TSV tab corruption); one related information-loss gap +documented but left unfixed (multi-line diagnostic truncation, needs +a design decision); one exit-code contract gap flagged for the +CI-integration TODO (`other-error` doesn't gate exit status); one +formatter-diagnostics escaping asymmetry flagged out-of-scope for +`crates/vlog_formatter/src/verify.rs` owners. No corpus modification +observed across any run (mine or the pre-existing baseline). No +crashes, before or after the fix, on the real 820-file corpus. + +## Review + +**2026-08-19 — lead. Verdict: accepted and committed; roadmap re-ordered +on this feature's evidence.** + +This is the project's reality check, and it did its job: the "Not yet +supported" roadmap in the top-level README was ordered by intuition and +the corpus proved the intuition wrong. I have re-ordered the README +roadmap as part of this review, per the data: macro invocation at +item/statement position first (≈60% of RTL parse errors), then `bind`, +classes (DV-weighted), dynamic arrays/queues, identifier-typed +declarations — with interfaces demoted from #1 to the tail where the +corpus says it belongs (one RTL file in 820). The four verification-error +root causes (event-list `,`→`or`, dropped comments in port/param lists +and always blocks, merged header imports, dropped empty `#()`) become +the next bug-fix round, with the named corpus files as acceptance +inputs. + +On the work itself: exact SHA pins, license verification, a corpus- +unmodified guarantee, per-file TSV designed for commit-to-commit +diffing, and honest bucketing (refusal ≠ corruption, and the zero-crash +caveat about nesting depth) are all the right calls. QA's re-run being +byte-identical to the baseline is the reproducibility standard every +future corpus run should be held to. The `status` persistence bug the +dev caught itself, and the TSV tab-splitting bug QA caught and fixed +with a proportionate one-line sanitize, both belong in the QA log as +textbook examples of the two roles working. + +Dispositions: + +- **verify.rs `Item::Display` doesn't escape embedded tabs/newlines** + (root cause of the TSV bug): assigned to the next bug-fix round — + print token/comment text with `{:?}` (like the parser's errors do) or + equivalent escaping. +- **`other-error` not gating the script exit** + histogram + normalization miss on `at L:C`: both stay as documented notes for the + CI-integration TODO; neither affects the per-file listing the gating + relies on. +- **shellcheck**: unavailable on this machine; `bash -n` clean and the + scripts are written defensively. Acceptable; run shellcheck + opportunistically when available. diff --git a/tools/corpus_check.sh b/tools/corpus_check.sh new file mode 100755 index 0000000..578b60f --- /dev/null +++ b/tools/corpus_check.sh @@ -0,0 +1,144 @@ +#!/usr/bin/env bash +# Run vfmt over a corpus of real-world RTL and report parse/format health. +# +# This is vfmt's answer to ruff's "ecosystem check": point it at a tree of +# third-party Verilog and it says how much of it we can parse, how much is +# already format-clean, and which errors dominate. It never writes to the +# corpus -- only --check is used. +# +# Usage: tools/corpus_check.sh [corpus-dir] [-o results.tsv] [-t TOP] [-b vfmt] +# +# Exit status: 0 if no verification errors and no crashes were seen, +# 1 otherwise (those two outcomes are always formatter bugs). + +set -eu + +corpus_dir=corpus +vfmt=target/release/vfmt +results=corpus-check-results.tsv +top=20 + +while [ $# -gt 0 ]; do + case $1 in + -o) results=$2; shift 2 ;; + -t) top=$2; shift 2 ;; + -b) vfmt=$2; shift 2 ;; + -*) echo "usage: $0 [corpus-dir] [-o out.tsv] [-t top-n] [-b vfmt-binary]" >&2; exit 2 ;; + *) corpus_dir=$1; shift ;; + esac +done + +[ -x "$vfmt" ] || { echo "no vfmt binary at $vfmt (cargo build --release?)" >&2; exit 2; } +[ -d "$corpus_dir" ] || { echo "no corpus at $corpus_dir (tools/corpus_fetch.sh?)" >&2; exit 2; } + +# Classify one file. vfmt --check exit codes (frozen contract, see README): +# 0 clean, 1 would reformat, 2 error. Anything else is a crash -- a signal +# death (128+n) or an abort the per-file catch_unwind could not contain. +check_one() { + file=$1 + status=0 + out=$("$vfmt" --check "$file" 2>&1) || status=$? + msg=$(printf '%s\n' "$out" | grep '^error: ' | head -1) + msg=${msg#error: } + msg=${msg#"$file": } + # A diagnostic can embed raw source text (e.g. a verification-error's + # comment payload) that itself contains a literal tab or newline -- see + # QA log 2026-08-19. Squash those before the TSV write below, or a stray + # tab silently splits this row into 4+ fields for every downstream + # awk -F'\t'/cut -f consumer. + msg=$(printf '%s' "$msg" | tr '\t\n' ' ') + + case $status in + 0) outcome=ok-unchanged; msg= ;; + 1) outcome=would-reformat; msg= ;; + 2) + case $msg in + *"verification failed"*) outcome=verification-error ;; + "parse error:"*|"lex error:"*) outcome=parse-error ;; + *) outcome=other-error ;; + esac + ;; + *) outcome=crash; msg="exit status $status ${msg:-(no diagnostic)}" ;; + esac + printf '%s\t%s\t%s\n' "$outcome" "$file" "$msg" +} + +echo "vfmt: $vfmt" +echo "corpus: $corpus_dir" +echo + +: >"$results" +find "$corpus_dir" -type f \( -name '*.v' -o -name '*.sv' \) -not -path '*/.git/*' | + sort | + while IFS= read -r f; do + check_one "$f" >>"$results" + # A crash kills the child, not us; keep going so the report is complete. + done + +total=$(wc -l <"$results" | tr -d ' ') +[ "$total" -gt 0 ] || { echo "no .v/.sv files found under $corpus_dir" >&2; exit 2; } + +count() { grep -c "^$1 " "$results" || true; } +pct() { awk -v n="$1" -v d="$2" 'BEGIN { printf "%.1f", d ? 100 * n / d : 0 }'; } + +ok=$(count ok-unchanged) +reformat=$(count would-reformat) +parse=$(count parse-error) +verify=$(count verification-error) +other=$(count other-error) +crash=$(count crash) +formatted=$((ok + reformat)) + +echo "outcome files share" +echo "-------------------- ----- -------" +for pair in "ok-unchanged $ok" "would-reformat $reformat" "parse-error $parse" \ + "verification-error $verify" "other-error $other" "crash $crash"; do + # shellcheck disable=SC2086 # deliberate split of "name count" pairs + set -- $pair + printf '%-20s %5d %5s%%\n' "$1" "$2" "$(pct "$2" "$total")" +done +echo "-------------------- ----- -------" +printf '%-20s %5d %5s%%\n' "total" "$total" 100.0 +echo +echo "parsed & formattable: $formatted/$total ($(pct "$formatted" "$total")%)" +echo "already format-clean: $ok/$total ($(pct "$ok" "$total")%)" +echo " (of formattable: $(pct "$ok" "$formatted")%)" + +# Error breakdown. Source positions are stripped so the same diagnostic from +# different files collapses into one bucket; double-quoted literals are +# collapsed for the same reason (backticked keywords are kept -- they are +# what names the unsupported construct). +echo +echo "top $top error messages (positions and quoted literals normalized):" +awk -F'\t' '$3 != "" { print $3 }' "$results" | + sed -e 's/[0-9][0-9]*:[0-9][0-9]*: /L:C: /' -e 's/"[^"]*"/"…"/g' | + sort | uniq -c | sort -rn | head -"$top" | + awk '{ n = $1; $1 = ""; sub(/^ /, ""); printf "%6d %s\n", n, $0 }' + +# The parser stops at the first error, so each file votes exactly once: this +# is "which token blocks the most files", i.e. the unsupported-construct +# ranking to feed back into README.md's roadmap. +echo +echo "top $top blocking tokens (the \"found\" token of each parse error):" +awk -F'\t' '$3 != "" { print $3 }' "$results" | + sed -n 's/.*(found "\(.*\)").*/\1/p' | + cut -c1-60 | sort | uniq -c | sort -rn | head -"$top" | + awk '{ n = $1; $1 = ""; sub(/^ /, ""); printf "%6d %s\n", n, $0 }' + +# Verification errors and crashes are never "unsupported syntax" -- the +# runtime safety net guarantees equivalence and convergence for anything +# that formats, so each of these is a formatter bug. List them all. +for kind in verification-error crash; do + n=$(count "$kind") + echo + if [ "$n" -eq 0 ]; then + echo "$kind: none" + else + echo "$kind ($n) -- these are formatter bugs, not unsupported syntax:" + awk -F'\t' -v k="$kind" '$1 == k { printf " %s\n %s\n", $2, $3 }' "$results" + fi +done + +echo +echo "per-file results: $results" +[ "$verify" -eq 0 ] && [ "$crash" -eq 0 ] diff --git a/tools/corpus_fetch.sh b/tools/corpus_fetch.sh new file mode 100755 index 0000000..5b97954 --- /dev/null +++ b/tools/corpus_fetch.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# Clone pinned revisions of permissively-licensed open-source RTL into a +# local corpus directory, for tools/corpus_check.sh to run vfmt over. +# +# Every repo is pinned to an exact commit and fetched shallow (--depth 1); +# nothing here ever tracks a moving branch, so corpus numbers recorded in +# docs/features/corpus-check/README.md stay reproducible. +# +# Usage: tools/corpus_fetch.sh [corpus-dir] (default: ./corpus) + +set -eu + +corpus_dir=${1:-corpus} + +# name|url|commit|sparse paths (space separated, empty = whole repo) +# +# Licenses: picorv32 ISC, ibex Apache-2.0, common_cells SHL-0.51, +# opentitan Apache-2.0. All permissive; nothing is redistributed by this +# repo -- corpus/ is gitignored and only ever read. +repos=$( + cat <<'EOF' +picorv32|https://github.com/YosysHQ/picorv32.git|a473fc8fca393771d83b0ffcf0b14db3393339d8| +ibex|https://github.com/lowRISC/ibex.git|7b5df75a041affe56e8c235260f98a09b3319008| +common_cells|https://github.com/pulp-platform/common_cells.git|1281545696eb3fcba50ec5b4275993476a3c710e| +opentitan|https://github.com/lowRISC/opentitan.git|bc1910f4505346dbef000155530fd5a68c60e889|hw/ip/uart hw/ip/gpio +EOF +) + +fetch_one() { + name=$1 + url=$2 + commit=$3 + sparse=$4 + dest="$corpus_dir/$name" + stamp="$dest/.vfmt-corpus-rev" + + if [ -f "$stamp" ] && [ "$(cat "$stamp")" = "$commit" ]; then + echo "== $name: already at $commit, skipping" + return 0 + fi + + echo "== $name: fetching $commit from $url" + rm -rf "$dest" + mkdir -p "$dest" + git -C "$dest" init --quiet + git -C "$dest" remote add origin "$url" + + if [ -n "$sparse" ]; then + # Big repo (opentitan): blobless partial clone + sparse checkout of + # just the subdirectories we care about. + git -C "$dest" config core.sparseCheckout true + git -C "$dest" sparse-checkout init --cone + # shellcheck disable=SC2086 # $sparse is an intentional path list + git -C "$dest" sparse-checkout set $sparse + git -C "$dest" fetch --quiet --depth 1 --filter=blob:none origin "$commit" + else + git -C "$dest" fetch --quiet --depth 1 origin "$commit" + fi + + git -C "$dest" checkout --quiet FETCH_HEAD + echo "$commit" >"$stamp" +} + +mkdir -p "$corpus_dir" + +echo "$repos" | while IFS='|' read -r name url commit sparse; do + [ -n "$name" ] || continue + fetch_one "$name" "$url" "$commit" "$sparse" +done + +echo +echo "corpus in $corpus_dir:" +for d in "$corpus_dir"/*/; do + [ -d "$d" ] || continue + n=$(find "$d" -type f \( -name '*.v' -o -name '*.sv' \) -not -path '*/.git/*' | wc -l | tr -d ' ') + printf ' %-16s %5s .v/.sv files\n' "$(basename "$d")" "$n" +done