329 lines
19 KiB
Markdown
329 lines
19 KiB
Markdown
# item-misc
|
||
|
||
## Goal
|
||
|
||
Four unrelated shapes that all stand where a **module / generate / class item**
|
||
belongs, and that the corpus loop bucketed into `macro-items` (18 files) and
|
||
`elab-tasks` (9 files). Each was a hard parse error, so each cost a whole file:
|
||
|
||
1. **A macro invocation with a space before its argument list** —
|
||
`` `uvm_field_int (fetch_addr, UVM_DEFAULT) ``. The
|
||
`` `uvm_object_utils_begin … `uvm_field_* … `uvm_object_utils_end `` idiom,
|
||
12 corpus files, e.g.
|
||
`corpus/ibex/dv/uvm/core_ibex/common/ibex_cosim_agent/ibex_ifetch_pmp_seq_item.sv:10`,
|
||
`corpus/ibex/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_env_cfg.sv:66`,
|
||
`corpus/ibex/dv/uvm/icache/dv/env/ibex_icache_env_cfg.sv:24`. Documented as
|
||
a known gap in `docs/features/macro-items/README.md` and assessed-and-parked
|
||
as a *lexer* change in `docs/features/lexer-cleanup/README.md`; this round
|
||
lands it as a *parser* change instead, which is what makes it safe.
|
||
2. **A bare macro invocation that ends its line, followed by an ordinary
|
||
declaration** — `` `uvm_component_new `` ⏎ ⏎ `uvm_report_server rs;`.
|
||
4 corpus files: `corpus/ibex/dv/uvm/core_ibex/tests/core_ibex_test_lib.sv:19`,
|
||
`corpus/ibex/vendor/lowrisc_ip/dv/sv/push_pull_agent/push_pull_agent_cov.sv:35`,
|
||
`corpus/ibex/dv/uvm/icache/dv/ibex_icache_core_agent/ibex_icache_core_sequencer.sv:13`,
|
||
`corpus/ibex/dv/uvm/icache/dv/ibex_icache_core_agent/seq_lib/ibex_icache_core_base_seq.sv:17`.
|
||
The old one-token lookahead read the pair as one macro-typed declaration
|
||
(`` `uvm_component_new uvm_report_server ``) and then choked on the
|
||
declarator.
|
||
3. **`` `error "message" ``** as a compiler directive at item position —
|
||
`corpus/picorv32/picosoc/icebreaker.v:21`,
|
||
`corpus/picorv32/picosoc/picosoc.v:22`, both inside an `` `ifdef``.
|
||
4. **Elaboration system tasks as items** — `$error(...)`, `$fatal(...)`,
|
||
`$warning(...)`, `$info(...)` with a `;`, at module scope and inside
|
||
generate `if`/`for`/`case`/`begin…end`. 9 corpus files:
|
||
`corpus/common_cells/src/clk_int_div.sv:109` (inside
|
||
`if (...) begin : gen_elab_error`), `corpus/common_cells/src/popcount.sv:31`
|
||
(a generate-`if` whose entire body is a bare system task, no `begin`/`end`),
|
||
`corpus/common_cells/src/cdc_2phase_clearable.sv:93` and
|
||
`corpus/common_cells/src/cdc_fifo_gray_clearable.sv:153` (two string
|
||
literals as separate arguments across lines),
|
||
`corpus/common_cells/src/deprecated/clk_div.sv:45` (`$warning(` with the
|
||
arguments starting on the next line),
|
||
`corpus/common_cells/src/stream_arbiter_flushable.sv:78` (inside
|
||
`` `ifndef SYNTHESIS `` inside a generate case item),
|
||
`corpus/ibex/rtl/ibex_top_tracing.sv:136` (inside `` `ifndef RVFI `` at
|
||
module scope), `corpus/common_cells/src/clk_int_div_static.sv:71`,
|
||
`corpus/common_cells/src/clk_mux_glitch_free.sv:92`.
|
||
|
||
## Assumptions
|
||
|
||
- **A spaced macro invocation is still opaque text, and the space is part of
|
||
it.** The formatter reproduces `` `uvm_field_int (a, b) `` byte-for-byte
|
||
rather than tightening it to the canonical `` `uvm_field_int(a, b) ``. This
|
||
is *not* a style preference — it is forced. The lexer delivers a glued
|
||
invocation as **one** `Ident` token whose text is the whole call, so
|
||
`` `A (x) `` (two-plus tokens) and `` `A(x) `` (one token, text `` `A(x) ``)
|
||
are different token streams. Removing the space would make the output's
|
||
stream differ from the input's, and `verify.rs` — which this feature must not
|
||
and does not touch — would rightly refuse the result. Proven in both
|
||
directions by `tightening_a_spaced_macro_call_is_rejected` and
|
||
`loosening_a_glued_macro_call_is_rejected` in
|
||
`crates/vlog_formatter/tests/verification.rs`. The ruff-like answer (one
|
||
canonical spelling) is reachable only from inside the safety net, which is
|
||
the lead's call, not this round's.
|
||
- **The spaced reading is offered at item and statement position only, never
|
||
in an expression.** `assign x = `A (b);` keeps today's parse
|
||
(`ExprKind::Call`). `docs/features/lexer-cleanup/README.md` established why:
|
||
whether `(b)` is `` `A ``'s argument list or an independent parenthesized
|
||
value depends on whether the macro was `` `define``d with formals (IEEE 1800
|
||
§22.5.1), and that definition routinely lives in an `` `include``d file lucisv
|
||
never reads — `` `define NOT ~ `` plus `` `NOT (a) `` is the counterexample.
|
||
At *item* position that ambiguity does not exist: neither reading is a legal
|
||
item on its own, so accepting the invocation cannot take a valid parse away
|
||
from anything. That asymmetry is the whole reason this landed in the parser
|
||
and not in the lexer, where it was correctly parked.
|
||
- **The `(` must be on the macro's own line.** A `(` opening the next line is
|
||
far more likely the start of a separate construct, and the lexer already
|
||
guards the glued case the same way (`bare_macro_does_not_swallow_the_next_line`).
|
||
- **A macro that ends its line is a complete macro.** A type and its declarator
|
||
are written together (`` `MY_TYPE_T sig; ``); nobody writes the type on one
|
||
line and the declarator on the next. Guessing wrong here still cannot corrupt
|
||
code — both readings emit the same tokens in the same order, so only line
|
||
breaks differ (the standing `macro-items` argument).
|
||
- **`` `error`` / `` `warning`` are a closed two-name addition to the directive
|
||
list, not a general "unknown backtick name is a directive" rule.** The
|
||
opposite rule would swallow every macro invocation in the corpus. The price
|
||
of the closed list is that a *macro* actually named `` `error`` would now be
|
||
read as a directive; no such macro exists in the corpus (checked: the only
|
||
`` `error``/`` `warning`` occurrences are the two directives above), and IEEE
|
||
1800 §22.8 reserves the names.
|
||
- **`$display` at item position stays an error.** Only the four elaboration
|
||
tasks of IEEE 1800 §20.11 (`$fatal`, `$error`, `$warning`, `$info`) may stand
|
||
where an item does; `$display` is legal only inside a procedural block, and
|
||
accepting it would turn a real error into silent acceptance.
|
||
- **An elaboration task's arguments are an ordinary expression list.** The
|
||
adjacent-string-literal "concatenation by juxtaposition" the corpus uses is
|
||
not juxtaposition at all — the strings are separate `,`-separated arguments —
|
||
so nothing special is needed for it.
|
||
- **An elaboration task item requires its `;`.** `$error` with no parentheses
|
||
and no semicolon is legal LRM-wise but appears nowhere; requiring the `;`
|
||
keeps a missing one an error rather than a silent re-parse.
|
||
|
||
## Handshakes
|
||
|
||
**Consumed from `vlog_parser::lexer`:** unchanged contracts —
|
||
`Token::is_macro()` / `Token::has_macro_args()`, and `Token::line`, which is
|
||
what makes the "ends its line" rule expressible. The one lexer change is two
|
||
names added to `is_line_directive` (`error`, `warning`); anything that
|
||
enumerates directives by name should know the list grew.
|
||
|
||
**Consumed from `vlog_parser::parser` internals (used, not changed):**
|
||
`Parser::skip_balanced` and `Parser::verbatim_since` — the same pair
|
||
`parse_constraint`/`parse_covergroup` use to lift verbatim source by span. The
|
||
spaced invocation is rebuilt from the source bytes with them, which is why
|
||
`RawText.col` still points at the backtick and the existing `Fmt::raw_lines`
|
||
dedent/re-indent contract keeps working for a multi-line spaced call.
|
||
|
||
**Promised to `vlog_formatter`:**
|
||
|
||
- `ItemKind::MacroItem(MacroCall)` may now carry a `raw.text` that contains a
|
||
space (or a comment, or a newline) between the macro name and its `(`. The
|
||
existing "print `raw_text(&call.raw)` verbatim" handling is already correct
|
||
for it; nothing must re-space it.
|
||
- **New AST variant `ItemKind::ElabTask(Expr)`** — an elaboration system task
|
||
standing where a module or generate item belongs. The payload is the ordinary
|
||
system-task-call expression, so the formatter prints it exactly like
|
||
`StmtKind::ExprStmt`: `concat([self.expr(e), text(";")])`. Its argument group
|
||
is the existing breakable call group.
|
||
|
||
**Exhaustive-match arms added elsewhere for that new variant** (minimal, no
|
||
behavior beyond what the variant needs):
|
||
|
||
- `crates/vlog_formatter/src/format.rs` — prints it like a statement.
|
||
- `crates/vlog_semantic/src/bind.rs` — `bind_expr` on the payload, because the
|
||
arguments name real parameters (`$error("...", DIV_VALUE_WIDTH)`).
|
||
- `crates/vlog_parser/tests/spans.rs` — `check_expr` on the payload.
|
||
- `crates/vlog_linter/src/visit.rs` needed **no** arm (it already ends in a
|
||
catch-all); no lint rule looks at elaboration tasks.
|
||
|
||
**Not touched:** `crates/vlog_formatter/src/verify.rs`. No normalization was
|
||
added or widened, so the "guilty until proven innocent" clause of CLAUDE.md
|
||
does not fire. The two verification tests this feature adds are *attack* tests
|
||
in the same spirit — they assert the net still rejects the one rewrite this
|
||
feature could plausibly have wanted to make.
|
||
|
||
**Requests to other features (out of scope here, not acted on):** none. The two
|
||
files that advanced past this feature's constructs into other categories are
|
||
listed in the work log for whoever owns those buckets.
|
||
|
||
## Status / TODO
|
||
|
||
- [x] Baseline `scripts/score.sh` captured before any change.
|
||
- [x] Shape 1 — spaced macro invocation at item/statement position
|
||
(`Parser::at_spaced_macro_call`, `Parser::parse_macro_call`).
|
||
- [x] Shape 1 — expression position deliberately unchanged, with a parser test
|
||
pinning it.
|
||
- [x] Shape 2 — line-aware `Parser::at_macro_item`.
|
||
- [x] Shape 3 — `` `error`` / `` `warning`` added to `is_line_directive`.
|
||
- [x] Shape 4 — `ItemKind::ElabTask(Expr)`, parsed at item position, printed
|
||
like a statement.
|
||
- [x] Cases: 8 in `crates/vlog_formatter/tests/cases/macros.cases` (shapes 1–2,
|
||
where the existing macro-item cases live), 11 in the new
|
||
`crates/vlog_formatter/tests/cases/item_misc.cases` (shapes 3–4).
|
||
Negative/edge cases included: both constructs inside a
|
||
`// verilog_format: off` fence, comments attached above and trailing, and
|
||
the 100-column boundary in both directions.
|
||
- [x] Parser unit tests (6) and lexer unit tests (2).
|
||
- [x] Safety-net attack tests (2) for the space-tightening rewrite.
|
||
- [x] `cargo fmt --all`, `cargo clippy --all-targets`, `cargo test --workspace`
|
||
all clean.
|
||
- [x] Score re-run; passing set is a strict superset of the baseline.
|
||
- [x] `README.md` "Supported syntax" and the roadmap list updated.
|
||
- [x] `TODO.md` note about the macro-items lexer gap updated.
|
||
|
||
## Work log
|
||
|
||
### 2026-08-20 — dev
|
||
|
||
**Baseline** (`cargo build --release && scripts/score.sh`):
|
||
|
||
```
|
||
{"passing":636,"total":820,"pct":77.6,"failures_by_category":{"interface":31,"bind":28,"dv-statements":24,"expressions":18,"macro-items":18,"directive-split":14,"assertions":13,"dpi-export":11,"types-decls":11,"elab-tasks":9,"invalid-or-fragment":3,"lex-macro-number":2,"not-verilog":1,"other":1}}
|
||
```
|
||
|
||
**After**:
|
||
|
||
```
|
||
{"passing":661,"total":820,"pct":80.6,"failures_by_category":{"interface":31,"bind":28,"dv-statements":25,"expressions":19,"directive-split":14,"assertions":13,"dpi-export":11,"types-decls":11,"invalid-or-fragment":3,"lex-macro-number":2,"not-verilog":1,"other":1}}
|
||
```
|
||
|
||
**+25 files, 0 lost.** `macro-items` and `elab-tasks` are both gone from the
|
||
bucket list. Verified as a set operation, not just as a count: the passing
|
||
file list before is a strict subset of the list after (`comm -23` on the two
|
||
sorted `pass` columns of `.score-results.tsv` is empty).
|
||
|
||
25 of the 27 files in the two categories now pass end to end. The other 2
|
||
advanced to a **new first error in a different category** — progress, and
|
||
neither is mine to fix:
|
||
|
||
| file | was | now |
|
||
|---|---|---|
|
||
| `corpus/common_cells/src/cdc_fifo_gray_clearable.sv` | `elab-tasks` 153:5 `$error` | `expressions` 182:5 `expected expression (found "(* async *)")` |
|
||
| `corpus/ibex/dv/uvm/core_ibex/tests/core_ibex_test_lib.sv` | `macro-items` 19:21 `expected ';' (found "rs")` | `dv-statements` 483:29 `expected ')' (found "[")` |
|
||
|
||
(That is where the `dv-statements` 24→25 and `expressions` 18→19 deltas come
|
||
from — both are files arriving from my buckets, not regressions.)
|
||
|
||
**Decisions.**
|
||
|
||
*Shape 1, parser not lexer.* `docs/features/lexer-cleanup/README.md` assessed
|
||
the lexer glue and parked it, correctly: in expression position the reading
|
||
depends on a `` `define`` lucisv cannot see. That analysis is entirely about
|
||
expression position, so the fix is the same predicate applied only where an
|
||
item or a statement belongs. `Parser::at_spaced_macro_call` is deliberately a
|
||
*separate* predicate from `at_macro_item` rather than a clause inside it,
|
||
because `at_macro_item` is also what `take_list_directives` uses to spot a
|
||
macro standing between port/parameter list elements — folding the spaced case
|
||
in there would have had that loop consume the bare name and leave the `(`
|
||
behind, turning a clean error into a mis-parse. `parse_macro_call` grew a
|
||
`PResult` return for `skip_balanced`'s sake.
|
||
|
||
*Shape 1, space preserved.* Removing it is the ruff-like choice and I did not
|
||
take it, because it is a token-text rewrite the safety net refuses and
|
||
`verify.rs` is off limits this round (and should stay off limits for this: the
|
||
normalization that would forgive it — "ignore whitespace between a macro name
|
||
and its `(`" — is exactly the kind of widening CLAUDE.md invariant 4 is about).
|
||
Two attack tests now pin both directions of the rewrite as rejected. Preserving
|
||
also keeps the round consistent with the standing `macro-items` assumption that
|
||
an invocation is reproduced byte-for-byte. Idempotency is trivially fine: the
|
||
output *is* the input bytes.
|
||
|
||
*Shape 2, line-awareness in `at_macro_item` itself.* Here the change does
|
||
belong in the shared predicate — "a macro that ends its line is finished" is
|
||
true at list position too. Checked against the corpus rather than argued: the
|
||
passing set stayed a superset, and `macro_lookahead_leaves_declarations_alone`
|
||
(the existing test pinning `` `MY_TYPE_T sig; ``, `` `MY_MODULE u_inst (...) ``
|
||
and friends) still passes untouched, because each of those writes the macro and
|
||
what follows on one line. A comment line between the macro and the declaration
|
||
changes nothing — comments are trivia on the token, so the declarator token's
|
||
`line` is still a later line.
|
||
|
||
*Shape 3, closed list.* Two names, `error` and `warning`, added to
|
||
`is_line_directive` with a comment saying why the list must stay closed. Grepped
|
||
the corpus first: the only `` `error``/`` `warning`` occurrences anywhere are
|
||
the two real directives. A lexer test pins that `` `error_if(x) `` is still a
|
||
macro, i.e. that the match is on the exact word and not a prefix.
|
||
|
||
*Shape 4, one new item kind.* `ItemKind::ElabTask(Expr)` wrapping the existing
|
||
system-task-call expression, gated on a closed four-name list. No new statement
|
||
kind and no new expression machinery: `parse_expr` already parses
|
||
`$error("a", "b")` as a `Call`, and the generate-block parser already falls
|
||
through to `item_or_recover()` for a body with no `begin`/`end`, so
|
||
`if (W < 1) $error(...);` (popcount.sv) works with no generate-side change at
|
||
all. Formatting is `expr` + `";"`, byte-identical to how `StmtKind::ExprStmt`
|
||
prints — which means the argument list is the existing breakable call group and
|
||
the 100-column behavior is inherited rather than invented (both boundary
|
||
directions are pinned in `item_misc.cases`).
|
||
|
||
**Files changed.**
|
||
|
||
- `crates/vlog_parser/src/lexer.rs` — `error`/`warning` in `is_line_directive`
|
||
+ 2 tests.
|
||
- `crates/vlog_parser/src/parser.rs` — `ELAB_TASKS`, line-aware
|
||
`at_macro_item`, new `at_spaced_macro_call`, `parse_macro_call` rebuilds a
|
||
spaced invocation verbatim, `parse_item_kind` accepts an elaboration task
|
||
+ 6 tests.
|
||
- `crates/vlog_parser/src/ast.rs` — `ItemKind::ElabTask(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` — 8 cases.
|
||
- `crates/vlog_formatter/tests/cases/item_misc.cases` — new, 11 cases.
|
||
- `README.md`, `TODO.md` — documentation.
|
||
|
||
**Gates.** `cargo fmt --all` clean; `cargo clippy --all-targets` clean (no new
|
||
`#[allow]`); `cargo test --workspace` green, 28 test binaries, 0 failed. No
|
||
`unwrap`/`expect`/`panic!` added outside tests. No `unsafe`. No new dependency.
|
||
|
||
## QA log
|
||
|
||
### 2026-08-21 — round-1 adversarial QA
|
||
|
||
Verified: `cargo test --workspace`, `cargo clippy --all-targets`, `cargo fmt
|
||
--check` all clean. `scripts/score.sh` reports 796/820 as expected. Ran a
|
||
whole-corpus sweep (all 796 passing files, `--stdout` twice + `cmp`, plus a
|
||
comment-multiset diff of input vs output): 0 crashes, 0 idempotency breaks, 0
|
||
comment losses (one file had a trailing-whitespace-inside-comment trim, which
|
||
is an existing, benign normalization, not a loss of content). Ran a 476-case
|
||
mutation fuzz (delete `;`, delete `(`/`)`, comments jammed into every gap,
|
||
`// verilog_format: off` fence-wrap) over 3 examples from every new `.cases`
|
||
file × `{plain, --lines 1-999, --indent 4, --line-length 40}`: 0 panics, 0
|
||
hangs, 0 unexpected exit codes, 0 idempotency breaks.
|
||
|
||
Targeted attacks from the hit-list:
|
||
|
||
- **Shared `at_macro_item` predicate misused at list position** (parser.rs
|
||
`take_list_directives` / port-param lists). Tried a macro-typed port/param
|
||
split across lines inside `#( ... )` and `( ... )` (`` `WIDTH_T`` / ⏎ /
|
||
`parameter x = 1`), a macro-with-args followed by an identifier on the same
|
||
line (`` `WIDTH_T(8) portname``), nested macro args, etc. Every wrong guess
|
||
either reproduced the same tokens (formats fine, idempotent) or was caught
|
||
by `verify_equivalence`/the parser and cleanly rejected (exit 2, zero bytes
|
||
on stdout) — never corrupted. Confirms the doc comment's claim on parser.rs
|
||
around line 860 ("guessing wrong cannot corrupt code").
|
||
|
||
- **`` `error``/`` `warning`` as permanent line directives.** Confirmed: if a
|
||
project `` `define``s its own `error(msg)`/`warning(msg)` macro and calls
|
||
it, the call is lexed as a line directive (`is_line_directive`,
|
||
lexer.rs:685), so the *rest of the physical line* becomes directive text.
|
||
Repro: `` `define error(msg) $display(msg)`` then
|
||
`` `error("oops"); x = 1 ;`` **on one line** — the badly-spaced
|
||
`x = 1;` right after the macro call is never touched by the formatter
|
||
(byte-identical in and out), because it's inside the directive's
|
||
verbatim-to-EOL span. When the macro call and the next statement are on
|
||
separate lines (the overwhelmingly common real-world layout — see
|
||
`errmacro4.sv` in scratchpad), formatting of the next statement is
|
||
unaffected. Not corruption (output is a no-op, still valid, idempotent, no
|
||
comments lost), not a parser crash — just a silent "skip formatting this"
|
||
for the rare same-line case. **NON-BLOCKING**: a real gap for projects that
|
||
shadow `` `error``/`` `warning`` as user macros with same-line follow-on
|
||
statements, but no invariant is broken.
|
||
|
||
- **Spaced macro calls (`` `M (a) ``) verbatim capture, including a comment
|
||
between name and `(`.** `` `uvm_field_int /* c */ (fetch_addr,
|
||
UVM_DEFAULT)`` round-trips byte-identical and is idempotent.
|
||
|
||
No BLOCKING findings for this cluster.
|
||
|