Files
lucisv/docs/features/assertions/README.md
T

429 lines
24 KiB
Markdown

# assertions
## Goal
Parse and emit SystemVerilog **concurrent assertions** (IEEE 1800-2017 §16)
and the two declarations they use, so the `assertions` bucket of
`scripts/score.sh` — 13 corpus files, the fourth-largest blocker at the start
of this round — stops being a parse error. The lead's decision, taken before
any code was written, is that all of it is **verbatim pass-through**, exactly
like `constraint { ... }` and `covergroup ... endgroup` already are: the
property/sequence expression grammar (`|->`, `|=>`, `##[1:3]`, `[*2]`,
`throughout`, `disable iff`, `$rose`, `$past`) is a second language that lucisv
models nowhere else, and there is no layout convention worth inventing for it.
The payoff of a hand-rolled property grammar would be zero; the risk — a new
place to drop a token — would be real.
## What is captured, and where the evidence is
Every shape below is taken from a corpus file, named so the next reader can
check the evidence rather than the reasoning.
| shape | corpus evidence |
|---|---|
| `assert property ( ... );` at module scope | `common_cells/test/cdc_fifo_tb.sv:42-45`, `cdc_fifo_clearable_tb.sv:47-50` |
| `assume property (@(posedge clk) ... );` | `common_cells/formal/counter_properties.sv:38`, `fall_through_register_properties.sv:36`, `fifo_v3_properties.sv:61` |
| a property spec spanning several lines (`disable iff` on its own line) | `counter_properties.sv:48-50` |
| `restrict property ( ... );` | `picorv32/picorv32.v:2109,2112` |
| `cover property ( ... );` | taken with the other three — one keyword list, `picorv32.v:2115` has it commented out |
| `<label>: assume property ( ... );` at **file** scope | `ibex/dv/formal/check/protocol/irqs.sv:12-13` |
| a labeled assertion whose spec spans lines | `ibex/dv/formal/check/peek/mem.sv:32-34` |
| `assert property ( ... ) else $error("...");` at item position inside a generate `begin` | `common_cells/test/fifo_tb.sv:155-156` |
| label + `else` action, inside a generate `for` | `common_cells/test/clk_int_div_static_tb.sv:62-63` |
| `sequence <name>; ... endsequence` | `lowrisc_ip/ip/prim/rtl/prim_alert_sender.sv:305-310`, `prim_alert_rxtx_assert_fpv.sv:58`, `prim_alert_rxtx_async_assert_fpv.sv:91` |
| `property <name>(args); <local decls> ... endproperty [: name]` | `common_cells/test/clk_int_div_static_tb.sv:40-47` |
Taken for completeness, without corpus evidence, because they are the rest of
the same two grammar rules and cost nothing:
- statement position (`assert property (...)` inside an `initial begin`) —
concurrent assertions are legal wherever a statement is. The one corpus
occurrence that *looked* like this (`fifo_tb.sv:155`) turned out to sit in a
generate `if ... begin`, i.e. item position; the statement path is pinned by
a case and a parser test instead.
- the pass half of an action block (`assert property (p) $info("y"); else
$error("n");`) and a `begin ... end` action block.
## Assumptions
- **The `property` keyword is the whole disambiguator.** `at_concurrent_
assertion` fires only on `[ident :] (assert|assume|cover|restrict)
property`. That is what keeps the *immediate* assertion path — `assert
(expr) stmt else stmt;`, a real `StmtKind::Assert` node with canonical
layout — byte-for-byte unchanged, and it is why a label in front of an
immediate assertion (`check_decode: assert (x) ...`, the dv-statements
cluster's problem) is not pre-empted here.
- **`restrict` is deliberately *not* promoted to a lexer keyword.** It reaches
the item dispatch as an ordinary identifier and is matched by text, only
when the very next token is the `property` keyword. Adding it to
`token.rs`'s keyword list would have changed the lexing of every
Verilog-2001 file that uses `restrict` as a signal or type name, for no gain.
- **`expect property` and `cover sequence` are not implemented.** Neither
appears in the corpus, and both would be a guess at an action-block shape
nothing exercises. They still error out, as before.
- **`default clocking` / `default disable iff` are not implemented.** Clocking
blocks are the `interface` cluster's (`ibex/dv/formal/check/top.sv:143` is
categorized there). `default` at item position is left untouched by this
work.
- **A verbatim block's *relative* layout is what survives, not its absolute
indent.** Only the first line is re-indented to the item's level; the
continuation lines are dedented by the block's original start column and the
printer indents them back — the same fixed-point trick `constraint` uses
(`Fmt::raw_lines`). A property spec written entirely at column 1 comes out
entirely at the item's indent, relative shape intact.
- **A verbatim block is never reflowed to the line limit.** A 130-column
property expression stays 130 columns. There is no grammar to break it on.
Pinned by the last case in `assertions.cases`.
## Handshakes
### Consumed
- `Parser::verbatim_since(start, col)` (from the classes round) — slices
`source[span]` into a `RawText` and drops the comments the capture
swallowed, so a comment *inside* an assertion prints once and a comment
*after* its `;` stays pending for the next node. Used unchanged.
- `Parser::skip_balanced(open, close)` — used for the property spec's parens
and for brackets inside an action block.
- `Fmt::raw_text(raw)` — prints a `RawText` re-indented, **except** when
`crosses_line_inside_string` says a line break falls inside a string
literal, in which case the text is emitted as one `Doc::Text` and the
printer copies the newlines through without touching them. This is what
makes a multi-line string inside `else $error("...")` byte-identical, and it
needed no change. `verify.rs::line_starts_inside_string` is the shared
reading of "which line breaks are data" that the safety net uses on the
other side of the same question.
### Promised / changed for others
- **New AST variant `StmtKind::Verbatim(RawText)`** (`vlog_parser/src/ast.rs`)
— the statement-level twin of `ItemKind::Verbatim`, for a concurrent
assertion in statement position. Minimal arms added:
- `vlog_formatter/src/format.rs`: `StmtKind::Verbatim(raw) =>
self.raw_text(raw)`.
- `vlog_semantic/src/bind.rs:955`: folded into the no-op group next to
`StmtKind::Directive`/`MacroStmt` — verbatim source is opaque to name
resolution, exactly as `ItemKind::Verbatim` already is at
`bind.rs:306`.
- `vlog_parser/tests/spans.rs`: folded into the `Directive | MacroStmt`
raw-text arm.
- `vlog_linter/src/visit.rs` needed **no** arm — `walk_stmts` ends in a
`_ => {}`.
- **`ItemKind::Verbatim` gained a third and fourth producer** (concurrent
assertions, `property`/`sequence` declarations). No signature changed; every
existing consumer already treats it as an opaque leaf.
- **No change to `crates/vlog_formatter/src/verify.rs`.** No forgiveness was
widened. The attack tests below exist anyway, per CLAUDE.md invariant #4,
because the capture is forgiveness-*adjacent*: a verbatim block is re-lexed
as ordinary tokens on both sides, so every token inside it must still match.
### Requests to other clusters
- **interface cluster**: `assert property` inside an `interface` body cannot
be tested yet — `interface` itself is still a parse error
(`unsupported construct starting with keyword \`interface\``). Once an
interface body parses through the ordinary item path
(`Parser::parse_item_kind`), concurrent assertions inside it work with no
further change, because that is the same dispatch module bodies use. Worth
one case in `interface.cases` when that lands.
- **dv-statements cluster**: if you add a general `label:` prefix for
*statements*, note that `Parser::parse_stmt_kind` already consults
`at_concurrent_assertion()` before the keyword dispatch, and that check
consumes `ident :` itself when a `property` keyword follows. Keep the
general label path from firing on `[label:] assert property`, or the
assertion will be split in two.
- **linter**: AST-driven rules do not descend into a verbatim assertion — a
`case` written inside an action block's `begin ... end` would not be seen by
`case-missing-default`. This is the pre-existing posture for `constraint`
and `covergroup` and is left as is; the text-driven rules (`no-tabs`,
`no-trailing-whitespace`) still fire inside these blocks, verified by hand.
## Status / TODO
- [x] Baseline `scripts/score.sh` recorded and TSV saved before any edit.
- [x] AST: `StmtKind::Verbatim(RawText)`; doc comment on `ItemKind::Verbatim`
widened to name its two new producers.
- [x] Parser: `at_concurrent_assertion`, `parse_concurrent_assertion`,
`skip_action_block`, `skip_action_stmt`, `parse_property_decl`.
- [x] Parser dispatch: `parse_keyword_item` (`assert`/`assume`/`cover` behind
the guard, `property`/`sequence`), `parse_item_kind`'s `Ident` arm
(labels and `restrict`), `parse_stmt_kind` (statement position).
- [x] Formatter: one arm, `StmtKind::Verbatim(raw) => self.raw_text(raw)`.
- [x] Downstream exhaustive matches: `bind.rs`, `spans.rs`.
- [x] 19 cases in `crates/vlog_formatter/tests/cases/assertions.cases`, one
per corpus shape cited above plus: comments before/after, a comment
*inside* the capture, a `// verilog_format: off` fence, a multi-line
string in an action block, the immediate-assertion negative case, and a
past-the-line-limit spec.
- [x] 11 parser unit tests in `parser.rs`, including the four keywords, the
label form, both action-block halves, the `begin`/`end` action block,
statement position, the immediate-assertion negative case, and an
unterminated `property` erroring rather than swallowing the file.
- [x] 12 invariant-#4 attack tests in
`crates/vlog_formatter/tests/verification.rs`.
- [x] `cargo fmt --all`, `cargo clippy --all-targets`, `cargo test` (whole
workspace) all clean.
- [x] Idempotency swept by hand over all 712 passing corpus files, not just
the 13 new ones.
- [x] QA round-1: `skip_action_stmt` tracks `begin`/`end`, `fork`/`join*` and
`case`/`endcase` nesting, so an action block that is an `if` with a
`begin ... end` body (with or without `else`) is captured whole
(3 parser tests + 2 cases).
- [ ] **Not done, deliberately:** canonical layout for property/sequence
expressions; `expect property`; `cover sequence`; `default clocking` /
`default disable iff` (interface cluster's).
## Work log
### 2026-08-20 — dev
**Baseline** (`cargo build --release && scripts/score.sh`):
```json
{"passing":699,"total":820,"pct":85.2,"failures_by_category":{"interface":31,"dv-statements":26,"expressions":19,"directive-split":14,"assertions":13,"types-decls":11,"invalid-or-fragment":3,"lex-macro-number":2,"not-verilog":1,"other":1}}
```
**After**:
```json
{"passing":712,"total":820,"pct":86.8,"failures_by_category":{"interface":31,"dv-statements":26,"expressions":19,"directive-split":14,"types-decls":11,"invalid-or-fragment":3,"lex-macro-number":2,"not-verilog":1,"other":1}}
```
`assertions` is gone from the bucket list: **13 of 13 files fixed, 0 remain**.
The set of passing files is a strict superset of the baseline's — `comm -23`
over the two sorted pass lists is empty, and `comm -13` is exactly the 13
files of this bucket, nothing else moved in either direction.
`corpus/picorv32/picorv32.v` — 3000 lines of Verilog-2001, blocked on
`restrict property` at line 2109 since the directives-in-lists round — now
formats end to end and needed no follow-up: it did **not** advance to a new
blocker, it passes.
Key decisions and how they were reached:
1. **Reused `ItemKind::Verbatim` rather than adding an assertion variant.**
The classes round already documents that leaf as "a block lucisv
deliberately does not model, kept byte-for-byte", and every consumer
already treats it as opaque. A new item variant would have bought nothing
and cost exhaustive-match arms in four crates. Only the *statement* side
needed a new variant, because none existed.
2. **`skip_action_block` / `skip_action_stmt` rather than "scan to the next
`;`".** A naive scan is wrong for `assert property (p) $info("y"); else
$error("n");` (two `;`, the item ends at the second) and for `else begin
... end` (no trailing `;` at all). The two functions mirror the grammar's
`action_block ::= statement_or_null | [statement] else statement_or_null`
literally, so both fall out. Brackets are skipped as units so a `;` inside
one cannot end the scan early. Both shapes are pinned by a parser test that
also asserts **the following item was not swallowed** — the failure mode
that matters.
3. **`property`/`sequence` declarations scan to their closer like
`covergroup` does**, via `expect_closer`, so an unterminated one is a
clean parse error in strict mode and a recorded diagnostic in tolerant
mode. Pinned by `an_unclosed_property_declaration_is_an_error_not_a_
swallowed_file`.
4. **The multi-line-string question needed no new machinery.** `Fmt::raw_text`
already routes a `RawText` whose line break falls inside a string literal
to an untouched `Doc::Text`, using `crosses_line_inside_string`, which is
built on the same `verify.rs::line_starts_inside_string` the safety net
uses. So an `else $error("line one\n line two")` comes out
byte-identical — the *first* line is still indented (the printer's indent
lands before the first character of the doc) but no continuation line is
touched, which is a fixed point on the second pass. Verified end to end by
`an_assertion_carrying_a_multiline_string_is_left_alone_end_to_end`, and
the corrupting direction is refused by
`a_reindented_string_inside_an_assertion_action_is_rejected`. The visible
consequence — an action block that stays at column 1 under an assertion
indented to column 3 — is the correct trade: those bytes are string *data*.
5. **`verify.rs` untouched.** All 13 corpus files pass through the runtime
safety net (`scripts/score.sh` runs `lucisv --check`, which verifies), so no
forgiveness needed widening. The 12 attack pairs were written anyway and
each one is refused: a changed `|->` → `|=>`, a changed `##[1:3]` range, a
dropped `disable iff` clause, a dropped action block, a dropped label, a
dropped comment inside the spec, a re-indented multi-line string, a changed
`sequence` body, a dropped `endproperty : p` label, and a dropped local
variable declaration inside a `property`. The matching *legitimate*
transformation (`a_concurrent_assertion_may_be_reindented`) is accepted, so
the ten rejections are not vacuous.
Answers to the three questions the brief asked to check and report:
- **`generate` block, item position** — works; case
`sequence ... endsequence` inside `if (AsyncOn) begin : gen_async_assert`
and case `assert property ... else $error` inside `if (FALL_THROUGH) begin`
both come from real corpus files and both pass.
- **`always` block, statement position** — works; covered by the
statement-position case (`cover property` inside `always @(posedge clk)
begin`) and by
`a_concurrent_assertion_also_parses_in_statement_position`.
- **inside an `interface`** — **cannot be tested yet**: `interface` is itself
a parse error, and is the interface cluster's (31 files). No change here is
needed for it; see Handshakes.
Linter check, as asked: no rule needs to descend. AST rules see the assertion
as one opaque `Verbatim` leaf, which is what `constraint` and `covergroup`
already are; `vlog_linter/src/visit.rs`'s `walk_stmts` ends in `_ => {}` so it
needed no arm at all. The text-driven rules still work over these lines —
checked by hand on a file with a tab-indented and trailing-whitespaced
assertion, which reported `no-tabs` and `no-trailing-whitespace` at the right
columns. `lucisv check` runs clean (exit 0/1) on all 13 new files; that is part
of what `scripts/score.sh` counts as a pass.
Files changed:
- `crates/vlog_parser/src/ast.rs` — `StmtKind::Verbatim`, widened doc on
`ItemKind::Verbatim`
- `crates/vlog_parser/src/parser.rs` — five new functions, three dispatch
sites, 11 unit tests
- `crates/vlog_parser/tests/spans.rs` — one match arm
- `crates/vlog_formatter/src/format.rs` — one match arm
- `crates/vlog_formatter/tests/cases/assertions.cases` — new, 19 cases
- `crates/vlog_formatter/tests/verification.rs` — 12 attack tests
- `crates/vlog_semantic/src/bind.rs` — one match arm
- `README.md` — "Supported syntax" bullet, roadmap items 7/7b/8
- `docs/features/assertions/README.md` — this file
### 2026-08-21 — dev (response to QA round 1)
The round-1 finding below — `skip_action_stmt`'s generic branch tracking
brackets but not `begin`/`end`, so an action block like `if (c) begin x = 1;
end else y = 2;` ended at the first `;` *inside* the nested block — is fixed.
`skip_action_stmt` is now one loop with a block-keyword depth counter beside
the bracket skipping. It counts the openers `BLOCK_OPENERS` (`begin`, `fork`,
`case`/`casex`/`casez`/`randcase`) against the closers `BLOCK_CLOSERS`
(`end`, `join`/`join_any`/`join_none`, `endcase`), and:
- a `;` ends the statement only at depth 0, so a `;` inside a nested block no
longer ends the scan;
- a statement that *ends* with a block ends there — no `;` follows one — and
the scan then reads the optional `end : label` and continues only if an
`else` follows, which is what makes the `if`/`else` shape whole;
- `disable fork` / `wait fork` are matched as a pair and skipped: they name
the enclosing block rather than opening one, and counting them would have
broken the very common UVM `fork ... join_none` + `disable fork` action
block;
- a closer at depth 0 (nothing open) is a clean `expected ';'` error where it
stands, which is both a better position than the old run-to-EOF and the
reason the counter can never underflow.
The termination argument the QA log asked about still holds and is now in the
doc comment: `at_eof` is checked on every turn and every arm consumes at
least one token, so unbalanced input is a clean parse error, never a loop and
never a read past the end of the file. Both directions are pinned by
`an_unbalanced_action_block_is_a_clean_error`.
Tests: three parser tests (`an_action_block_keeps_a_nested_begin_end_whole`,
`an_action_block_may_be_a_fork_or_a_case`,
`an_unbalanced_action_block_is_a_clean_error`) and two cases in
`assertions.cases` (the `if`/`begin`/`end`/`else` shape and a
`fork ... join_none` with `disable fork` inside), each with a following item
asserted to survive so a future over-greedy scan is caught.
The old special case that required the pass statement's *first* token to be
`begin` is gone — it is now just depth 1 on the first token — so the previous
begin-block behaviour is unchanged, `begin`-first or not.
Score unchanged before and after
(`{"passing":800,"total":820,"pct":97.6,...}`), passing set identical, all
800 passing files byte-identical against the pre-change binary, two-pass
idempotency sweep clean.
Files changed: `crates/vlog_parser/src/parser.rs` (`skip_action_stmt`, the
two new consts, 3 tests), `crates/vlog_formatter/tests/cases/assertions.cases`
(2 cases).
## QA log
### 2026-08-21 — round-1 adversarial QA
Verified: `cargo test --workspace`/clippy/fmt clean; corpus score 796/820;
whole-corpus idempotency + comment-preservation sweep clean; 476-case mutation
fuzz clean.
Targeted attacks:
- **`skip_action_stmt` running off the end / infinite loop on unbalanced
input.** Not found — `skip_balanced` and the outer `skip_action_stmt` loop
both check `at_eof()` on every iteration and return a clean parse error
("expected `)`" / "expected `;`" / "expected `end`") rather than looping.
- **`skip_action_stmt` swallowing the FOLLOWING item/statement — found a real
gap (clean error, not corruption).** `skip_action_stmt`'s non-`begin`
branch (parser.rs, `fn skip_action_stmt`, ~line 1665) scans token-by-token
for a depth-0 `;`, tracking nesting only for `(`/`[`/`{`. It does **not**
track `begin`/`end` nesting unless the pass statement's *very first* token
is literally `begin`. So when the pass statement is, e.g., an `if` whose
then-branch is a `begin ... end` block, the scan stops at the first `;`
**inside** that nested block instead of after the block's `end`. Repro:
```verilog
assert property (@(posedge clk) a |-> b)
if (cond)
begin
x = 1;
end
else
y = 2;
```
→ `parse error: 8:7: unsupported construct starting with keyword 'else'
(found "else")` (exit 2). Without the `else`, the leftover `end` after the
prematurely-ended verbatim span becomes `parse error: 8:5: expected
declaration or instantiation (found "z")` for whatever follows. Both are
**clean rejections** — exit 2, zero bytes written, input untouched on disk
— so no hard invariant is broken, but this is a real, reproducible parsing
gap in the assertions cluster: an otherwise-legal concurrent-assertion
action block (`if` with a `begin/end` body, optionally followed by `else`)
is currently unformattable. Files at
`/private/tmp/claude-501/.../scratchpad/qa/assert1.sv` and `assert2.sv`.
**NON-BLOCKING** (no corruption/idempotency/comment-loss), but flagged as a
concrete follow-up: `skip_action_stmt`'s generic branch needs `begin`/`end`
depth tracking alongside its bracket tracking.
- **`restrict` matched by text.** No case found where an ordinary identifier
named `restrict` followed by `property` gets misidentified — the exact
scenario the dev's comment says cannot happen (no type/instance name is
ever followed by the `property` keyword) held up under testing.
- **Verbatim raw_text with a multi-line string inside `else $error("...")`.**
Constructed a concurrent assertion whose action block contains
`$error("line one\nline two")` at a nested `generate`/`begin` indent level
different from column 0; the whole assertion — multi-line string included —
reproduces byte-identical and is idempotent; the first line gets
re-indented with the rest of the item, the string's continuation line does
not move (per `crosses_line_inside_string`/`raw_text`, format.rs).
- **Comment immediately after `assert`/`property`/inside the property
paren/around the action-block boundary.** `assert /*c1*/ property /*c2*/ (
/*c3*/ @(posedge clk) a |-> b /*c4*/ ) /*c5*/ else /*c6*/ $error("x")
/*c7*/ ;` — every comment position round-trips byte-identical (the whole
construct is one verbatim span), no losses.
No BLOCKING findings for this cluster. The `skip_action_stmt` begin/end gap
above is the most concrete follow-up item.
### 2026-08-21 — round-2 adversarial QA (verifying the round-1 fix)
Confirms the dev's 2026-08-21 "response to QA round 1" work log entry above:
the `skip_action_stmt` depth-counter rewrite.
- **The exact repro from round-1** (`if (cond) begin x = 1; end else y = 2;`
as an assertion's action block) now formats correctly and no longer drops
the `else`/leftover `end`; re-ran both the `begin`-first and non-`begin`-
first spellings.
- **`fork`/`join_none` with `disable fork` and `wait fork` inside**, and
`case`/`endcase` as the action block, both nested one level deeper than the
dev's own test cases (a `case` inside a `fork`, a `disable fork` inside a
`begin` inside a `fork`) — all keep the whole action block, all correctly
swallow nothing past `end`/`endcase`/`join_none`.
- **Unbalanced input, both directions:** a `begin` with no matching `end`
before EOF, and a `join_none`/`end`/`endcase` with nothing open at depth 0
— both exit 2 with a clean, on-the-spot error and the input file untouched;
no run to EOF, no loop. Consistent with `an_unbalanced_action_block_is_a_
clean_error`.
- **Whole-corpus idempotency and the pre/post-fix binary diff** — see
`docs/features/mop-up-2/README.md`'s round-2 QA log for the full corpus,
clippy/fmt/test-suite, and swallowed-error sweep that covers this file's
half of the `a4f8476` commit too (the two changes were reviewed together).
No BLOCKING findings. The round-1 gap is closed.