369 lines
20 KiB
Markdown
369 lines
20 KiB
Markdown
# mop-up-2
|
||
|
||
## Goal
|
||
|
||
Round-2 mop-up: the last *fixable* parse failures in the 820-file corpus.
|
||
Three unrelated shapes, four files, each one the whole file's blocker:
|
||
|
||
1. **A macro statement that ends its line, followed by a line that starts
|
||
with a symbol** — `` `uvm_info(`gfn, "waiting for rst_n assertion...",
|
||
UVM_MEDIUM) `` ⏎ `@(negedge cfg.clk_rst_vif.rst_n);` (corpus
|
||
`ibex/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_vseq.sv:160`).
|
||
`Parser::at_macro_item` already knew that a macro which ends its line is a
|
||
finished macro item, but only when an *identifier* opened the next line;
|
||
a symbol still read as "the expression continues".
|
||
2. **A shallow copy in expression position** — `instr_h = new
|
||
instr_template[name];` (IEEE 1800 §8.12; corpus
|
||
`ibex/vendor/google_riscv-dv/src/isa/riscv_instr.sv:238`). `new` is not a
|
||
keyword, so the pair parsed as two adjacent names and the statement lost
|
||
its `;`.
|
||
3. **A based number whose digits come from a macro** — `32'h`DM_ADDR`
|
||
(corpus `ibex/dv/uvm/core_ibex/tb/core_ibex_tb_top.sv:75`) and
|
||
`((32'h`BOOT_ADDR & ~(32'h0000_00FF)) | 8'h80)` (corpus
|
||
`ibex/dv/uvm/core_ibex/tests/core_ibex_base_test.sv:142`). The lexer
|
||
refused it with "expected digits after number base", so the file never
|
||
reached the parser.
|
||
|
||
A fourth shape was investigated and deliberately **not** implemented: see
|
||
"`X_EACH_CSR`" under Assumptions.
|
||
|
||
## Assumptions
|
||
|
||
- **A macro that ends its line is a complete macro item, whatever kind of
|
||
token opens the next line.** This is the standing `macro-items` assumption
|
||
(`docs/features/item-misc/README.md`) with the `TokenKind::Symbol` exception
|
||
removed. Guessing wrong still cannot corrupt code — both readings emit the
|
||
same tokens in the same order, so only line breaks differ — but it does move
|
||
where a *parse error* falls. Two shapes that used to parse now do not:
|
||
`` `T `` ⏎ `[3:0] x;` (a macro-named type whose packed dimension opens the
|
||
next line) and `` `MOD `` ⏎ `#(.W(8)) u ();`. Neither appears anywhere in the
|
||
corpus, nobody writes a type on one line and its dimensions on the next, and
|
||
the outcome is a clean exit-2 error with the input untouched, never a
|
||
rewrite. The same-line spellings (`` `T [3:0] x; ``, `` `MOD #(.W(8)) u
|
||
(); ``, `` `LVALUE(x) = 1; ``) are unchanged and pinned by cases and by the
|
||
pre-existing `macro_lookahead_leaves_declarations_alone`.
|
||
- **"Ends its line" means the invocation's *last* line.** The lexer hands a
|
||
whole invocation over as one token, so `` `PACKED(a, `` ⏎ `` b) [3:0] vec; ``
|
||
starts on one line and ends on another; the new `Parser::macro_end_line`
|
||
counts the newlines in the token's text so the `[` is correctly seen as
|
||
standing on the macro's own line. Without this the multi-line declaration
|
||
would have regressed.
|
||
- **`` `M `` ⏎ `(x)` is a macro item followed by a new construct**, not a
|
||
spaced macro call. `Parser::at_spaced_macro_call` already required the `(`
|
||
to be on the macro's line, and the lexer's
|
||
`bare_macro_does_not_swallow_the_next_line` agrees; the new rule just makes
|
||
the *item* reading fire first, which is the same answer.
|
||
- **A shallow copy is `new` followed by a plain identifier on `new`'s own
|
||
line.** `new` stays a non-keyword (`token.rs`'s `is_keyword` explains why),
|
||
so this is a two-token test on an ordinary name. Every other spelling is
|
||
followed by a *symbol* and keeps its old parse: `x = new;` is an `Ident`,
|
||
`x = new(a, b)` a `Call`, `x = new[N]` an `Index` (the reading
|
||
`docs/features/dynamic-types/README.md` pinned), and `new = 1;` is an
|
||
assignment to a variable that happens to be called `new`. The source handle
|
||
is parsed with `parse_postfix`, so `new pkg::t[i].h` works and `new a + b`
|
||
parses as `(new a) + b` — the §8.12 grammar's precedence.
|
||
- **The macro that supplies a number's digits must touch the base.**
|
||
`` 32'h `DM_ADDR `` (with a space) stays the "expected digits after number
|
||
base" lex error it always was: a space there is far more likely a typo than
|
||
this idiom, and the formatter could not print the accepted form back anyway
|
||
— `` 32'h `X `` does not re-lex as a number, so the safety net would reject
|
||
its own output. `` 32'h `` with a non-digit, non-backtick after it is
|
||
likewise still an error.
|
||
- **A number with macro digits is *two* tokens and one expression.** The
|
||
lexer emits `Number("32'h")` then the ordinary macro token; the parser joins
|
||
their text into one `ExprKind::Number`. Splitting in the lexer rather than
|
||
gluing there keeps the "how far does a macro invocation reach" question in
|
||
the one place that already answers it (`scan_macro_args`), and keeps the
|
||
invocation visible as a macro token to anything that walks the stream.
|
||
- **`` `X_EACH_CSR 1 `` (corpus
|
||
`ibex/dv/formal/check/peek/compare_helper.sv:69`) is not fixable and was not
|
||
attempted.** Confirmed the previous dev's conclusion: `` `X_EACH_CSR `` is
|
||
defined in `corpus/ibex/dv/formal/check/top.sv:206` as a chain of `` `X(...)
|
||
`` invocations, and the file-local `` `define X(c) ... && `` makes the
|
||
expansion end in a dangling `&&`, so `` `X_EACH_CSR 1 `` is one expression
|
||
only *after* preprocessing. lucisv deliberately does not read `` `define ``
|
||
bodies from other files, and the only rule that would accept the shape
|
||
without them — "a macro in expression position may be followed by an
|
||
operand" — would have to accept `` `A b `` everywhere, which is exactly the
|
||
`` `TYPE x; `` declaration this parser spends `at_macro_item` telling apart.
|
||
Left failing.
|
||
- **A comment written between `new` and its source handle is not preserved**
|
||
(`a = new /* c */ src;` fails verification, exit 2, input untouched). This
|
||
is not new behavior for this shape: `~ /* c */ x`, `foo /* c */ [3]` and
|
||
`foo /* c */ .bar` all do the same today. `ExprKind::New` deliberately does
|
||
not grow a comment slot none of its siblings has.
|
||
|
||
## Handshakes
|
||
|
||
**Consumed from `vlog_parser::lexer` (unchanged contracts):** `Token::line`,
|
||
`Token::text`, `Token::is_macro()`. `macro_end_line` newly depends on the
|
||
lexer's guarantee that a macro invocation's `text` is the raw source bytes,
|
||
newlines included (`scan_macro_args`) — if that ever changes to a normalized
|
||
text, the end-line count changes with it.
|
||
|
||
**Changed in `vlog_parser::lexer`:** `lex_based_part` may now return a number
|
||
token that ends at the base, with no digits — and only ever when the next
|
||
source byte is a backtick. Anything that assumes a `TokenKind::Number` token
|
||
carries digits must handle it; `Token::is_base_only_number()` is the predicate
|
||
to test with.
|
||
|
||
**New in `vlog_parser::token`:** `Token::is_base_only_number()`.
|
||
|
||
**New AST variant `ExprKind::New(Box<Expr>)`** — a §8.12 shallow copy. The
|
||
payload is the source handle, an ordinary postfix expression.
|
||
|
||
**Exhaustive-match arms added elsewhere for that variant** (minimal, nothing
|
||
beyond what the variant needs):
|
||
|
||
- `crates/vlog_formatter/src/format.rs` — prints `new ` then the payload.
|
||
- `crates/vlog_semantic/src/bind.rs` — `bind_expr` on the payload; the source
|
||
handle names a real variable.
|
||
- `crates/vlog_parser/tests/spans.rs` — `check_expr` on the payload.
|
||
- `crates/vlog_linter/src/visit.rs` needed **no** arm (it ends in a catch-all).
|
||
|
||
**Not touched:** `crates/vlog_formatter/src/verify.rs`. Confirmed by reading
|
||
`lex_stream`/`normalize`: `normalize` passes a `TokenKind::Number` through
|
||
verbatim, and both sides of every construct here lex to the same stream, so no
|
||
normalization was added or widened. The two attack tests this feature adds pin
|
||
the one rewrite it could plausibly have wanted (a space between the base and
|
||
the macro, and gluing `new` to its handle) as *rejected*.
|
||
|
||
**Requests to other features:** none.
|
||
|
||
## Status / TODO
|
||
|
||
- [x] Baseline `scripts/score.sh` captured before any change (796/820).
|
||
- [x] Shape 1 — line-aware `Parser::at_macro_item` for every token kind, with
|
||
`Parser::macro_end_line` for multi-line invocations.
|
||
- [x] Shape 2 — `Parser::at_shallow_copy` + `ExprKind::New`.
|
||
- [x] Shape 3 — `lex_based_part` stops at the base before a backtick;
|
||
`Token::is_base_only_number`; the parser rejoins the pair.
|
||
- [x] Shape 4 — investigated, confirmed unfixable without preprocessing, not
|
||
implemented.
|
||
- [x] Cases: 5 in `tests/cases/macros.cases` (shape 1, where the macro-item
|
||
cases live), 4 in `tests/cases/classes.cases` (shape 2, where the class
|
||
cases live), 3 in `tests/cases/expressions_2.cases` (shape 3, where the
|
||
literal/expression cases live). Negative and edge cases included: the
|
||
same-line spellings that must keep their old parse, a format fence, a
|
||
comment between the macro and the next statement, and the line-length
|
||
boundary.
|
||
- [x] Lexer unit tests (3, two of them negative), parser unit tests (5, two of
|
||
them negative).
|
||
- [x] Safety-net attack tests (2).
|
||
- [x] `cargo fmt --all`, `cargo clippy --all-targets`, `cargo test --workspace`
|
||
all clean.
|
||
- [x] Score re-run; passing set verified as a strict superset of the baseline.
|
||
- [x] `README.md` roadmap and `TODO.md` updated.
|
||
|
||
## Work log
|
||
|
||
### 2026-08-21 — dev
|
||
|
||
**Baseline** (`cargo build --release && scripts/score.sh corpus/`):
|
||
|
||
```
|
||
{"passing":796,"total":820,"pct":97.1,"failures_by_category":{"directive-split":14,"invalid-or-fragment":3,"lex-macro-number":2,"macro-items":2,"other":2,"not-verilog":1}}
|
||
```
|
||
|
||
**After**:
|
||
|
||
```
|
||
{"passing":800,"total":820,"pct":97.6,"failures_by_category":{"directive-split":14,"invalid-or-fragment":3,"macro-items":1,"not-verilog":1,"other":1}}
|
||
```
|
||
|
||
**+4 files, 0 lost.** Verified as a set operation, not a count: `comm -23` on
|
||
the sorted `pass` columns of the before/after `.score-results.tsv` is empty.
|
||
The `lex-macro-number` bucket is gone. Scored after each shape landed
|
||
(797 → 798 → 800) so any regression would have been attributable.
|
||
|
||
Gained: `dv_base_vseq.sv` (shape 1), `riscv_instr.sv` (shape 2),
|
||
`core_ibex_tb_top.sv` and `core_ibex_base_test.sv` (shape 3).
|
||
|
||
**Decisions.**
|
||
|
||
*Shape 1, hoisted rather than patched.* The line test now runs before the
|
||
`match` on the next token's kind instead of inside the `Ident` arm. That is
|
||
behavior-preserving for every arm but `Symbol` (a keyword, a macro, a
|
||
directive and EOF all already answered "the macro stands alone"), and it says
|
||
the rule once instead of twice. The `Symbol` arm keeps its old answer for
|
||
tokens on the macro's *own* line, which is what protects `` `TYPE [3:0] x; ``,
|
||
`` `MACRO(x) = y; `` and `` `MOD #(...) u(); ``.
|
||
|
||
*Shape 1, end line not start line.* `at_macro_item` compared the next token's
|
||
line against `self.cur().line`, which for a macro whose argument list spans
|
||
lines is where the invocation *started*. With the rule now firing on symbols
|
||
too, that would have broken `` `PACKED(a, `` ⏎ `` b) [3:0] vec; ``, so
|
||
`macro_end_line` counts the newlines inside the token's text. The existing
|
||
`Ident` arm is unaffected either way (a multi-line invocation has arguments, so
|
||
`has_macro_args()` had already decided it).
|
||
|
||
*Shape 2, parser not lexer, and `new` still not a keyword.* Promoting `new`
|
||
would have forced a keyword arm in every position it can appear
|
||
(`x = new;`, `super.new()`, `function new;`) for no gain; the whole shape is
|
||
one two-token test in `parse_primary`. The payload is parsed with
|
||
`parse_postfix`, not `parse_expr`, so `new` binds tighter than any operator —
|
||
which is both what §8.12 means and what keeps `new a + b` from swallowing the
|
||
addition.
|
||
|
||
*Shape 3, split in the lexer, joined in the parser.* The alternative was to
|
||
have the lexer glue `` 32'h`DM_ADDR `` into one `Number` token. That needs no
|
||
parser change at all, but it makes the lexer answer "how far does the macro
|
||
invocation reach" a second time, in a second place, and it hides a macro usage
|
||
from anything that walks the token stream (the LSP's `` `define``-expansion
|
||
hover reads macro tokens). Splitting keeps both jobs where they already live.
|
||
The formatter prints the joined text, which is the only spelling that re-lexes
|
||
to the same pair — proven from the other side by the new attack test.
|
||
|
||
*Shape 3, no `verify.rs` change, checked rather than assumed.* Read
|
||
`lex_stream` and `normalize` first: `normalize` returns a `Number`'s text
|
||
verbatim, and both sides lex to `Number("32'h")` + `Ident("`DM_ADDR")`. Better
|
||
than neutral, in fact — if the formatter ever put a space there, the *output*
|
||
would fail to lex and the net would refuse it, which is what
|
||
`spacing_out_a_macro_digit_number_is_rejected` pins.
|
||
|
||
**Files changed.**
|
||
|
||
- `crates/vlog_parser/src/lexer.rs` — `lex_based_part` stops at a base
|
||
followed by a backtick, + 3 tests.
|
||
- `crates/vlog_parser/src/token.rs` — `Token::is_base_only_number`.
|
||
- `crates/vlog_parser/src/parser.rs` — line-aware `at_macro_item`,
|
||
`macro_end_line`, `at_shallow_copy`, the two new `parse_primary` branches,
|
||
+ 5 tests.
|
||
- `crates/vlog_parser/src/ast.rs` — `ExprKind::New(Box<Expr>)`.
|
||
- `crates/vlog_formatter/src/format.rs` — one arm for it.
|
||
- `crates/vlog_semantic/src/bind.rs` — one arm for it.
|
||
- `crates/vlog_parser/tests/spans.rs` — one arm for it.
|
||
- `crates/vlog_formatter/tests/verification.rs` — 2 attack tests.
|
||
- `crates/vlog_formatter/tests/cases/macros.cases` — 5 cases.
|
||
- `crates/vlog_formatter/tests/cases/classes.cases` — 4 cases.
|
||
- `crates/vlog_formatter/tests/cases/expressions_2.cases` — 3 cases.
|
||
- `README.md`, `TODO.md` — documentation.
|
||
|
||
**Still failing, and why.**
|
||
|
||
| file | category | reason |
|
||
|---|---|---|
|
||
| `corpus/ibex/dv/formal/check/peek/compare_helper.sv` | macro-items | `` `X_EACH_CSR 1 `` — needs the macro body, which lives in another file lucisv does not read. See Assumptions. Not mine to fix and not fixable. |
|
||
| `corpus/picorv32/scripts/smtbmc/mulcmp.v` | other | Not in this cluster's scope (deliberately unsupported). |
|
||
|
||
**Gates.** `cargo fmt --all` clean; `cargo clippy --all-targets` clean (no new
|
||
`#[allow]`); `cargo test --workspace` green, 0 failed. No
|
||
`unwrap`/`expect`/`panic!` added outside tests. No `unsafe`. No new dependency.
|
||
|
||
## QA log
|
||
|
||
### 2026-08-21 — round-2 adversarial QA
|
||
|
||
Scope: this feature's own commit (`e35da29`), reviewed together with the
|
||
sibling "Fix round-1 QA findings" commit (`a4f8476`) per the round-2 mandate.
|
||
|
||
**Gates.** `cargo build --release`, `cargo test --workspace` (883 tests, 0
|
||
failed), `cargo clippy --all-targets` (clean, no warnings), `cargo fmt
|
||
--check` (clean). `scripts/score.sh` → 800/820, matching the work log.
|
||
|
||
**Swallowed-error grep.** `git diff 0557933..a4f8476` for `let _ =`, `.ok()`,
|
||
`unwrap_or`, `if let Ok(`, `Err(_) =>`, `_ => {}` inside `crates/`: one hit,
|
||
`tail.strip_prefix(['s','S']).unwrap_or(tail)` in
|
||
`Token::is_base_only_number` (`token.rs`) — a default on a plain string
|
||
strip, not an error path. Nothing swallowed.
|
||
|
||
**Truncated/unbalanced input, all the new grammar surfaces:** `a = new`
|
||
+EOF, `32'h`+EOF, `` 32'h` ``+EOF, `bind /*c`+EOF, `` `randomize() with ``
|
||
+EOF, unbalanced `with {`, unbalanced `with (`, an assertion action block
|
||
with an unclosed `begin`. All eight exit 2 with a clean parse/lex error and
|
||
the input file untouched — no hang, no panic, no partial write.
|
||
|
||
**`32'h`MACRO` join, every shape in the mandate:** unsized (`` 'h`X ``),
|
||
`32'H`, `32'sh`, `` 32'h`X + 1 ``, inside a concatenation and a replication,
|
||
as a port connection, as a parameter default, at EOF with no trailing
|
||
newline — all parse, format and round-trip idempotently. Whitespace between
|
||
base and backtick (`` 32'h `X ``) is a clean lex error, exit 2, input
|
||
untouched, in every position tried. A multi-line string inside the macro's
|
||
argument list (`` 32'h`M("a\nb", c) ``) formats unchanged and idempotently;
|
||
the re-lexed *output* still splits into `Number("32'h")` +
|
||
`Ident("`M(...)")`, so `verify.rs`'s existing string-aware trim on the macro
|
||
`Ident` is what protects it — confirmed by two new attack tests (below), not
|
||
assumed.
|
||
|
||
**`macro_end_line` against multi-line strings:** built three cases where a
|
||
macro's only newlines come from a string argument (closing paren on the
|
||
string's own line, on a later line, and with trailing tokens continuing the
|
||
macro's last line right after the string) — all parse and round-trip
|
||
correctly. `macro_end_line` counts every `\n` byte in the token text
|
||
regardless of string/comment context, which is exactly what `Parser::bump`'s
|
||
line counter does when producing the *next* token's `.line`, so the two never
|
||
disagree; no case was found where this trips.
|
||
|
||
**`verify.rs` re-attack (added, not just reasoned about):** two new tests in
|
||
`crates/vlog_formatter/tests/verification.rs`,
|
||
`a_macro_digit_numbers_multiline_string_may_not_be_reindented` and
|
||
`a_macro_ending_its_line_still_rejects_a_reindented_multiline_string`. Both
|
||
construct an (input, corrupted-output) pair that reindents whitespace inside
|
||
a multi-line string carried by a macro argument — one for the `32'h`MACRO`
|
||
join, one for a macro that ends its own line ahead of an unrelated symbol —
|
||
and both assert `verify_equivalence` rejects it. Both pass without any change
|
||
to `verify.rs`; the feature's claim that this commit needed no net change
|
||
holds up under attack, not just under reading. A third assertion in the same
|
||
test confirms the non-string line break in the same construct is still
|
||
correctly *forgiven* (so the fix isn't just "reject everything").
|
||
|
||
**Mutation fuzz.** Extracted the 19 cases this round added across
|
||
`macros/classes/expressions_2/assertions/bind/dv_statements.cases`. Ran every
|
||
prefix-truncation and every single-character deletion (2231 trials): 0
|
||
crashes, 0 timeouts, every one either a clean exit 0/1 or a clean exit 2.
|
||
Ran a second pass inserting a block comment and a line comment at every
|
||
whitespace/newline gap, wrapping each case in `// lucisv: off` / `// lucisv: on`
|
||
fences, and running `--lines <N>-<N>` for every line (807 trials): same, 0
|
||
crashes.
|
||
|
||
**Whole-corpus idempotency sweep.** All 800 passing corpus files, formatted
|
||
twice via `--stdout` and compared: 0 mismatches. Repeated at `--line-length
|
||
40`, `--indent 4`, and both together: 0 idempotency failures and 0 unexpected
|
||
exit codes (always 0 or 1) across all four sweeps × 800 files.
|
||
|
||
**Printer `fits()` change, isolated.** Built `0557933` (pre-both-commits)
|
||
with only `crates/vlog_formatter/src/printer.rs` replaced by the `a4f8476`
|
||
version, and diffed its output against the unmodified `0557933` binary over
|
||
the *entire* 820-file corpus (not just the 800 that currently pass, since the
|
||
old parser accepts a different set): **0 files differ.** The `fits()` change
|
||
is a no-op for every layout in this corpus that doesn't involve a multi-line
|
||
`Doc::Inline`, which is what the change was scoped to.
|
||
|
||
**Byte-identical-output claim, verified against the correct baseline.**
|
||
Built `e35da29` (this feature's own commit, before the "Fix round-1 QA
|
||
findings" commit) and diffed its output against `a4f8476` over the 800
|
||
currently-passing files: **0 differ**, confirming the sibling commit's "800
|
||
passing files byte-identical against the pre-change binary" claims in the
|
||
assertions/bind READMEs (their baseline is `e35da29`, i.e. this commit, not
|
||
`0557933`).
|
||
|
||
**One thing worth recording, not a defect.** Diffing `0557933` (before
|
||
*either* commit) against `a4f8476` (after both) over the 800 passing files
|
||
shows 7 differences, not 0: 4 are files this commit newly rescues from a
|
||
parse/lex error (expected — see Status/TODO), and 3
|
||
(`corpus/ibex/dv/formal/check/peek/mem.sv`,
|
||
`corpus/ibex/vendor/lowrisc_ip/ip/prim/dv/prim_esc/tb/prim_esc_tb.sv`,
|
||
`corpus/opentitan/hw/ip/uart/dv/env/seq_lib/uart_loopback_vseq.sv`) passed
|
||
*before* this commit too but now format differently. Traced it: `at_macro_item`
|
||
is also called from `take_list_directives`, i.e. its hoisted line rule reaches
|
||
into connection/port-list contexts, not only the module/statement-item case
|
||
the Assumptions section describes. In all three files a macro that expands to
|
||
several named connections stands on its own source line, followed by a
|
||
`.name(...)` connection on the next line; before this commit the parser read
|
||
the two as one continued expression (`` `MACRO ``, then `.name(...)` as a
|
||
dot-postfix on it) and the formatter joined them onto one line, which is
|
||
arguably a misparse of the author's intent. After this commit each is
|
||
correctly read as its own list element, matching the source's own line
|
||
break. Confirmed safe: all three still verify, still round-trip, still
|
||
idempotent — this is a behavior change worth a line in Assumptions (the
|
||
"whatever kind of token opens the next line" rule reaches list-directive
|
||
contexts too, not just item/statement position) but not a bug. Not fixed
|
||
here since it's documentation, outside QA's remit to redesign.
|
||
|
||
**Findings: nothing blocking.** No corruption, no idempotency failure, no
|
||
panic, no swallowed error, and no gap in `verify.rs`'s forgiveness found
|
||
under attack. The one item above is a documentation gap (Assumptions doesn't
|
||
mention the list-directive blast radius), not a code defect.
|
||
|
||
## Review
|