Compare commits

...
11 Commits
Author SHA1 Message Date
lucioandClaude Fable 5 852d05d9ad Release 0.16.0 — the testbench-syntax release
ci / checks (push) Successful in 52s
ci / corpus (push) Successful in 23s
release / build-and-publish (push) Successful in 4m52s
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 15:34:30 -07:00
lucioandClaude Fable 5 98675c630a docs/topo.md: the testbench wave's edges
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 15:33:43 -07:00
lucioandClaude Fable 5 7f65a2449a The merged-tree pins both lanes promised each other
ci / checks (push) Successful in 48s
ci / corpus (push) Successful in 21s
The refusal pin a_comment_before_a_call_in_a_condition_is_still_refused
flips exactly as Lane B's Handshake said it should now that take_gap
and header_parens share a tree: the shape formats, the comment stays
inside the parens, fixed point asserted, plus the keymgr .cases entry.
And the standing invariant-4 template applied to the directive
capture: three (input, corrupted output) pairs — a dropped `else arm,
swapped arms, a lost `endif — each asserted rejected by the safety
net. Both were flagged by the serial round as the lead's first
post-merge task; done by the lead.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 13:43:24 -07:00
lucio 3f300fa9e9 Merge testbench-syntax serial round (directive-in-statements + take_gap)
Co-Authored-By: Claude Fable 5 <[email protected]>

# Conflicts:
#	docs/features/formatter-bug-fixes/README.md
2026-08-29 13:38:32 -07:00
lucioandClaude Fable 5 7881cc869c Directives may open inside a statement, and comments keep their owners
Bucket 7: the mirror image of directive-split — an `ifdef opening
INSIDE an assign RHS, expression or instantiation head, where all
three existing directive features trigger on a closing directive and
could not fire. The construct is captured verbatim by two mirror
recoveries sharing one capture step (statement-level first, item-level
behind it), construct_end classifying the head (Semi /
endfunction+label / Unknown -> refuse rather than guess), and
terminated_in_arm honoring both real terminator placements. Both
flagship tb.sv files needed only take_list_directives to stop
harvesting an outer region's `else as a list element. OpenTitan sweep
107 -> 100, exactly the 7 targets (chip_if.sv x2, chip_earlgrey
asic/cw340, jtag_dtm_reg_block, both top_* tb.sv), zero regressions,
corpus per-file byte-identical to baseline.

Also delivers Lane B's Handshake: take_before_open's queue drain was
necessary-but-not-sufficient — CallComments::dangling drained the
same way — both now behind Parser::take_gap (comments kept only when
span.start >= last_end()), verified by composing with Lane B's tree:
keymgr_scoreboard.sv formats, closing the last bucket-2 file.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 13:38:02 -07:00
lucio 89186a8eaa docs: move performance and topology notes
ci / checks (push) Successful in 53s
ci / corpus (push) Successful in 21s
2026-08-29 13:29:57 -07:00
lucio 27a652ee3d Merge testbench-syntax Lane B (formatter round-trip bugs)
ci / checks (push) Successful in 54s
ci / corpus (push) Successful in 21s
Co-Authored-By: Claude Fable 5 <[email protected]>

# Conflicts:
#	TODO.md
2026-08-29 12:56:47 -07:00
lucioandClaude Fable 5 d3deacf0f6 Three formatter comment bugs fixed where they lived, safety net unwidened
Bucket 2 of syntax_coverage.md: 12 opentitan files parsed but failed
the formatter's own verification. Three shapes: (A) a line comment
trailing 'end' swallowed a cuddled 'else' into the comment — cuddling
now requires no trailing line comment (block comments still cuddle);
(B) a comment inside if/while/repeat/wait/case header parens printed
after the ')' — Fmt::header_parens finds the real ')' and prints the
split comments through the shared paren layout; (C) 'default;' grew an
invented ':' — the optional colon is read from the source byte. 11 of
12 files now format and round-trip (12 -> 1 verification failures on
the sweep); the 12th is a parser bug filed as a specified Handshake
and delivered by the directive round, not edited cross-lane. verify.rs
untouched; four masked-corruption rejection pairs added per the
standing template; QA's ~30-attack sweep found zero corruption and
pinned two informational boundaries. Formatter output changed:
release must bump the workspace version (format-cache rule).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 12:55:51 -07:00
lucio 17633d2214 Merge testbench-syntax Lane A (out-of-class constraints)
ci / checks (push) Successful in 55s
ci / corpus (push) Successful in 22s
Co-Authored-By: Claude Fable 5 <[email protected]>

# Conflicts:
#	TODO.md
2026-08-29 11:11:29 -07:00
lucioandClaude Fable 5 e2c954ba77 Out-of-class constraints parse: one line, 45 files, a cascade gone
constraint C::name { ... } at file/package scope failed at the `::` —
parse_constraint's name was expect_name where the out-of-body method
path already existed; it is now parse_method_name, and nothing else
moved: the item was always a verbatim leaf, so no AST variant, no
formatter/binder/spans arm, verify.rs untouched. On the real opentitan
checkout: 45 of 45 bucket-1 files unblocked (44 fully clean, the 45th
advancing to its documented bucket-10 gap), whole-sweep failures
151 -> 107 with zero newly-failing files, and the tolerant-mode
cascade collapsing 1,349 diagnostics -> 1 across the bucket — the LSP
win the round was chosen for. Corpus gate exactly at baseline. QA
reproduced every number independently via stash before/after,
attacked the grammar widening and the verbatim byte-integrity, and
pinned the index-opacity promise with the corrected semantic test.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 11:05:34 -07:00
lucioandClaude Fable 5 e565dc0812 TODO.md: the testbench-syntax wave, planned from syntax_coverage.md
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 10:33:38 -07:00
23 changed files with 3448 additions and 86 deletions

No files matched your search

+41
View File
@@ -4,6 +4,47 @@ All notable changes to lucisv are recorded here. Versions follow
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
(see `README.md`) are the only frozen contract.
## 0.16.0 — 2026-08-29
The testbench-syntax release: the coverage gap named by
`syntax_coverage.md` (a full sweep of a 3,943-file opentitan checkout),
closed bucket by bucket. Sweep failures 151 → 100 across three
lead-reviewed rounds.
### Out-of-class constraints parse
`constraint ClassName::name { ... }` at file or package scope — the
single biggest bucket, 45 files — was a one-line grammar fix reusing
the out-of-body method-name path. The real win is tolerant-mode: the
cascade of bogus diagnostics these files produced in the editor
(300+ per file, 1,349 across the bucket) collapses to at most one
honest report.
### Directives may open inside a statement
An `` `ifdef `` splitting the right-hand side of an assign, an
expression, or an instantiation head — the mirror image of every
previous directive feature, which all recovered at a *closing*
directive — is captured verbatim, with a head classifier that refuses
what it cannot prove rather than guessing. Fixes chip_if.sv in both
opentitan tops, both flagship tb.sv testbenches, and friends. Crafted
corrupted-capture pairs are asserted rejected by the safety net.
### Three formatter comment bugs, fixed where they lived
A line comment trailing `end` no longer swallows a cuddled `else`; a
comment inside an `if`/`while`/`repeat`/`wait`/`case` header's parens
stays inside them; `default;` no longer grows an invented `:`. Eleven
of the twelve files the safety net had (correctly) refused now format
and round-trip; the twelfth needed a parser-side pending-comment fix
(`take_gap`) delivered by the directive round — all twelve close on
the merged tree. `verify.rs`'s forgiveness was not widened; the
attack-test template was applied anyway.
**Formatter output changed for the comment shapes above, so this
release bumps the version and warm format caches re-verify** (the
format-cache rule).
## 0.15.0 — 2026-08-29
The interactive-latency release, benchmarked twice against a real
+3 -3
View File
@@ -90,9 +90,9 @@ Rules:
## Parallel lanes (the 2-agent loop)
Up to **two dev/QA lanes may run concurrently** when — and only when —
their features do not collide in `TOPO.md`: no shared edge between them
their features do not collide in `docs/topo.md`: no shared edge between them
(no `──▶`, no `◀──▶`, and neither touching the same open handshake in
§2.9), and disjoint file sets. `TOPO.md` is the authority; if the
§2.9), and disjoint file sets. `docs/topo.md` is the authority; if the
collision question is not answerable from it, the features are not
proven independent and run serially. Rules for a parallel wave:
@@ -119,5 +119,5 @@ proven independent and run serially. Rules for a parallel wave:
in their own sections — the lead resolves the trivially-parallel
merge; anything worse than trivially-parallel means the lanes were
not actually independent, which is a planning failure to record.
- After merging, the lead updates `TOPO.md` for any edge a lane added
- After merging, the lead updates `docs/topo.md` for any edge a lane added
or amended, so the next wave plans against reality.
Generated
+8 -8
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.15.0"
version = "0.16.0"
[[package]]
name = "lucisv_server"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -264,11 +264,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.15.0"
version = "0.16.0"
[[package]]
name = "vlog_refactor"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"vlog_parser",
"vlog_semantic",
@@ -276,7 +276,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.15.0"
version = "0.16.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -12,7 +12,7 @@ members = [
]
[workspace.package]
version = "0.15.0"
version = "0.16.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+66 -3
View File
@@ -1129,9 +1129,9 @@ color, goto implementation, goto declaration (Verilog has no
declaration/definition split lucisv models). Recorded here so the
audit doesn't repeat.
## 10. Performance wave (2026-08-28) — performance.md findings
## 10. Performance wave (2026-08-28) — docs/performance.md findings
Source: `performance.md` (benchmark of every LSP action against
Source: `docs/performance.md` (benchmark of every LSP action against
opentitan, 3 976 files). Tracking for the two-worktree parallel round;
each lane's dev ticks only its own lines. Lane file ownership is the
merge contract — a lane touches no file outside its list.
@@ -1186,7 +1186,7 @@ references-nav,index-scope}/README.md, docs/perf/README.md)
fifteen-shape plan-equality test and a module-table equality test.
- [x] `documentHighlight` answered 0 results at every opentitan
position while references answered — root-cause and fix (or
prove the benchmark request wrong and correct performance.md).
prove the benchmark request wrong and correct docs/performance.md).
**A real bug, not a benchmark mistake**: the handler asked only
single-file `Semantics`, so a name this file uses but does not
declare — an instantiated module, a `.port` connection — had no
@@ -1296,3 +1296,66 @@ and three owner items. See
unit's range is now in the index for free.
- [ ] Manual extension-host acceptance (themes, keyboard-only, zoom,
screen readers, an old server binary, both VSIX shapes).
## 11. Testbench-syntax wave (2026-08-29) — syntax_coverage.md findings
Source: `syntax_coverage.md` (opentitan sweep, 96.2% → the gap). The top
two buckets both edit `vlog_parser/src/parser.rs`, so per CLAUDE.md's
parallel-lane rule they run serially; the wave's first two lanes pair
the constraints round with the TOPO-independent formatter bugs instead.
### Lane A — out-of-class constraints (worktree; files:
crates/vlog_parser/src/parser.rs, crates/vlog_parser/tests/*,
crates/vlog_semantic if an arm is needed, docs/features/
out-of-class-constraints/README.md, TODO.md §11 Lane A lines)
- [x] `constraint C::name { ... }` at file/package/class-external scope
— 45 files blocked, and the tolerant-mode cascade (300+ bogus
diagnostics per file) is the real LSP damage. Expected shape: the
classes feature's verbatim capture reused (justify if not).
Done: `parse_constraint` reuses `parse_method_name`, no new AST
variant. OpenTitan 151 → 107 failures; 44 of the 45 clean, the
45th advances to bucket 10. Tolerant diagnostics over the 45:
1 349 → 1. `docs/features/out-of-class-constraints/README.md`.
### Lane B — formatter round-trip bugs (worktree; files:
crates/vlog_formatter/src/* EXCEPT verify.rs forgiveness,
crates/vlog_formatter/tests/*, docs/features/formatter-bug-fixes/
README.md, TODO.md §11 Lane B lines)
- [x] The 12 files the safety net refused (comment / `else if` merging
shapes in syntax_coverage.md §bucket 2): fix the formatter so its
output verifies; verify.rs forgiveness may NOT be widened (any
widening needs masked-corruption attack tests per invariant 4 —
prefer no widening at all). **11 of 12 fixed; `verify.rs`
untouched.** The 12th (`keymgr_scoreboard.sv`) had its bucket-2
bug fixed and a second, distinct, *parser*-side bug behind it —
`Parser::take_before_open` (parser.rs:757) drains the whole
pending-comment queue, so a comment written after `if (` is
swallowed by the condition's first call. Out of Lane B's file set;
filed as a handshake in `docs/features/formatter-bug-fixes/
README.md`.
- [ ] Owner/lead: the one-line parser fix above (Lane A's file), which
closes the last of the 12.
### Serial, after Lane A merges (parser.rs frees up)
- [x] Directive-split for expressions/statements: `` `ifdef `` splitting
an assign RHS / instantiation head (chip_if.sv:1192 anchor; blocks
both top_* tb.sv testbenches). 5-file floor, high leverage.
Done: the mirror of `directive-split` — the failure lands on the
`` `ifdef `` that *opens* a region inside a construct, not on the
`` `else `` that closes one around it. Verbatim capture, at item and
at statement level; no new AST variant or field, so no printer arm.
Plus one guard in `take_list_directives` so an outer region's seam
is not harvested as a list element, which is all the two tb.sv files
needed. OpenTitan 107 → 100 failures: all 5 bucket-7 files, both
`top_{earlgrey,darjeeling}/dv/tb/tb.sv`, zero regressions, corpus
gate byte-identical at 813/820.
`docs/features/directive-in-statements/README.md`.
Also delivered there: the `Parser::take_before_open` handshake Lane B
filed (`docs/features/formatter-bug-fixes/README.md`), which unblocks
the 12th bucket-2 file, `keymgr_scoreboard.sv`.
- [ ] Mop-up bundle (~26 files): enum member ranges, cast-base drive
strengths, local typedef statement, gate delays, virtual+modport,
rand-on-struct, foreach-skip-dim, hierarchical bind instance list.
+178 -44
View File
@@ -413,9 +413,16 @@ impl<'a> Fmt<'a> {
/// printing every comment and then every attribute moves a comment across
/// an attribute in the token stream, which the safety net rejects.
fn leading(&self, meta: &Meta) -> Vec<Doc> {
self.leading_from(meta, 0)
}
/// The same, minus the first `skip` leading comments — the ones a
/// statement header already printed inside its own parentheses. See
/// [`Fmt::header_parens`].
fn leading_from(&self, meta: &Meta, skip: usize) -> Vec<Doc> {
let mut docs = Vec::new();
let mut attrs = meta.attrs.iter().peekable();
for c in &meta.leading {
for c in meta.leading.iter().skip(skip) {
while let Some(attr) = attrs.next_if(|a| a.span.start < c.span.start) {
Self::push_leading(&mut docs, self.raw_text(attr), false);
}
@@ -832,6 +839,63 @@ impl<'a> Fmt<'a> {
group(vec![text("("), indent(vec![Doc::SoftLine, self.expr(e)]), Doc::SoftLine, text(")")])
}
/// `( expr )` with the comments the source wrote just inside the
/// parentheses. A comment there forces them open, the same way a comment
/// inside a port list does.
fn paren_comments(&self, inner: &Expr, before: &[&Comment], after: &[&Comment]) -> Doc {
let mut docs = vec![Doc::SoftLine];
for c in before {
docs.push(self.comment(c));
docs.push(Doc::HardLine);
}
docs.push(self.expr(inner));
let mut outer = vec![text("("), indent(docs)];
for c in after {
outer.push(text(" "));
outer.push(self.comment(c));
}
let ends_line = after.iter().any(|c| is_line_comment(&c.text));
outer.push(if ends_line { Doc::HardLine } else { Doc::SoftLine });
outer.push(text(")"));
group(outer)
}
/// The `(cond)` of a statement header, taking back the comments the parser
/// handed to the construct's *body* because they were written before the
/// closing `)`.
///
/// Nothing between `(` and `)` owns trivia, so a comment written inside a
/// header's parentheses stays queued and lands on the next node that takes
/// meta — the body statement, or a `case`'s first item. Printed there it
/// would sit *after* a `)` it was written before, and `verify.rs` refuses
/// the file, rightly: the comment moved across a token.
///
/// Returns the header doc and how many of `body`'s leading comments it
/// consumed, which the caller must then skip. When the source does not
/// have the expected shape nothing is taken and the plain parentheses are
/// printed, so an unrecognized header is left exactly as it was.
fn header_parens(&self, cond: &Expr, body: &Meta) -> (Doc, usize) {
let close = match skip_trivia(self.src, cond.span.end as usize) {
Some(i) if self.src.as_bytes().get(i) == Some(&b')') => i as u32,
_ => return (self.parens(cond), 0),
};
let taken = body.leading.iter().take_while(|c| c.span.start < close).count();
if taken == 0 {
return (self.parens(cond), 0);
}
let (before, after): (Vec<&Comment>, Vec<&Comment>) =
body.leading[..taken].iter().partition(|c| c.span.start < cond.span.start);
(self.paren_comments(cond, &before, &after), taken)
}
/// True when the source wrote the optional `:` after a `default` case
/// label. IEEE 1800 §12.5 makes it optional — `default;` is legal — and
/// the token stream has to come back with exactly what was written.
fn default_has_colon(&self, span: TextRange) -> bool {
let after = span.start as usize + "default".len();
matches!(skip_trivia(self.src, after), Some(i) if self.src.as_bytes()[i] == b':')
}
/// Sequence of items at one indent level, preserving single blank lines
/// between them. An item a fenced region swallowed emits nothing, and
/// contributes no separator either.
@@ -1981,7 +2045,7 @@ impl<'a> Fmt<'a> {
for item in &g.items {
body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
body.extend(self.leading(&item.meta));
let mut item_docs = vec![self.case_labels(&item.labels)];
let mut item_docs = vec![self.case_labels(&item.labels, item.span)];
self.gen_block(&mut item_docs, &item.body, depth + 1);
body.push(concat(item_docs));
body.extend(self.trailing(&item.meta));
@@ -2320,10 +2384,17 @@ impl<'a> Fmt<'a> {
/// blocks cuddle onto the prefix line, single statements go on the same
/// line if they fit, otherwise indented on the next line.
fn stmt_as_body(&self, prefix: Doc, s: &Stmt) -> Doc {
self.stmt_as_body_from(prefix, s, 0)
}
/// The same, skipping the body's first `skip` leading comments because
/// `prefix` already printed them inside its parentheses. See
/// [`Fmt::header_parens`].
fn stmt_as_body_from(&self, prefix: Doc, s: &Stmt, skip: usize) -> Doc {
match &s.kind {
StmtKind::Block { label, stmts, dangling, end_label, .. } => {
let mut docs = vec![prefix, text(" ")];
docs.extend(self.leading(&s.meta));
docs.extend(self.leading_from(&s.meta, skip));
docs.push(self.block_doc(label, stmts, dangling, end_label));
docs.extend(self.trailing(&s.meta));
concat(docs)
@@ -2331,13 +2402,19 @@ impl<'a> Fmt<'a> {
StmtKind::Timing { control, stmt: Some(inner) } => {
// e.g. `always @(posedge clk) begin ... end`
let mut docs = vec![prefix, text(" ")];
docs.extend(self.leading(&s.meta));
docs.extend(self.leading_from(&s.meta, skip));
let control_doc = self.timing_control(control);
docs.push(self.stmt_as_body(control_doc, inner));
docs.extend(self.trailing(&s.meta));
concat(docs)
}
_ => group(vec![prefix, indent(vec![Doc::Line, self.stmt(s)])]),
// The same three parts `stmt` prints, with the skip applied.
_ => {
let mut body = self.leading_from(&s.meta, skip);
body.push(self.stmt_kind(&s.kind));
body.extend(self.trailing(&s.meta));
group(vec![prefix, indent(vec![Doc::Line, concat(body)])])
}
}
}
@@ -2469,17 +2546,21 @@ impl<'a> Fmt<'a> {
}
head.push_str(kw);
head.push(' ');
let mut docs = vec![text(head), self.parens(expr)];
let (parens, taken) = match items.first() {
Some(first) => self.header_parens(expr, &first.meta),
None => (self.parens(expr), 0),
};
let mut docs = vec![text(head), parens];
if *inside {
docs.push(text(" inside"));
}
docs.push(self.case_body(items, dangling));
docs.push(self.case_body(items, dangling, taken));
concat(docs)
}
// `randcase` is a `case` body with weights for labels and no
// selector, so it shares the body layout.
StmtKind::RandCase { items, dangling } => {
concat(vec![text("randcase"), self.case_body(items, dangling)])
concat(vec![text("randcase"), self.case_body(items, dangling, 0)])
}
StmtKind::For { init, cond, step, body } => {
let mut header = vec![text("for (")];
@@ -2511,7 +2592,8 @@ impl<'a> Fmt<'a> {
self.stmt_as_body(concat(header), body)
}
StmtKind::While { cond, body } => {
self.stmt_as_body(concat(vec![text("while "), self.parens(cond)]), body)
let (parens, taken) = self.header_parens(cond, &body.meta);
self.stmt_as_body_from(concat(vec![text("while "), parens]), body, taken)
}
StmtKind::DoWhile { body, cond } => {
let mut docs = vec![text("do")];
@@ -2532,7 +2614,8 @@ impl<'a> Fmt<'a> {
concat(docs)
}
StmtKind::Repeat { count, body } => {
self.stmt_as_body(concat(vec![text("repeat "), self.parens(count)]), body)
let (parens, taken) = self.header_parens(count, &body.meta);
self.stmt_as_body_from(concat(vec![text("repeat "), parens]), body, taken)
}
StmtKind::Forever { body } => self.stmt_as_body(text("forever"), body),
StmtKind::Foreach { target, vars, body } => {
@@ -2589,13 +2672,13 @@ impl<'a> Fmt<'a> {
None => concat(vec![control_doc, text(";")]),
}
}
StmtKind::Wait { cond, stmt } => {
let head = concat(vec![text("wait "), self.parens(cond)]);
match stmt {
Some(s) => self.stmt_as_body(head, s),
None => concat(vec![head, text(";")]),
StmtKind::Wait { cond, stmt } => match stmt {
Some(s) => {
let (parens, taken) = self.header_parens(cond, &s.meta);
self.stmt_as_body_from(concat(vec![text("wait "), parens]), s, taken)
}
}
None => concat(vec![text("wait "), self.parens(cond), text(";")]),
},
StmtKind::ExprStmt(e) => concat(vec![self.expr(e), text(";")]),
StmtKind::EventTrigger(e) => concat(vec![text("-> "), self.expr(e), text(";")]),
StmtKind::VarDecl(d) => concat(vec![self.data_decl(d), text(";")]),
@@ -2660,9 +2743,13 @@ impl<'a> Fmt<'a> {
head.push(' ');
}
head.push_str("if ");
let prefix = concat(vec![text(head), self.parens(cond)]);
let then_is_block = matches!(then.kind, StmtKind::Block { .. });
let mut docs = vec![self.stmt_as_body(prefix, then)];
let (parens, taken) = self.header_parens(cond, &then.meta);
let prefix = concat(vec![text(head), parens]);
// A line comment trailing the then-branch runs to end of line, so a
// cuddled `else` would be swallowed into its text.
let then_is_block =
matches!(then.kind, StmtKind::Block { .. }) && !trailing_ends_line(&then.meta);
let mut docs = vec![self.stmt_as_body_from(prefix, then, taken)];
if let Some(els) = els {
// A comment written before `else` prints before it, each on its
// own line: it is where the source put it, and after the keyword
@@ -2700,9 +2787,9 @@ impl<'a> Fmt<'a> {
/// Labels normally share one line; as soon as any of them carries a
/// comment they go one per line, so a comment written between two labels
/// is printed between the same two labels instead of drifting past them.
fn case_labels(&self, labels: &[ExprItem]) -> Doc {
fn case_labels(&self, labels: &[ExprItem], item: TextRange) -> Doc {
if labels.is_empty() {
return text("default:");
return text(if self.default_has_colon(item) { "default:" } else { "default" });
}
let plain = labels.iter().all(|l| {
l.meta.leading.is_empty() && l.meta.before_sep.is_empty() && l.meta.trailing.is_none()
@@ -2744,16 +2831,27 @@ impl<'a> Fmt<'a> {
}
fn case_item(&self, item: &CaseItem) -> Doc {
self.stmt_as_body(self.case_labels(&item.labels), &item.stmt)
// `default;` — the colon IEEE 1800 §12.5 makes optional, with a null
// body. The `;` closes the keyword rather than standing as a body of
// its own, so it hugs instead of going through `stmt_as_body`.
if item.labels.is_empty()
&& matches!(item.stmt.kind, StmtKind::Null)
&& is_bare(&item.stmt.meta)
&& !self.default_has_colon(item.span)
{
return text("default;");
}
self.stmt_as_body(self.case_labels(&item.labels, item.span), &item.stmt)
}
/// The indented items of a `case`/`randcase` body and the `endcase` that
/// closes it.
fn case_body(&self, items: &[CaseItem], dangling: &[Comment]) -> Doc {
/// The items of a `case`/`randcase` body. `skip` is the number of leading
/// comments of the *first* item the `case (...)` header already printed
/// inside its parentheses (see [`Fmt::header_parens`]).
fn case_body(&self, items: &[CaseItem], dangling: &[Comment], skip: usize) -> Doc {
let mut body = Vec::new();
for item in items {
for (i, item) in items.iter().enumerate() {
body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
body.extend(self.leading(&item.meta));
body.extend(self.leading_from(&item.meta, if i == 0 { skip } else { 0 }));
body.push(self.case_item(item));
body.extend(self.trailing(&item.meta));
}
@@ -2874,23 +2972,9 @@ impl<'a> Fmt<'a> {
if before.is_empty() && after.is_empty() {
return self.parens(inner);
}
// A comment inside the parens forces them open, the same way
// a comment inside a port list does.
let mut docs = vec![Doc::SoftLine];
for c in before {
docs.push(self.comment(c));
docs.push(Doc::HardLine);
}
docs.push(self.expr(inner));
let mut outer = vec![text("("), indent(docs)];
for c in after {
outer.push(text(" "));
outer.push(self.comment(c));
}
let ends_line = after.iter().any(|c| is_line_comment(&c.text));
outer.push(if ends_line { Doc::HardLine } else { Doc::SoftLine });
outer.push(text(")"));
group(outer)
let before: Vec<&Comment> = before.iter().collect();
let after: Vec<&Comment> = after.iter().collect();
self.paren_comments(inner, &before, &after)
}
ExprKind::Cast { ty, expr } => {
concat(vec![self.expr(ty), text("'("), self.expr(expr), text(")")])
@@ -3102,3 +3186,53 @@ fn strip_blanks(line: &str, n: usize) -> &str {
fn is_line_comment(text: &str) -> bool {
text.starts_with("//")
}
/// True when a node carries no trivia at all, so printing it cannot move a
/// comment anywhere.
fn is_bare(meta: &Meta) -> bool {
meta.leading.is_empty()
&& meta.trailing.is_none()
&& meta.before_sep.is_empty()
&& meta.attrs.is_empty()
}
/// True when a node's trailing comments end in a line comment, so anything
/// printed after them on the same line would be swallowed into the comment's
/// text. `trailing` prints `before_sep` first and `trailing` last.
fn trailing_ends_line(meta: &Meta) -> bool {
match &meta.trailing {
Some(tr) => is_line_comment(&tr.text),
None => meta.before_sep.last().is_some_and(|c| is_line_comment(&c.text)),
}
}
/// Offset of the first byte at or after `from` that is neither whitespace nor
/// part of a comment, or `None` if the text ends first.
///
/// Used to ask what a node is followed by in the source — a `)` that closes
/// the header it sits in, the optional `:` of a `default` case label — when
/// the AST does not record it.
fn skip_trivia(src: &str, from: usize) -> Option<usize> {
let bytes = src.as_bytes();
let mut i = from;
while i < bytes.len() {
match bytes[i] {
b'/' if bytes.get(i + 1) == Some(&b'/') => {
i += 2;
while i < bytes.len() && bytes[i] != b'\n' {
i += 1;
}
}
b'/' if bytes.get(i + 1) == Some(&b'*') => {
i += 2;
while i < bytes.len() && !(bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/')) {
i += 1;
}
i = (i + 2).min(bytes.len());
}
c if c.is_ascii_whitespace() => i += 1,
_ => return Some(i),
}
}
None
}
@@ -1191,3 +1191,227 @@ endmodule
module m;
sub /* the one */ u (.a(b));
endmodule
====
# a line comment trailing `end` pushes `else if` onto the next line
module m;
always_comb begin
if (a) begin
x = 1;
end // addr_phase_write
else if (b) begin
x = 2;
end
else begin
x = 3;
end
end
endmodule
----
module m;
always_comb begin
if (a) begin
x = 1;
end // addr_phase_write
else if (b) begin
x = 2;
end else begin
x = 3;
end
end
endmodule
====
# a line comment trailing `end` pushes a one-statement `else` down too
module m;
always_comb begin
if (a) begin
x = 1;
end // fell through
else if (b) x = 2;
else x = 3;
end
endmodule
----
module m;
always_comb begin
if (a) begin
x = 1;
end // fell through
else if (b) x = 2;
else x = 3;
end
endmodule
====
# a block comment trailing `end` still lets `else` cuddle
module m;
always_comb begin
if (a) begin
x = 1;
end /* why */ else begin
x = 2;
end
end
endmodule
----
module m;
always_comb begin
if (a) begin
x = 1;
end /* why */ else begin
x = 2;
end
end
endmodule
====
# a comment after `if (` stays inside the parentheses
module m;
always_comb begin
if (// the first transaction
a ||
// or the last one
b) begin
x = 1;
end
end
endmodule
----
module m;
always_comb begin
if (
// the first transaction
a || // or the last one
b
) begin
x = 1;
end
end
endmodule
====
# a block comment before an if condition's `)` stays inside them
module m;
always_comb begin
if (bitstuff /* && !serial_tx_se0 */) begin
x = 1;
end
end
endmodule
----
module m;
always_comb begin
if (bitstuff /* && !serial_tx_se0 */) begin
x = 1;
end
end
endmodule
====
# an if condition keeps comments on both sides of it
module m;
always_comb begin
if (// only the leading one
a) begin
x = 1;
end
if (b /* and a trailing one */) begin
x = 2;
end
if (// both ends
c /* like this */) begin
x = 3;
end
end
endmodule
----
module m;
always_comb begin
if (
// only the leading one
a
) begin
x = 1;
end
if (b /* and a trailing one */) begin
x = 2;
end
if (
// both ends
c /* like this */
) begin
x = 3;
end
end
endmodule
====
# a comment after `while (` stays inside the parentheses
module m;
initial begin
while (// keep adding while the agent wants more
rcvd < sent ||
// and while there are transactions left to drive
cnt < num) begin
x = 1;
end
end
endmodule
----
module m;
initial begin
while (
// keep adding while the agent wants more
rcvd < sent || // and while there are transactions left to drive
cnt < num
) begin
x = 1;
end
end
endmodule
====
# `repeat` and `wait` keep a comment written before their `)`
module m;
initial begin
repeat (n // how many
) begin
x = 1;
end
wait (w // until this settles
) begin
x = 2;
end
end
endmodule
----
module m;
initial begin
repeat (
n // how many
) begin
x = 1;
end
wait (
w // until this settles
) begin
x = 2;
end
end
endmodule
====
# a comment after `case (` stays inside the parentheses
module m;
always_comb begin
case (// the decoded opcode
op)
A: y = 1;
default: y = 0;
endcase
end
endmodule
----
module m;
always_comb begin
case (
// the decoded opcode
op
)
A: y = 1;
default: y = 0;
endcase
end
endmodule
@@ -0,0 +1,263 @@
# a `ifdef opened part-way through an assign, each arm carrying the
# construct's own `;` -- the block ends at the `endif, because there is no
# `;` after it to stop at
# hw/top_earlgrey/dv/env/chip_if.sv:1189 (the anchor)
module m;
// Signal probe function for `rnd_ctr` of AES_CIPHER_CTRL
wire [3:0] aes_ctrl_rnd_ctr;
assign aes_ctrl_rnd_ctr =
`ifdef GATE_LEVEL
`AES_HIER.u_aes_core.u_aes_cipher_control.mr_rnd_ctr[3:0];
`else
`AES_HIER.u_aes_core.u_aes_cipher_control.rnd_ctr;
`endif
wire after;
endmodule
----
module m;
// Signal probe function for `rnd_ctr` of AES_CIPHER_CTRL
wire [3:0] aes_ctrl_rnd_ctr;
assign aes_ctrl_rnd_ctr =
`ifdef GATE_LEVEL
`AES_HIER.u_aes_core.u_aes_cipher_control.mr_rnd_ctr[3:0];
`else
`AES_HIER.u_aes_core.u_aes_cipher_control.rnd_ctr;
`endif
wire after;
endmodule
====
# the same shape at *statement* level: a region between two call arguments,
# balanced inside the parens, so the statement ends at its own `;`. Only the
# statement is captured -- the function around it still formats
# hw/dv/sv/jtag_agent/jtag_dtm_reg_block.sv:173
class c;
virtual function void build();
abits = (dv_base_reg_field::type_id::create("abits"));
abits.configure(
.parent(this),
.size(6),
`ifdef USE_DMI_INTERFACE
.reset(32'h10),
`else
.reset(32'h07),
`endif
.has_reset(1));
dmistat = 1;
endfunction
endclass
----
class c;
virtual function void build();
abits = (dv_base_reg_field::type_id::create("abits"));
abits.configure(
.parent(this),
.size(6),
`ifdef USE_DMI_INTERFACE
.reset(32'h10),
`else
.reset(32'h07),
`endif
.has_reset(1));
dmistat = 1;
endfunction
endclass
====
# a region between the elements of a concatenation, three brackets deep inside
# an instantiation's parameter override -- the whole instantiation becomes the
# block, ending at its `;`
# hw/top_earlgrey/rtl/autogen/chip_earlgrey_asic.sv:621
module chip;
padring #(
.DioPadType ({
AnalogIn0, // RRAM_ANALOG
`ifdef ANALOGSIM
'0,
`else
CC2,
`endif
DualBidirTol // USB_N
})
) u_padring (
.clk_scan_i(ast_base_clks.clk_sys),
.scanmode_i(scanmode)
);
wire after;
endmodule
----
module chip;
padring #(
.DioPadType ({
AnalogIn0, // RRAM_ANALOG
`ifdef ANALOGSIM
'0,
`else
CC2,
`endif
DualBidirTol // USB_N
})
) u_padring (
.clk_scan_i(ast_base_clks.clk_sys),
.scanmode_i(scanmode)
);
wire after;
endmodule
====
# two instantiation *heads* behind one `ifdef, sharing a connection list. The
# region opened before the item, so this is the closing shape the
# `directive-split` recovery already knew -- what changed is that
# `take_list_directives` no longer harvests the `else as a list element and
# reads the second arm's head as a positional connection
# hw/top_earlgrey/dv/tb/tb.sv:105
module tb;
`ifdef DISABLE_ROM_INTEGRITY_CHECK
chip_earlgrey_asic #(
// This is to be used carefully, and should never be on for synthesis.
.SecRomCtrlDisableScrambling(1'b1)
) dut (
`else
chip_earlgrey_asic dut (
`endif
// Dedicated Pads
.POR_N(dut.chip_if.dios[DioPadPorN]),
`ifdef ANALOGSIM
.CC1(cc1),
`else
.CC1(dut.chip_if.dios[DioPadCc1]),
`endif
.SPI_HOST_D0(dut.chip_if.dios[DioPadSpiHostD0])
);
wire after;
endmodule
----
module tb;
`ifdef DISABLE_ROM_INTEGRITY_CHECK
chip_earlgrey_asic #(
// This is to be used carefully, and should never be on for synthesis.
.SecRomCtrlDisableScrambling(1'b1)
) dut (
`else
chip_earlgrey_asic dut (
`endif
// Dedicated Pads
.POR_N(dut.chip_if.dios[DioPadPorN]),
`ifdef ANALOGSIM
.CC1(cc1),
`else
.CC1(dut.chip_if.dios[DioPadCc1]),
`endif
.SPI_HOST_D0(dut.chip_if.dios[DioPadSpiHostD0])
);
wire after;
endmodule
====
# a split `function` header: the header's own `;` closes a *header*, so the
# block runs to `endfunction` and takes the `: label` with it
# hw/dv/sv/jtag_agent/jtag_dtm_reg_block.sv:273
class jtag_dtm_reg_dmi;
function new(string name = "",
`ifdef USE_DMI_INTERFACE
int unsigned n_bits = 50,
`else
int unsigned n_bits = 41,
`endif
int has_coverage = UVM_NO_COVERAGE);
super.new(name, n_bits, has_coverage);
endfunction : new
int after;
endclass
----
class jtag_dtm_reg_dmi;
function new(string name = "",
`ifdef USE_DMI_INTERFACE
int unsigned n_bits = 50,
`else
int unsigned n_bits = 41,
`endif
int has_coverage = UVM_NO_COVERAGE);
super.new(name, n_bits, has_coverage);
endfunction : new
int after;
endclass
====
# the control: a region opened *and* closed inside the connection list still
# conditions list elements, even with an outer region live, and the
# instantiation still parses as an instantiation rather than becoming opaque
module m;
`ifdef OUTER
chip dut (
.A(a),
`ifdef ANALOGSIM
.CC1(c1),
`else
.CC1(d1),
`endif
.B(b)
);
`endif
endmodule
----
module m;
`ifdef OUTER
chip dut (
.A(a),
`ifdef ANALOGSIM
.CC1(c1),
`else
.CC1(d1),
`endif
.B(b)
);
`endif
endmodule
====
# comments survive: the ones written inside the block print once, as part of
# its bytes, and the ones around it stay outside
module m;
// before the block
assign y =
`ifdef A
a; // inside the first arm
`else
b; /* inside the second */
`endif
// after the block
wire after;
endmodule
----
module m;
// before the block
assign y =
`ifdef A
a; // inside the first arm
`else
b; /* inside the second */
`endif
// after the block
wire after;
endmodule
====
# the keymgr shape: the take_gap parser fix and header_parens in one tree —
# the comment written after `if (` stays inside the parens (the last of
# bucket 2's 12; merged-tree pin the serial round could not add itself)
module m;
function automatic int f();
if (// why
!en() || b
) begin
return 1;
end
endfunction
endmodule
----
module m;
function automatic int f();
if (
// why
!en() || b
) begin
return 1;
end
endfunction
endmodule
@@ -0,0 +1,86 @@
# Out-of-block constraint definitions (IEEE 1800 §18.5.2), the constraint
# sibling of `function C::method`. See
# docs/features/out-of-class-constraints/README.md. The whole item is an
# ItemKind::Verbatim leaf, so the body is reproduced byte for byte; only the
# block's absolute indent is re-set, exactly as for an in-class constraint.
# an extern constraint prototype and its out-of-block definition
class my_item;
rand int delay;
extern constraint delay_c;
endclass : my_item
constraint my_item::delay_c {
soft delay dist {0 :/ 5, [1:10] :/ 5};
solve delay before other;
}
----
class my_item;
rand int delay;
extern constraint delay_c;
endclass : my_item
constraint my_item::delay_c {
soft delay dist {0 :/ 5, [1:10] :/ 5};
solve delay before other;
}
====
# inside a package: the block is re-indented, its relative layout is not
package p;
constraint my_item::delay_c {
soft delay dist {0 :/ 5};
}
endpackage
----
package p;
constraint my_item::delay_c {
soft delay dist {0 :/ 5};
}
endpackage
====
# a scope chain, a stray `;`, and comments on both sides of the block
// why this constraint exists
constraint pkg::cls::deep_c { x < 4; }; // and a trailing note
int b;
----
// why this constraint exists
constraint pkg::cls::deep_c { x < 4; }; // and a trailing note
int b;
====
# an empty body and a prototype next to a definition
class c;
extern constraint empty_c;
endclass
constraint c::empty_c {}
----
class c;
extern constraint empty_c;
endclass
constraint c::empty_c {}
====
# the body's own second grammar survives untouched: dist, ->, foreach, if
constraint seq::mode_c {
r_esc_rsp == 1 -> (!s_alert_send && !r_alert_rsp);
foreach (ranges[i]) {
ranges[i].base % 4 == 0;
}
if (enabled) {
delay dist {0 :/ 5, [1:10] :/ 5};
} else {
delay == 0;
}
}
----
constraint seq::mode_c {
r_esc_rsp == 1 -> (!s_alert_send && !r_alert_rsp);
foreach (ranges[i]) {
ranges[i].base % 4 == 0;
}
if (enabled) {
delay dist {0 :/ 5, [1:10] :/ 5};
} else {
delay == 0;
}
}
@@ -587,3 +587,54 @@ endmodule
module m;
always @(a or b or c) y = a & b & c;
endmodule
====
# `default;` keeps IEEE 1800 §12.5's optional colon off; `default: ;` keeps it
module m;
always_comb begin
unique case (digest_size_i)
SHA2_256: y = 1;
default;
endcase
unique case (other)
SHA2_256: y = 1;
default: ;
endcase
end
endmodule
----
module m;
always_comb begin
unique case (digest_size_i)
SHA2_256: y = 1;
default;
endcase
unique case (other)
SHA2_256: y = 1;
default: ;
endcase
end
endmodule
====
# a trailing comment on a colon-less `default;` keeps the comment and the
# missing colon; the null statement is no longer bare, so the hug shortcut
# does not fire and a space appears before the `;` (QA-found nit: a real
# statement or comment on the null body falls through to the general path,
# which spaces `default` off whatever follows it the same way it would any
# other case label)
module m;
always_comb begin
case (s)
A: y = 1;
default; // fallback
endcase
end
endmodule
----
module m;
always_comb begin
case (s)
A: y = 1;
default ; // fallback
endcase
end
endmodule
+148
View File
@@ -1257,3 +1257,151 @@ fn an_opaque_body_cannot_launder_a_stray_endif_into_a_split() {
}
}
}
/// Assert `format_source` refuses `input` with a verification error, i.e. the
/// safety net caught the layout and the caller keeps the original bytes.
fn expect_refusal(input: &str) {
match format_source(input, &Config::default()) {
Err(FormatError::Verification(_)) => {}
Ok(out) => panic!("expected a refusal, got:\n{out}"),
Err(e) => panic!("expected a verification refusal, got {e}"),
}
}
/// The header shapes `header_parens` deliberately does *not* cover, pinned as
/// clean refusals so a future round sees them move rather than appear.
///
/// `for` and `foreach` do not end their header in a single condition
/// expression, and a `do ... while (c);` has no body after its parentheses to
/// take the comment back from. All three still leave the file untouched.
#[test]
fn a_comment_in_a_for_foreach_or_do_while_header_is_still_refused() {
for input in [
"module m;\n initial begin\n for (int i = 0; i < 4; i++ // why\n ) begin\n y = 1;\n end\n end\nendmodule\n",
"module m;\n initial begin\n foreach (arr[i] // why\n ) begin\n y = 1;\n end\n end\nendmodule\n",
"module m;\n initial begin\n do begin\n y = 1;\n end while (c // why\n );\n end\nendmodule\n",
] {
expect_refusal(input);
}
}
/// The three bucket-2 shapes, formatted for real: every comment comes back
/// with its own text, none merged into the code that follows it, and the
/// second pass is a fixed point.
#[test]
fn the_repaired_comment_shapes_keep_every_comment_intact() {
for (input, kept, banned) in [
(
"module m;\n always_comb begin\n if (a) begin\n x = 1;\n end // addr_phase_write\n else if (b) begin\n x = 2;\n end\n end\nendmodule\n",
"// addr_phase_write",
"// addr_phase_write else",
),
(
"module m;\n always_comb begin\n if (// why not\n a || b) begin\n x = 1;\n end\n end\nendmodule\n",
"// why not",
") // why not",
),
(
"module m;\n always_comb begin\n if (a /* and here */) begin\n x = 1;\n end\n end\nendmodule\n",
"/* and here */",
") /* and here */",
),
] {
let out = format_source(input, &Config::default()).expect("formats cleanly");
assert!(out.contains(kept), "comment lost:\n{out}");
assert!(!out.contains(banned), "comment merged or moved:\n{out}");
let again = format_source(&out, &Config::default()).expect("formats again");
assert_eq!(out, again, "not idempotent");
}
}
/// Standing rule (`topo.md` §2.1): `verify.rs` was not widened for any of
/// these fixes, and the corruptions they used to produce must still be
/// rejected if a future layout change reintroduces them.
#[test]
fn the_bucket_two_corruptions_are_still_rejected() {
// A trailing line comment swallowing the `else if` that followed it.
expect_divergence(
"module m;\n always_comb begin\n if (a) begin\n x = 1;\n end // note\n else if (b) begin\n x = 2;\n end\n end\nendmodule\n",
"module m;\n always_comb begin\n if (a) begin\n x = 1;\n end // note else if (b) begin\n x = 2;\n end\n end\nendmodule\n",
);
// A comment written inside the condition, printed after the `)`.
expect_divergence(
"module m;\n always_comb begin\n if (// note\n a) begin\n x = 1;\n end\n end\nendmodule\n",
"module m;\n always_comb begin\n if (a) // note\n begin\n x = 1;\n end\n end\nendmodule\n",
);
// The `:` a `default;` did not write, invented by the printer.
expect_divergence(
"module m;\n always_comb begin\n case (s)\n A: y = 1;\n default;\n endcase\n end\nendmodule\n",
"module m;\n always_comb begin\n case (s)\n A: y = 1;\n default: ;\n endcase\n end\nendmodule\n",
);
// And its mirror: a `default: ;` losing the colon it did write.
expect_divergence(
"module m;\n always_comb begin\n case (s)\n A: y = 1;\n default: ;\n endcase\n end\nendmodule\n",
"module m;\n always_comb begin\n case (s)\n A: y = 1;\n default;\n endcase\n end\nendmodule\n",
);
}
/// A comment written just after a statement header's `(` is queued by the
/// parser and drained onto the first bracket it meets — so when the condition
/// started with a call, `CallComments::before_open` swallowed it and the
/// comment printed between the callee and its `(`. This was pinned as a
/// refusal until the directive-in-statements round delivered the parser's
/// `take_gap` fix (2026-08-29); the pin flips exactly as the Handshake said
/// it should: the shape now formats, the comment keeps its place inside the
/// parens, and the round trip is a fixed point. The last of bucket 2's 12.
#[test]
fn a_comment_before_a_call_in_a_condition_now_formats() {
let input = "module m;\n function automatic int f();\n if (// why\n !en() || b\n ) begin\n return 1;\n end\n endfunction\nendmodule\n";
let expected = "module m;\n function automatic int f();\n if (\n // why\n !en() || b\n ) begin\n return 1;\n end\n endfunction\nendmodule\n";
let config = Config::default();
let once = format_source(input, &config).expect("the delivered handshake formats this");
assert_eq!(once, expected, "the comment stays inside the parens");
let twice = format_source(&once, &config).expect("and the result still formats");
assert_eq!(twice, once, "fixed point");
}
/// The standing template applied to directive-in-statements' verbatim
/// capture (the round could not add these itself — this file was Lane B's
/// during the wave): crafted (input, corrupted output) pairs the capture
/// could plausibly produce if its extent scan slipped, each asserted
/// rejected. An `` `else `` arm dropped, the arms swapped, and the
/// `` `endif `` lost — every one is a divergence the safety net must see.
#[test]
fn a_corrupted_directive_capture_is_rejected() {
// The `` `else `` arm dropped from the captured region.
expect_divergence(
"module m;\n assign x =\n`ifdef A\n a;\n`else\n b;\n`endif\nendmodule\n",
"module m;\n assign x =\n`ifdef A\n a;\n`endif\nendmodule\n",
);
// The two arms swapped.
expect_divergence(
"module m;\n assign x =\n`ifdef A\n a;\n`else\n b;\n`endif\nendmodule\n",
"module m;\n assign x =\n`ifdef A\n b;\n`else\n a;\n`endif\nendmodule\n",
);
// The `` `endif `` lost, leaking the region into the module tail.
expect_divergence(
"module m;\n assign x =\n`ifdef A\n a;\n`else\n b;\n`endif\nendmodule\n",
"module m;\n assign x =\n`ifdef A\n a;\n`else\n b;\nendmodule\n",
);
}
/// QA (2026-08-29, Lane B): `trailing_ends_line` decides whether `end`'s
/// trailing comments swallow a cuddled `else` by checking whether the
/// *merged* trailing text starts with `//` (`is_line_comment` is a prefix
/// test). A block comment followed by a line comment on the same trailing
/// group — `end /* a */ // b` — merges into one string that starts with
/// `/*`, so the check says "does not end in a line comment" and `else` still
/// tries to cuddle, which does produce the merge this whole fix exists to
/// prevent. The safety net catches it (the reparsed output has one big
/// comment where the input had two), so the file is refused rather than
/// corrupted — this pins that it stays a safe refusal, not a fix for the
/// gap. If a later round teaches `trailing_ends_line` to look at the last
/// merged comment instead of the first, this test should flip to a `.cases`
/// entry the same way the parser handshake above is meant to.
#[test]
fn a_block_comment_merged_with_a_trailing_line_comment_before_else_is_still_refused() {
expect_refusal(
"module m;\n always_comb begin\n if (a) begin\n x = 1;\n end /* a */ // b\n else if (c) begin\n x = 2;\n end\n end\nendmodule\n",
);
}
+790 -25
View File
@@ -319,9 +319,10 @@ fn is_drive_strength(t: &Token) -> bool {
t.kind == TokenKind::Keyword && DRIVE_STRENGTHS.contains(&t.text.as_str())
}
/// Where an item started, for the recovery that may have to replace it whole.
/// Where an item — or a statement — started, for the recovery that may have to
/// replace it whole.
struct ItemMark {
/// Index of the item's first token, past its attributes.
/// Index of the construct's first token, past its attributes.
pos: usize,
/// Conditional regions open at that token.
conds: u32,
@@ -337,7 +338,100 @@ fn directive_word(t: &Token) -> &str {
if t.kind != TokenKind::Directive {
return "";
}
let rest = t.text.strip_prefix('`').unwrap_or("");
directive_word_of(&t.text)
}
/// Keywords that open a body, so that the first `;` after them closes a
/// *header* — or a statement inside the body — rather than the construct.
///
/// `function` and `task` are handled separately, by [`ConstructEnd::Keyword`];
/// these are the ones the opening-split recovery refuses outright, because
/// nothing in the corpus asks for them and capturing at a `;` would leave a
/// truncated head with its body orphaned behind it.
const BODY_KEYWORDS: &[&str] = &[
"module",
"macromodule",
"interface",
"program",
"package",
"class",
"checker",
"config",
"primitive",
"specify",
"generate",
"covergroup",
"property",
"sequence",
"clocking",
"constraint",
"begin",
"fork",
"case",
"casex",
"casez",
"randcase",
"for",
"foreach",
"while",
"repeat",
"forever",
"do",
"if",
"initial",
"final",
"always",
"always_comb",
"always_ff",
"always_latch",
];
/// Keywords that may stand in front of a `function` / `task` without changing
/// what closes it. `extern` and `pure` are deliberately absent: those spell a
/// prototype, which really does end at its `;`.
const TF_QUALIFIERS: &[&str] = &["virtual", "static", "automatic", "local", "protected"];
/// What the opening-split extent scan must look for to know a construct ended.
#[derive(Clone, Copy, PartialEq)]
enum ConstructEnd {
/// Its own `;` — every declaration, every instantiation, every simple
/// statement, and what `directive-split` has always assumed.
Semi,
/// The closing keyword named, which the header's `;` only precedes.
Keyword(&'static str),
/// Not modeled: refuse rather than capture a truncated head.
Unknown,
}
/// How the construct starting at `head` ends.
///
/// Read from the head alone, because that is all the recovery knows: the parse
/// already failed, so there is no node to ask. `jtag_dtm_reg_block.sv` is why
/// this exists — its split `function new(` header stopped the scan at the
/// header's own `;` and left `super.new(...)` behind as an item.
fn construct_end(head: &[Token]) -> ConstructEnd {
let mut i = 0;
while let Some(t) = head.get(i) {
if t.kind != TokenKind::Keyword {
// An identifier head: an instantiation, a call statement, an
// assignment. All of them end at a `;`.
return ConstructEnd::Semi;
}
match t.text.as_str() {
w if TF_QUALIFIERS.contains(&w) => i += 1,
"function" => return ConstructEnd::Keyword("endfunction"),
"task" => return ConstructEnd::Keyword("endtask"),
w if BODY_KEYWORDS.contains(&w) => return ConstructEnd::Unknown,
_ => return ConstructEnd::Semi,
}
}
ConstructEnd::Unknown
}
/// [`directive_word`] over the source text of a directive already captured as
/// a [`RawText`], for the harvested lines a list keeps rather than a token.
fn directive_word_of(text: &str) -> &str {
let rest = text.strip_prefix('`').unwrap_or("");
let end = rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_').unwrap_or(rest.len());
rest.get(..end).unwrap_or("")
}
@@ -357,6 +451,18 @@ fn closes_conditional(t: &Token) -> bool {
directive_word(t) == "endif"
}
/// Move the comments written at or after byte `gap` out of `queue` and onto
/// `out`, in source order, leaving the earlier ones queued where they were.
fn take_since(queue: &mut Vec<Comment>, gap: u32, out: &mut Vec<Comment>) {
for c in std::mem::take(queue) {
if c.span.start >= gap {
out.push(c);
} else {
queue.push(c);
}
}
}
/// Split an optional [`Name`] into the `(text, span)` pair the nodes that keep
/// a name in a `String` field store it as.
fn split_label(name: Option<Name>) -> (Option<String>, Option<TextRange>) {
@@ -754,11 +860,33 @@ impl<'a> Parser<'a> {
/// [`Parser::take_before_sep`] is: a construct that wrote no such bracket
/// must leave the comments for whoever comes next, and stealing them here
/// would move them backwards across a token.
///
/// Only the comments written in the **gap that ends at this bracket** are
/// taken — see [`Parser::take_gap`].
fn take_before_open(&mut self, open: &str) -> Vec<Comment> {
if !self.cur().is_sym(open) {
return Vec::new();
}
self.take_dangling()
self.take_gap()
}
/// The comments written in the gap that ends at the cursor: those starting
/// at or after the end of the last token consumed.
///
/// The narrow sibling of [`Parser::take_dangling`], for the sites that own
/// *one* gap rather than everything still queued. A comment queued from
/// further back was written somewhere else and belongs to whoever owns
/// that place — `if (` ⏎ `// why` ⏎ `!f()` queues the comment on the `(`
/// of the **condition**, and neither `f`'s own `(` nor the inside of its
/// empty `()` may print it. Nothing is dropped: what is left queued is
/// harvested by the next node that takes meta.
fn take_gap(&mut self) -> Vec<Comment> {
let gap = self.last_end();
let mut out = Vec::new();
take_since(&mut self.pending_trailing, gap, &mut out);
take_since(&mut self.pending_leading, gap, &mut out);
take_since(&mut self.tokens[self.pos].leading, gap, &mut out);
out
}
/// Consume the compiler directives — and the standalone macro invocations
@@ -775,6 +903,9 @@ impl<'a> Parser<'a> {
fn take_list_directives(&mut self, out: &mut Vec<ListDirective>, before: usize) -> Harvested {
let mut found = Harvested::default();
while self.cur().kind == TokenKind::Directive || self.at_macro_item() {
if self.at_outer_arm_split(out) {
break;
}
let mut meta = self.take_meta();
let raw = self.take_raw_text();
meta.trailing = self.take_trailing();
@@ -786,6 +917,55 @@ impl<'a> Parser<'a> {
found
}
/// True when the directive at the cursor continues or closes a conditional
/// region **this list did not open**, while a region opened at item scope
/// is still live.
///
/// Such a directive is not conditioning list *elements* — it is the seam
/// where the whole item splits into rival spellings that share one list:
///
/// ```verilog
/// `ifdef DISABLE_ROM_INTEGRITY_CHECK
/// chip_earlgrey_asic #(.SecRomCtrlDisableScrambling(1'b1)) dut (
/// `else
/// chip_earlgrey_asic dut (
/// `endif
/// .POR_N(...), ...
/// );
/// ```
///
/// Harvesting the `` `else `` here would leave the parser reading the next
/// arm's *head* (`chip_earlgrey_asic dut`) as connection elements, and it
/// fails two tokens later with a diagnostic three lines from the defect.
/// Refusing it lets the item fail on the directive itself, where
/// [`Parser::at_split_conditional`] recognizes the shape and captures the
/// whole instantiation verbatim — the treatment the arms of a split region
/// have had since `docs/features/directive-split/README.md`.
///
/// `taken` is what this list has harvested so far, which is the only
/// scope that can have opened a region the directive legitimately ends.
fn at_outer_arm_split(&self, taken: &[ListDirective]) -> bool {
let t = self.cur();
if !continues_conditional(t) && !closes_conditional(t) {
return false;
}
// The same "a region is live" guard the split recovery makes: with
// nothing open at item scope there is no outer arm to belong to, and
// the directive is ordinary conditional text inside the list.
if self.open_conds == 0 {
return false;
}
let mut open = 0i32;
for d in taken {
match directive_word_of(&d.raw.text) {
"ifdef" | "ifndef" => open += 1,
"endif" => open -= 1,
_ => {}
}
}
open <= 0
}
/// Comments sitting right before a closing keyword (`end`, `endmodule`,
/// ...) — they belong inside the enclosing construct.
fn take_dangling(&mut self) -> Vec<Comment> {
@@ -1670,12 +1850,19 @@ impl<'a> Parser<'a> {
/// `solve ... before`, `inside`, `foreach`, `if`/`else`) that lucisv models
/// none of, and reflowing it has no payoff, so the block is copied out of
/// the source by span. A prototype (`constraint c;`) has no braces.
///
/// The name may carry a `my_class::` scope — the out-of-block constraint
/// definition of an `extern constraint` prototype (IEEE 1800 §18.5.2),
/// written at file or package scope. That is the constraint sibling of
/// `function my_class::method(...)`, so it reuses the same scoped-name
/// path; the scope is only consumed, since the whole item is verbatim and
/// binds no name either way.
fn parse_constraint(&mut self) -> PResult<RawText> {
let start = self.here();
let col = self.cur().col;
self.take_member_prefix();
self.expect_kw("constraint")?;
self.expect_name()?;
self.parse_method_name()?;
if !self.eat_sym(";") {
self.expect_sym("{")?;
self.skip_balanced("{", "}")?;
@@ -1904,15 +2091,43 @@ impl<'a> Parser<'a> {
}
}
/// Turn an item that is really one arm of a split conditional region into
/// a verbatim block, or hand `err` back untouched.
/// Turn an item that is really one arm of a split conditional region — or
/// one whose own region splits it — into a verbatim block, or hand `err`
/// back untouched.
///
/// The two shapes are mirror images and are tried in that order:
///
/// - the item **is an arm** of a region opened before it started, and
/// failed on the `` `else `` / `` `endif `` that closes it
/// ([`Parser::at_split_conditional`]);
/// - the item **opened** a region part-way through and failed on the
/// `` `ifdef `` itself ([`Parser::at_opening_split`]).
fn split_conditional_item(&mut self, mark: &ItemMark, err: ParseError) -> PResult<ItemKind> {
if !self.at_split_conditional(mark) {
return Err(err);
if self.at_split_conditional(mark) {
if let Some((end_pos, conds_after)) = self.scan_split_extent(mark) {
// The block swallowed the region's own `else / `endif, which
// *are* item-scope nesting even though they now sit inside
// opaque bytes. The extent scan already worked out what they
// leave open, so this is the second and last place
// `open_conds` moves.
self.open_conds = conds_after;
return Ok(ItemKind::Verbatim(self.capture_split(mark, end_pos)));
}
}
let Some((end_pos, conds_after)) = self.scan_split_extent(mark) else {
return Err(err);
};
if self.at_opening_split(mark) {
if let Some(end_pos) = self.scan_opening_split_extent(mark) {
// No `open_conds` adjustment: every exit of the scan leaves
// conditional nesting back at zero, so the block is
// conditional-balanced and item scope is undisturbed.
return Ok(ItemKind::Verbatim(self.capture_split(mark, end_pos)));
}
}
Err(err)
}
/// Replace the construct that began at `mark` with the source bytes
/// running from its first token to `end_pos`, and put the cursor there.
fn capture_split(&mut self, mark: &ItemMark, end_pos: usize) -> RawText {
self.diagnostics.truncate(mark.diags);
let start = self.tokens[mark.pos].span.start;
let col = self.tokens[mark.pos].col;
@@ -1926,12 +2141,7 @@ impl<'a> Parser<'a> {
while self.pos < end_pos && !self.at_eof() {
self.bump();
}
// The block swallowed the region's own `else / `endif, which *are*
// item-scope nesting even though they now sit inside opaque bytes.
// The extent scan already worked out what they leave open, so this is
// the second and last place `open_conds` moves.
self.open_conds = conds_after;
Ok(ItemKind::Verbatim(self.verbatim_since(start, col)))
self.verbatim_since(start, col)
}
/// True when the item that began at `mark` failed *because* it is one arm
@@ -2058,6 +2268,161 @@ impl<'a> Parser<'a> {
None
}
/// True when the construct that began at `mark` failed *because* it opened
/// a conditional region part-way through and the rest of it lives in the
/// arms:
///
/// ```verilog
/// assign aes_ctrl_rnd_ctr =
/// `ifdef GATE_LEVEL
/// `AES_HIER.u_aes_cipher_control.mr_rnd_ctr[3:0];
/// `else
/// `AES_HIER.u_aes_cipher_control.rnd_ctr;
/// `endif
/// ```
///
/// This is [`Parser::at_split_conditional`]'s mirror image. There the
/// failure is on the directive that *closes* a region opened before the
/// construct; here it is on the `` `ifdef `` that opens one inside it. An
/// expression has no "this might be a pass-through directive" branch — the
/// directive pass-through lives at item- and statement-list boundaries and
/// in the four bracketed-list sites `directives-in-lists` covers — so the
/// parse fails immediately, before any bracket is opened and before the
/// closing-split trigger can ever be evaluated.
///
/// Two things must hold at once:
///
/// 1. the cursor stands on an `` `ifdef `` / `` `ifndef ``. Any other
/// directive mid-expression (`` `include ``, a bare `` `endif ``) is
/// still an ordinary parse error;
/// 2. the construct is **one unterminated run** reaching that directive —
/// it has consumed at least one token and no `;` at bracket depth zero
/// since it started. A failure that propagated up from deeper inside an
/// already-terminated construct would otherwise capture the whole
/// enclosing item on a guess; this is what keeps the recovery at the
/// innermost construct the region actually splits.
fn at_opening_split(&self, mark: &ItemMark) -> bool {
if !opens_conditional(self.cur()) {
return false;
}
if self.pos <= mark.pos {
return false;
}
let mut brackets = 0i32;
for t in self.tokens.get(mark.pos..self.pos).unwrap_or_default() {
if t.is_sym("(") || t.is_sym("[") || t.is_sym("{") {
brackets += 1;
} else if t.is_sym(")") || t.is_sym("]") || t.is_sym("}") {
brackets -= 1;
} else if t.is_sym(";") && brackets <= 0 {
return false;
}
}
true
}
/// One past the last token of the construct a region opened inside it
/// splits, or `None` when the file holds no such end.
///
/// Like [`Parser::scan_split_extent`] the scan follows the **first** arm
/// and skips the alternatives whole, because the arms are rival spellings
/// of the same thing and counting every arm's brackets would demand as
/// many closers as there are arms.
///
/// Where the construct ends depends on which side of the region its
/// terminator was written on, and both spellings are in the corpus:
///
/// - the arms each carry their own `;` (`chip_if.sv`), so the construct
/// ends at the `` `endif `` that closes the region — there is no `;`
/// after it, and scanning on would swallow the next item;
/// - the region is balanced *inside* the construct and the `;` comes after
/// it (`chip_earlgrey_asic.sv`, `jtag_dtm_reg_block.sv`), so the
/// construct ends at that `;`.
///
/// `terminated_in_arm` is what tells them apart: a `;` met at bracket
/// depth zero while a region is still open means the tail is inside the
/// arms.
///
/// A head that opens a body ends at its closing keyword instead, and one
/// whose ending is not modeled ([`ConstructEnd::Unknown`]) is refused.
///
/// Every exit leaves conditional nesting back at zero, so a captured block
/// is conditional-balanced and item-scope nesting is undisturbed.
fn scan_opening_split_extent(&self, mark: &ItemMark) -> Option<usize> {
let end = construct_end(self.tokens.get(mark.pos..)?);
if end == ConstructEnd::Unknown {
return None;
}
let semi_ends = end == ConstructEnd::Semi;
let mut cond = 0i32;
let mut brackets = 0i32;
let mut terminated_in_arm = false;
let mut i = mark.pos;
while let Some(t) = self.tokens.get(i) {
if t.kind == TokenKind::Eof {
return None;
}
if t.kind == TokenKind::Directive {
if opens_conditional(t) {
cond += 1;
} else if closes_conditional(t) {
cond -= 1;
if cond < 0 {
return None;
}
if semi_ends && cond == 0 && terminated_in_arm {
return Some(i + 1);
}
} else if continues_conditional(t) {
// A `else / `elsif with nothing open is a stray closer,
// not an arm boundary: broken input, and the parse error
// stands — the same refusal the closing-split scan makes.
if cond == 0 {
return None;
}
i = self.skip_conditional_arms(i + 1)?;
cond -= 1;
if semi_ends && cond == 0 && terminated_in_arm {
return Some(i);
}
continue;
}
} else if let ConstructEnd::Keyword(kw) = end {
if t.is_kw(kw) && brackets == 0 && cond == 0 {
return Some(self.past_end_label(i + 1));
}
}
if t.is_sym("(") || t.is_sym("[") || t.is_sym("{") {
brackets += 1;
} else if t.is_sym(")") || t.is_sym("]") || t.is_sym("}") {
brackets -= 1;
if brackets < 0 {
return None;
}
} else if semi_ends && t.is_sym(";") && brackets == 0 {
if cond == 0 {
return Some(i + 1);
}
terminated_in_arm = true;
}
i += 1;
}
None
}
/// One past `after_kw`'s optional `: name` — the label a closing keyword
/// may carry (`endfunction : new`), which belongs inside the block with
/// the keyword it names.
fn past_end_label(&self, after_kw: usize) -> usize {
let colon = self.tokens.get(after_kw).is_some_and(|t| t.is_sym(":"));
let name = self.tokens.get(after_kw + 1).is_some_and(|t| t.kind == TokenKind::Ident);
if colon && name {
after_kw + 2
} else {
after_kw
}
}
/// True when the cursor opens a parameterized type's `#( ... )`.
fn at_type_params(&self) -> bool {
self.cur().is_sym("#") && self.nth(1).is_sym("(")
@@ -3655,7 +4020,12 @@ impl<'a> Parser<'a> {
let tok = &mut self.tokens[self.pos];
meta.leading.append(&mut tok.leading);
}
let kind = self.parse_stmt_kind()?;
let mark =
ItemMark { pos: self.pos, conds: self.open_conds, diags: self.diagnostics.len() };
let kind = match self.parse_stmt_kind() {
Ok(kind) => kind,
Err(e) => self.split_conditional_stmt(&mark, e)?,
};
let span = self.span_from(start);
if meta.trailing.is_none() {
meta.trailing = self.take_trailing();
@@ -3663,6 +4033,42 @@ impl<'a> Parser<'a> {
Ok(Stmt { meta, kind, span })
}
/// The statement half of [`Parser::split_conditional_item`]: a statement a
/// region opened inside it splits becomes a verbatim block.
///
/// `jtag_dtm_reg_block.sv:173` is the corpus shape — a `` `ifdef `` between
/// two named arguments of a call, deep inside a function body:
///
/// ```verilog
/// abits.configure(
/// .volatile(0),
/// `ifdef USE_DMI_INTERFACE
/// .reset(32'h10),
/// `else
/// .reset(32'h07),
/// `endif
/// .has_reset(1));
/// ```
///
/// Only the **opening** shape is recognized here. The closing one is
/// item-scope by construction: [`Parser::open_conds`] counts the
/// `` `ifdef ``s consumed as *items*, so `mark.conds` inside a body would
/// be answering a question about a different scope. Nothing in the corpus
/// asks for it, and guessing would widen the net for no evidence.
///
/// Running here rather than only at item level is what keeps the capture
/// at the innermost construct: a statement failure that reached
/// `parse_item_inner` would be scanned from the enclosing `module` or
/// `class` keyword instead.
fn split_conditional_stmt(&mut self, mark: &ItemMark, err: ParseError) -> PResult<StmtKind> {
if self.at_opening_split(mark) {
if let Some(end_pos) = self.scan_opening_split_extent(mark) {
return Ok(StmtKind::Verbatim(self.capture_split(mark, end_pos)));
}
}
Err(err)
}
fn parse_stmt_kind(&mut self) -> PResult<StmtKind> {
if self.at_macro_item() || self.at_spaced_macro_call() {
return Ok(StmtKind::MacroStmt(self.parse_macro_call()?));
@@ -4569,7 +4975,10 @@ impl<'a> Parser<'a> {
ExprItem { meta, expr: first_expr, span: self.span_from(arg_start) };
args = self.parse_expr_list(first, ")")?;
} else {
comments.dangling = self.take_dangling();
// Only what was written *inside* the empty `()`: a comment
// queued from before the callee belongs to whoever owns
// the place it was written, not to this argument list.
comments.dangling = self.take_gap();
}
self.expect_sym(")")?;
expr = self.expr_at(
@@ -6177,13 +6586,27 @@ mod tests {
}
#[test]
fn a_directive_inside_a_connection_is_still_a_parse_error() {
// A directive runs to end of line, so it can only stand *between*
// connections. One written inside a connection's parens is out of
// scope by design; this pins that it is refused rather than half-read.
fn a_directive_inside_a_connection_is_captured_or_refused_by_kind() {
// Superseded in part by `directive-in-statements` (2026-08-29). A
// *conditional* region inside a connection's parens is the bucket-7
// shape — `chip_earlgrey_asic.sv` writes one inside a parameter
// value's concatenation — so it is now captured verbatim rather than
// refused. `directives-in-lists` still does not read it as a list
// element: the whole instantiation becomes opaque bytes.
let src =
"module m;\n sub u (\n .a(\n`ifdef X\n y\n`endif\n )\n );\nendmodule\n";
assert!(parse(tokenize(src).expect("lex error"), src).is_err());
let f = parse_ok(src);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.starts_with("sub u ("), "{:?}", raw.text);
assert!(raw.text.ends_with(");"), "{:?}", raw.text);
// Any *other* directive there is still an ordinary parse error: the
// recovery triggers on `ifdef / `ifndef only.
let msg = parse_err(
"module m;\n sub u (\n .a(\n`include \"x.vh\"\n y\n )\n );\nendmodule\n",
);
assert!(msg.contains("`include"), "{msg}");
}
/// The strict entry point keeps its contract: it fails at the *first*
@@ -6404,6 +6827,59 @@ mod tests {
assert_eq!(items[0].meta.trailing.as_ref().expect("the comment survived").text, "// why");
}
// ------------------------------------------------------------------
// Out-of-block constraints
// (`docs/features/out-of-class-constraints/README.md`)
// ------------------------------------------------------------------
#[test]
fn an_out_of_block_constraint_is_a_file_scope_verbatim_item() {
let src = "constraint my_item::delay_c {\n soft delay dist {0 :/ 5};\n}\n";
let f = parse_ok(src);
let ItemKind::Verbatim(raw) = &f.items[0].kind else { panic!("expected a verbatim block") };
assert_eq!(raw.text, "constraint my_item::delay_c {\n soft delay dist {0 :/ 5};\n}");
assert_eq!(raw.text, src[raw.span.as_range()], "the capture is the source bytes");
}
#[test]
fn an_out_of_block_constraint_scope_may_be_a_chain() {
// `pkg::cls::name` — the same chain `parse_method_name` accepts for an
// out-of-body method. Nothing is bound either way, so all that matters
// is that the whole chain is consumed before the `{`.
let f = parse_ok("constraint pkg::cls::deep_c { x < 4; }\n");
let ItemKind::Verbatim(raw) = &f.items[0].kind else { panic!("expected a verbatim block") };
assert_eq!(raw.text, "constraint pkg::cls::deep_c { x < 4; }");
}
#[test]
fn an_out_of_block_constraint_lives_in_a_package_too() {
let f = parse_ok("package p;\n constraint c::x { a > 0; }\nendpackage\n");
let ItemKind::Package { items, .. } = &f.items[0].kind else {
panic!("expected a package")
};
assert!(matches!(items[0].kind, ItemKind::Verbatim(_)), "{:?}", items[0].kind);
}
#[test]
fn an_out_of_block_constraint_keeps_its_trailing_semicolon_and_comments() {
// `constraint C::c { ... };` — the stray `;` belongs to the block, and
// a comment written past the block must stay outside the capture.
let f = parse_ok("// head\nconstraint c::x { a == 0; }; // tail\nint b;\n");
let ItemKind::Verbatim(raw) = &f.items[0].kind else { panic!("expected a verbatim block") };
assert_eq!(raw.text, "constraint c::x { a == 0; };");
assert!(!raw.text.contains("tail"), "the capture swallowed the comment: {:?}", raw.text);
assert_eq!(f.items[0].meta.leading[0].text, "// head");
assert_eq!(f.items[0].meta.trailing.as_ref().expect("trailing comment").text, "// tail");
}
#[test]
fn an_in_class_constraint_still_rejects_a_scope_free_syntax_error() {
// The widened name must not swallow a genuinely broken header: the
// `::` path only accepts an identifier after the separator.
assert_eq!(parse_err("constraint c:: { a == 0; }\n"), "expected identifier (found \"{\")");
assert_eq!(parse_err("constraint 4::x { a == 0; }\n"), "expected identifier (found \"4\")");
}
// ------------------------------------------------------------------
// Concurrent assertions (`docs/features/assertions/README.md`)
// ------------------------------------------------------------------
@@ -7694,4 +8170,293 @@ mod tests {
["directive:`ifdef A", "decl", "directive:`else", "decl", "directive:`endif"]
);
}
// ------------------------------------------------------------------
// directive-in-statements: a region opened *inside* a construct
// (`docs/features/directive-in-statements/README.md`)
// ------------------------------------------------------------------
#[test]
fn an_ifdef_splitting_an_assigns_rhs_is_captured_verbatim() {
// hw/top_earlgrey/dv/env/chip_if.sv:1189-1194, the anchor shape: each
// arm carries the construct's own `;`, so the block ends at the
// `endif -- there is no `;` after it to stop at.
let src = "module m;\n assign y =\n`ifdef GATE_LEVEL\n a.b.mr_rnd_ctr[3:0];\n`else\n a.b.rnd_ctr;\n`endif\n wire z;\nendmodule\n";
let f = parse_ok(src);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.starts_with("assign y ="), "{:?}", raw.text);
assert!(raw.text.ends_with("`endif"), "{:?}", raw.text);
assert!(matches!(m.items[1].kind, ItemKind::DataDecl(_)), "the next item survived");
}
#[test]
fn an_ifdef_between_call_arguments_captures_the_statement_only() {
// hw/dv/sv/jtag_agent/jtag_dtm_reg_block.sv:173. The region is
// balanced inside the call's parens, so the statement ends at its own
// `;` -- and the capture is the *statement*, not the enclosing
// function, which is what running the recovery at statement level
// buys.
let src = "module m;\n initial begin\n a.configure(\n .size(2),\n`ifdef USE_DMI\n .reset(32'h10),\n`else\n .reset(32'h07),\n`endif\n .has_reset(1));\n b = 1;\n end\nendmodule\n";
let f = parse_ok(src);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected an initial") };
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") };
let StmtKind::Verbatim(raw) = &stmts[0].kind else { panic!("expected a verbatim stmt") };
assert!(raw.text.starts_with("a.configure("), "{:?}", raw.text);
assert!(raw.text.ends_with(".has_reset(1));"), "{:?}", raw.text);
assert!(matches!(stmts[1].kind, StmtKind::Assign { .. }), "the next statement survived");
}
#[test]
fn an_ifdef_inside_an_instantiations_parameter_value_captures_the_instantiation() {
// hw/top_earlgrey/rtl/autogen/chip_earlgrey_asic.sv:621 -- a region
// between the elements of a concatenation, three brackets deep inside
// a parameter override. The `;` after the whole instantiation ends it.
let src = "module m;\n padring #(\n .PadType({\n A,\n`ifdef ANALOGSIM\n \
'0,\n`else\n CC2,\n`endif\n B\n })\n ) u_padring (\n \
.clk(c)\n );\n wire z;\nendmodule\n";
let f = parse_ok(src);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.starts_with("padring #("), "{:?}", raw.text);
assert!(raw.text.ends_with(");"), "{:?}", raw.text);
assert!(matches!(m.items[1].kind, ItemKind::DataDecl(_)), "the next item survived");
}
#[test]
fn a_split_function_header_captures_through_endfunction() {
// hw/dv/sv/jtag_agent/jtag_dtm_reg_block.sv:273. A `function`'s own
// `;` closes its *header*: stopping there left `super.new(...)` behind
// as an item and the file failed three lines into the body. The
// closing keyword, and the `: label` it may carry, end the block.
let src = "class c;\n function new(string name = \"\",\n`ifdef USE_DMI\n int unsigned n = 50,\n`else\n int unsigned n = 41,\n`endif\n int cov = 0);\n super.new(name, n, cov);\n endfunction : new\n int after;\nendclass\n";
let f = parse_ok(src);
let ItemKind::Class(c) = &f.items[0].kind else { panic!("expected a class") };
let ItemKind::Verbatim(raw) = &c.items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.starts_with("function new("), "{:?}", raw.text);
assert!(raw.text.ends_with("endfunction : new"), "{:?}", raw.text);
assert!(matches!(c.items[1].kind, ItemKind::DataDecl(_)), "the next item survived");
}
#[test]
fn an_ifdef_that_splits_an_instantiation_head_is_still_the_closing_shape() {
// hw/top_earlgrey/dv/tb/tb.sv:113 (bucket 13): two instantiation heads
// behind one `ifdef sharing a connection list. The region opened
// *before* the item, so this is `at_split_conditional`'s shape -- what
// this round changed is that `take_list_directives` no longer harvests
// the `else as a list element and hides the seam.
let src = "module m;\n`ifdef DISABLE_ROM\n chip #(\n .Scramble(1'b1)\n ) dut \
(\n`else\n chip dut (\n`endif\n .POR_N(p),\n .USB_P(u)\n );\n wire \
z;\nendmodule\n";
let f = parse_ok(src);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
assert!(matches!(m.items[0].kind, ItemKind::Directive(_)), "the `ifdef stayed an item");
let ItemKind::Verbatim(raw) = &m.items[1].kind else { panic!("expected a verbatim block") };
assert!(raw.text.starts_with("chip #("), "{:?}", raw.text);
assert!(raw.text.ends_with(");"), "{:?}", raw.text);
assert!(matches!(m.items[2].kind, ItemKind::DataDecl(_)), "the next item survived");
}
#[test]
fn a_list_internal_region_is_still_harvested_as_list_elements() {
// The other side of the `take_list_directives` guard: a region opened
// *and* closed inside the connection list still conditions elements,
// and the instantiation still parses as an instantiation. Written
// inside an outer region, which is the state that arms the guard.
let src = "module m;\n`ifdef OUTER\n chip dut (\n .A(a),\n`ifdef ANALOGSIM\n \
.CC1(c1),\n`else\n .CC1(d1),\n`endif\n .B(b)\n );\n`endif\nendmodule\n";
let f = parse_ok(src);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Instantiation(inst) = &m.items[1].kind else {
panic!("expected an instantiation, got {:?}", split_items(&f))
};
assert_eq!(inst.instances[0].conn_directives.len(), 3, "`ifdef / `else / `endif harvested");
}
#[test]
fn an_opening_split_leaves_item_scope_nesting_alone() {
// Every exit of the extent scan has conditional nesting back at zero,
// so a captured block is conditional-balanced by construction.
assert_eq!(
open_conds_after(
"module m;\n assign y =\n`ifdef A\n a;\n`else\n b;\n`endif\nendmodule\n"
),
0
);
assert_eq!(
open_conds_after(
"`ifdef OUTER\nmodule m;\n assign y =\n`ifdef A\n a;\n`else\n \
b;\n`endif\nendmodule\n"
),
1,
"the region around it is untouched"
);
}
#[test]
fn the_opening_split_refuses_everything_it_does_not_model() {
// Each of these reaches `at_opening_split` or `scan_opening_split_extent`
// and is handed its parse error back. Verified against the release
// binary on the real files as well; see the feature README.
for (why, src) in [
(
"a non-conditional directive is not a split",
"module m;\n assign y =\n`include \"x.vh\"\n a;\nendmodule\n",
),
("a stray closer opens nothing", "module m;\n assign y =\n`endif\n a;\nendmodule\n"),
("an unterminated region has no end", "module m;\n assign y =\n`ifdef A\n a;\n"),
(
"the construct never ends",
"module m;\n assign y =\n`ifdef A\n a\n`endif\nendmodule\n",
),
(
"a plain syntax error near a directive stays one",
"module m;\n`ifdef A\n assign y = ;\n`endif\nendmodule\n",
),
(
"brackets that do not balance across the arms",
"module m;\n assign y = (\n`ifdef A\n a;\n`else\n b);\n`endif\nendmodule\n",
),
(
"a body-opening head whose end is not modeled",
"module m;\n initial\n case (\n`ifdef A\n x\n`else\n \
y\n`endif\n )\n 1: a = 1;\n endcase\nendmodule\n",
),
] {
let toks = tokenize(src).expect("lex error");
assert!(parse(toks, src).is_err(), "should still refuse: {why}");
}
}
#[test]
fn a_comment_after_an_opening_bracket_is_not_stolen_by_an_inner_call() {
// The handshake `docs/features/formatter-bug-fixes/README.md` filed:
// `take_before_open` drained the whole pending queue, so a comment
// written after `if (` was printed between the condition's first
// callee and its own `(`. Both of the call's comment slots must now
// leave it queued for whoever owns the place it was written.
let src = "module m;\n initial begin\n if (// why\n !en() || b\n ) \
begin\n x = 1;\n end\n end\nendmodule\n";
let f = parse_ok(src);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected an initial") };
let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") };
let StmtKind::If { cond, then, .. } = &stmts[0].kind else { panic!("expected an if") };
// Neither `before_open` (the `(` of `en(`) nor `dangling` (the inside
// of the empty `()`) may hold it.
let ExprKind::Binary { lhs, .. } = &cond.kind else { panic!("expected a binary") };
let ExprKind::Unary { expr, .. } = &lhs.kind else { panic!("expected a unary") };
let ExprKind::Call { comments, .. } = &expr.kind else { panic!("expected a call") };
assert!(comments.before_open.is_empty(), "{:?}", comments.before_open);
assert!(comments.dangling.is_empty(), "{:?}", comments.dangling);
// It stays queued and reaches the body's leading comments, which is
// where the formatter's `header_parens` takes it back from.
assert_eq!(then.meta.leading.len(), 1, "{:?}", then.meta.leading);
assert!(then.meta.leading[0].text.contains("why"));
}
#[test]
fn a_comment_actually_written_before_a_bracket_is_still_taken() {
// The other side of the same guard: `take_before_open` must keep
// doing its job for the comments written in the gap it owns.
let f = parse_ok("module m\n // why\n #(\n parameter int W = 1\n ) ();\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
assert_eq!(m.param_comments.len(), 1, "{:?}", m.param_comments);
assert!(m.param_comments[0].text.contains("why"));
let f = parse_ok("module m;\n initial x = f\n // why\n ();\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected an initial") };
let StmtKind::Assign { rhs, .. } = &stmt.kind else { panic!("expected an assignment") };
let ExprKind::Call { comments, .. } = &rhs.kind else { panic!("expected a call") };
assert_eq!(comments.before_open.len(), 1, "{:?}", comments.before_open);
}
// ------------------------------------------------------------------
// QA (2026-08-29): adversarial coverage for directive-in-statements,
// none of which turned up a bug -- pinned so a future refactor of
// `scan_opening_split_extent`/`at_outer_arm_split` cannot silently
// regress any of them.
// ------------------------------------------------------------------
#[test]
fn a_nested_ifdef_with_its_own_elsif_survives_inside_an_opening_split_under_an_outer_region() {
// Three levels of conditional at once: an outer region already open
// when the item starts, an opening split inside the assign's RHS, and
// a *nested* `ifdef / `elsif / `else / `endif fully inside that
// split's first arm. The nested region's own arms must not be
// mistaken for the split's own `else / `endif, and `open_conds` must
// land back at 1 (the outer region only) once the whole thing is
// captured.
let src = "`ifdef OUTER\nmodule m;\n assign y =\n`ifdef A\n`ifdef NESTED\n a\n\
`elsif NESTED2\n a2\n`else\n a3\n`endif\n + 1;\n`elsif A2\n q;\n\
`else\n b;\n`endif\n wire z;\nendmodule\n";
let f = parse_ok(src);
assert_eq!(open_conds_after(src), 1, "the outer region is still open at eof");
// items[0] is the outer `ifdef OUTER` itself, a file-scope directive.
let ItemKind::Module(m) = &f.items[1].kind else { panic!("expected a module") };
let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.starts_with("assign y ="), "{:?}", raw.text);
assert!(raw.text.contains("`ifdef NESTED"), "the nested region is inside the capture");
assert!(raw.text.ends_with("`endif"), "{:?}", raw.text);
assert!(matches!(m.items[1].kind, ItemKind::DataDecl(_)), "the next item survived");
}
#[test]
fn an_elsif_chain_in_an_opening_split_is_captured_through_the_final_endif() {
// Only if/else was exercised elsewhere; a 4-arm chain must still end
// at the one closing `endif, not at an intermediate `elsif.
let src = "module m;\n assign y =\n`ifdef A\n a;\n`elsif B\n b;\n`elsif C\n \
c;\n`else\n d;\n`endif\n wire z;\nendmodule\n";
let f = parse_ok(src);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.contains("`elsif B") && raw.text.contains("`elsif C"), "{:?}", raw.text);
assert!(raw.text.ends_with("`endif"), "{:?}", raw.text);
assert!(matches!(m.items[1].kind, ItemKind::DataDecl(_)), "the next item survived");
}
#[test]
fn a_block_comment_naming_endif_does_not_fool_the_extent_scan() {
// The extent scan walks tokens, not source text -- a comment is never
// a `TokenKind::Directive`, so text that merely *mentions* `endif
// inside a comment must not be mistaken for the real closer.
let src = "module m;\n assign y =\n`ifdef GATE_LEVEL\n /* not a real `endif here */ \
a;\n`else\n b;\n`endif\n wire z;\nendmodule\n";
let f = parse_ok(src);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.contains("not a real"), "{:?}", raw.text);
assert!(raw.text.ends_with("`endif"), "{:?}", raw.text);
assert!(matches!(m.items[1].kind, ItemKind::DataDecl(_)), "the next item survived");
}
#[test]
fn an_opening_split_that_is_the_last_item_does_not_eat_the_closing_keyword() {
// No sibling item follows the split in either container -- the scan
// must stop at the split's own terminator and never wander into
// `endmodule`/`endclass`.
let module_src =
"module m;\n assign y =\n`ifdef A\n a;\n`else\n b;\n`endif\nendmodule\n";
let f = parse_ok(module_src);
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
assert_eq!(m.items.len(), 1, "{:?}", split_items(&f));
let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") };
assert!(raw.text.ends_with("`endif"), "{:?}", raw.text);
let class_src = "class c;\n function new();\n`ifdef A\n super.new(1);\n`else\n \
super.new(2);\n`endif\n endfunction\nendclass\n";
// The `ifdef here opens at a *statement-list* boundary (the function
// body's first statement), which is ordinary directive pass-through,
// not an opening split -- included as the sibling case that must
// stay a pass-through rather than being swept into this recovery.
let f = parse_ok(class_src);
let ItemKind::Class(c) = &f.items[0].kind else { panic!("expected a class") };
let ItemKind::Function(func) = &c.items[0].kind else { panic!("expected a function") };
assert!(
matches!(func.stmts[0].kind, StmtKind::Directive(_)),
"a directive starting a statement list is pass-through, not a split"
);
}
}
@@ -248,6 +248,45 @@ fn tolerant_parse_equals_strict_parse_on_valid_sources() {
println!("{valid} valid sources agreed with the strict parser, {invalid} reported errors");
}
/// The out-of-block constraint cascade, pinned as a regression
/// (`docs/features/out-of-class-constraints/README.md`).
///
/// Before the fix, `constraint C::name { ... }` failed one token into the
/// header (`expected `{` (found "::")`); the recovery loop then resynchronized
/// inside the constraint body, and every out-of-block item after it produced
/// its own diagnostics. On the real corpus that turned one construct into 322
/// diagnostics in `cip_base_vseq.sv` and 274 in `hmac_base_vseq.sv` — a buffer
/// an editor cannot show usefully. This fixture is that shape in miniature:
/// with the fix it must be silent, not merely quieter.
#[test]
fn out_of_block_constraints_do_not_cascade() {
let src = "\
class my_seq;
rand int num_trans;
rand int delay;
extern constraint num_trans_c;
extern constraint delay_c;
extern function void configure();
endclass : my_seq
constraint my_seq::num_trans_c {
num_trans inside {[1:20]};
solve num_trans before delay;
}
constraint my_seq::delay_c {
soft delay dist {0 :/ 5, [1:10] :/ 5};
}
function void my_seq::configure();
num_trans = 1;
endfunction : my_seq
";
let (_, diags) = parse_source_tolerant(src);
assert!(diags.is_empty(), "out-of-block constraints still report: {diags:?}");
assert!(parse_source(src).is_ok(), "strict parse must agree with tolerant");
}
// ----------------------------------------------------------------------
// Guarantee 2: diagnostics and error nodes stay inside the file
// ----------------------------------------------------------------------
+3
View File
@@ -71,6 +71,9 @@ const SOURCES: &[&str] = &[
"virtual class base #(parameter int W = 8) extends pkg::top #(.A(1), b) implements i, j;\n rand bit [W-1:0] v;\n local int n;\n virtual my_if h;\n pure virtual function void f();\n extern task t(int x);\nendclass : base\n",
"class c;\n port_t #(bit [3:0]) p;\n constraint x {\n a == 0; // why\n } // after\n covergroup g;\n coverpoint a;\n endgroup : g\n function new(string name);\n super.new(name);\n x = db#(virtual bus_if)::get(this);\n endfunction : new\nendclass\n",
"typedef class fwd;\npackage p;\n class inner extends fwd;\n endclass\nendpackage\nfunction void inner::configure(int x);\nendfunction\n",
// Out-of-block constraints: the verbatim leaf reached from item position,
// at file scope and inside a package, with a scope chain and a stray `;`.
"class c;\n extern constraint x;\nendclass\nconstraint c::x {\n a == 0; // why\n}; // after\npackage p;\n constraint q::inner::deep_c { b < 4; }\nendpackage\n",
// Dynamic types: queues, dynamic and associative arrays, `$` indexes,
// named call arguments, `case ... inside`, a bare event control.
"class c;\n string q[$] = {};\n rand int offset[];\n logic hits[*];\n string lut[string];\n item_t #(A, B) rq[NumInp-1:0][$:8];\n function void f(string ops[$], output int outs[]);\n q[$].label = ops[$-1];\n offset = new[n];\n endfunction\nendclass\n",
+34
View File
@@ -623,6 +623,40 @@ endclass
}
}
/// Pins the opacity promise `docs/features/out-of-class-constraints/README.md`
/// makes without a test of its own: an out-of-block `constraint C::name { ... }`
/// is exactly as opaque as the in-class form above — same `ItemKind::Verbatim(_)`
/// arm in `bind.rs`, reached by the same item walker, item position never
/// entered into it.
#[test]
fn an_out_of_block_constraint_is_absent_but_nothing_crashes() {
let src = "\
class my_seq;
rand int num_trans;
extern constraint num_trans_c;
endclass
constraint my_seq::num_trans_c {
num_trans inside {[1:20]};
}
";
let s = sem(src);
// No symbol for the constraint name, in-class prototype or out-of-block
// definition alike — both are `ItemKind::Verbatim(_)` leaves.
assert!(s.symbols().iter().all(|sym| sym.name != "num_trans_c"));
assert_eq!(
s.symbols().iter().map(|sym| sym.name.as_str()).collect::<Vec<_>>(),
vec!["my_seq", "num_trans"]
);
assert!(s.reference_at(nth(src, "num_trans inside", 0)).is_none());
// Queries at every offset stay panic-free.
for offset in 0..=src.len() as u32 {
let _ = s.definition_of(offset);
let _ = s.symbol_at(offset);
let _ = s.reference_at(offset);
}
}
// ----------------------------------------------------------------------
// Workspace index
// ----------------------------------------------------------------------
@@ -0,0 +1,608 @@
# directive-in-statements
## Goal
Stop refusing files where a `` `ifdef ``/`` `else ``/`` `endif `` region opens
**part-way through a construct** — splitting an assign's right-hand side, an
expression inside a bracketed list, a call's argument list, an instantiation's
parameter value, or a function's port list. This is bucket 7 of
`syntax_coverage.md` plus its bucket-13 sibling: 7 files across the OpenTitan
sweep, and the specific files are the point — **both chips' top-level
synthesizable RTL** (`chip_earlgrey_asic.sv`, `chip_earlgrey_cw340.sv`), **both
chips' DV probe interfaces** (`top_{earlgrey,darjeeling}/dv/env/chip_if.sv`,
anchor B), and **both chips' DUT top testbenches**
(`top_{earlgrey,darjeeling}/dv/tb/tb.sv`), plus `jtag_dtm_reg_block.sv`.
Such a region is not a tree, for the same reason `directive-split`'s already
was not: there is no AST that holds "either this expression or that one", and
no layout to apply to something that only becomes a construct after the
preprocessor has chosen an arm. So it joins the **verbatim** bucket — the exact
source bytes, re-indented on the first line only — reached by a *recovery*
after a real parse failure rather than by a grammar rule. This is the sequel
`syntax_coverage.md`'s own implementation note recommends: "the existing
`ItemKind::Verbatim` pattern extends naturally to capture from the failed
statement/instantiation through the shared terminator, exactly as
`directive-split` already does for item-level declarations."
## Assumptions
### The gap, stated as a mirror image
`directive-split` (2026-08-26) recovers when the failure lands on the directive
that **closes** a region opened *before* the construct started, with a bracket
the arm left open. This round is the other half: the failure lands on the
`` `ifdef `` that **opens** a region *inside* the construct.
```verilog
// closing shape (directive-split, 2026-08-26) -- the item IS an arm
`ifdef DSIM
privileged_reg_t implemented_csr[] = { <- fails at the `else below
`else
const privileged_reg_t implemented_csr[] = {
`endif
MVENDORID
};
// opening shape (this round) -- the item CONTAINS the region
assign aes_ctrl_rnd_ctr =
`ifdef GATE_LEVEL <- fails right here
`AES_HIER.u_aes_cipher_control.mr_rnd_ctr[3:0];
`else
`AES_HIER.u_aes_cipher_control.rnd_ctr;
`endif
```
None of the three existing directive features fire on the second shape, and
`syntax_coverage.md`'s Anchor B deep-dive says why: `directives-in-lists` /
`directives-in-instances` sit at the element boundaries of four *bracketed
lists* (port lists, parameter lists, enum members, instantiation
`#()`/connection lists) — an assign's RHS is a single expression, not a list;
`directive-split` needs a bracket already open at a *closing* directive; and
directive pass-through otherwise exists only at item- and statement-list
boundaries. An expression parse has no "this might be a pass-through directive"
branch at all, so it fails immediately, before any bracket is opened and before
`directive-split`'s trigger is ever evaluated.
### The opening trigger is two conditions, checked in `at_opening_split`
1. **The cursor stands on an `` `ifdef `` / `` `ifndef ``.** Every other
directive mid-expression is still an ordinary parse error — `` `include ``,
a bare `` `endif ``, a macro call. This is what keeps the net narrow: the
recovery is about conditional *regions*, not about directives in general.
2. **The construct is one unterminated run reaching that directive**: it has
consumed at least one token (a directive standing where an item or a
statement *begins* is an ordinary pass-through directive, unchanged), and
there is no `;` at bracket depth zero between its first token and the
cursor.
Condition 2 is the load-bearing one and it replaces `directive-split`'s
"a bracket is open" test, which cannot be reused here — at `chip_if.sv:1192`
nothing is open yet, the failure is three tokens into the item. What it buys is
that a failure which **propagated up** from somewhere deeper cannot capture the
construct that happens to enclose it: by the time an error inside a module body
reaches `parse_item_inner`, many `;` at depth zero have gone by, so the module
is refused as a candidate. Without it, one bad expression would turn an entire
`module` into opaque bytes on a guess.
### The extent follows the first arm, and ends on one of two terminators
`scan_opening_split_extent` walks from the construct's first token, tracking
brackets and conditional nesting, and — like `scan_split_extent` — on a
`` `else ``/`` `elsif `` it **skips the alternative arms whole** (reusing
`skip_conditional_arms`), because the arms are rival spellings of one thing and
counting all of their brackets would demand as many closers as there are arms.
Where it stops depends on which side of the region the construct's terminator
was written on, and **both spellings are in the corpus**:
| shape | corpus evidence | ends at |
|---|---|---|
| each arm carries the construct's own `;` | `chip_if.sv:1189` | the `` `endif `` closing the region |
| the region is balanced *inside* the construct | `chip_earlgrey_asic.sv:621`, `jtag_dtm_reg_block.sv:173` | the `;` after it |
`terminated_in_arm` is what tells them apart: a `;` met at bracket depth zero
while a region is still open means the tail lives inside the arms. Getting this
wrong in the first direction swallows the next item (there is no `;` after
`chip_if.sv`'s `` `endif ``); getting it wrong in the second truncates the
construct.
**Every exit leaves conditional nesting back at zero.** A captured block is
therefore conditional-balanced by construction, which is why this recovery —
unlike `directive-split`'s — needs no `open_conds` adjustment at all. Pinned by
`an_opening_split_leaves_item_scope_nesting_alone`.
### A head that opens a body does not end at its first `;`
The first draft assumed, as `directive-split` documents it does, that "the
construct's terminator is a `;`". `jtag_dtm_reg_block.sv:273` is the
counterexample — a split `function new(` **header**:
```verilog
function new(string name = "",
`ifdef USE_DMI_INTERFACE
int unsigned n_bits = 50,
`else
int unsigned n_bits = 41,
`endif
int has_coverage = UVM_NO_COVERAGE);
super.new(name, n_bits, has_coverage);
endfunction : new
```
That `;` closes a *header*. Stopping there captured the header, left the body
behind as items, and the file failed on `super` three lines later — a worse
diagnostic than the one it replaced. So `construct_end` reads the construct's
head and answers one of three things:
- `Semi` — the default, and what every identifier-headed construct gets
(instantiation, call statement, assignment) along with every declaration
keyword. Unchanged from `directive-split`'s assumption.
- `Keyword("endfunction")` / `Keyword("endtask")` — the two body-opening heads
the corpus needs. The block runs to the closing keyword and takes the
`: label` it may carry (`past_end_label`), because a label left outside would
be parsed as an item.
- `Unknown` — every other body-opening keyword (`BODY_KEYWORDS`: `module`,
`class`, `case`, `begin`, `for`, `always`, …). **Refused outright**, because
capturing at a `;` would produce exactly the truncated head above and nothing
in the corpus asks for these.
`TF_QUALIFIERS` (`virtual`, `static`, `automatic`, `local`, `protected`) are
skipped in front of `function`/`task`. `extern` and `pure` are deliberately
**not** in that list: those spell a prototype, which really does end at its `;`,
so they fall through to `Semi`, which is correct for them.
### `take_list_directives` must not harvest an outer region's seam
The two `tb.sv` files (bucket 13) fail for a related but distinct reason, and
they need no new recovery at all — `directive-split`'s existing one already
fits, it just never got to see the failure:
```verilog
`ifdef DISABLE_ROM_INTEGRITY_CHECK
chip_earlgrey_asic #( .SecRomCtrlDisableScrambling(1'b1) ) dut (
`else
chip_earlgrey_asic dut (
`endif
.POR_N(...), ...
);
```
The parser accepts the first arm's head, opens the shared connection list, and
inside it meets the `` `else ``. `take_list_directives` harvested *any*
directive found inside a list's brackets as conditioning list elements, so it
took the `` `else ``, then read `chip_earlgrey_asic` (the second arm's module
name) as a positional connection — which succeeds, as a bare identifier — and
failed two tokens later at `dut`, three lines from the actual seam.
`at_outer_arm_split` stops that: a `` `else ``/`` `elsif ``/`` `endif `` that
**this list did not open** (counted over the list's own harvested directives),
while a region opened at **item** scope is still live (`open_conds > 0`, the
same "a region is live" guard `at_split_conditional` makes), is not conditioning
elements — it is the seam. The harvest breaks, the item fails standing on the
directive, and `at_split_conditional`'s four conditions all hold: the whole
instantiation becomes one verbatim block.
Both halves of the guard matter. Without `open_conds > 0` an ordinary
list-internal region would be refused; without the "did not open it" count the
`` `endif `` of a legitimately list-internal region would be. Pinned from both
sides by `an_ifdef_that_splits_an_instantiation_head_is_still_the_closing_shape`
and `a_list_internal_region_is_still_harvested_as_list_elements`, and by the
`.cases` control entry.
### The statement level runs first, and only the opening shape
The recovery is wired into **both** `parse_item_inner` and `parse_stmt_inner`.
The statement one is what keeps `jtag_dtm_reg_block.sv:173`'s capture at the
`abits.configure(...)` statement instead of at the enclosing `class`: an error
raised inside a function body propagates outward, and the innermost frame that
recognizes the shape must claim it first. (Condition 2 above would refuse the
enclosing item anyway — the belt to this braces — but the useful capture is the
narrow one.)
Statements get **only** the opening shape. The closing shape is item-scope by
construction: `Parser::open_conds` counts the `` `ifdef ``s consumed *as items*,
per `directive-split`'s rule, so `mark.conds` inside a body would be answering a
question about a different scope. No corpus file asks for it.
### What is deliberately still refused
- Any non-conditional directive mid-expression.
- A stray `` `else ``/`` `endif `` with nothing open.
- An unterminated region, or a construct with no terminator before EOF.
- Brackets that do not balance across the chosen arm.
- A plain syntax error that merely sits near a directive.
- Any body-opening head other than `function`/`task`.
All seven pinned by `the_opening_split_refuses_everything_it_does_not_model`
and re-run against the release binary on standalone files.
### One deliberate widening, and it supersedes a test
`parser.rs`'s `a_directive_inside_a_connection_is_still_a_parse_error` pinned
that a conditional region written *inside* a connection's parens is refused —
"out of scope by design". That premise is exactly what this round changes:
`chip_earlgrey_asic.sv:621` writes one inside a parameter value's
concatenation, which is the same shape. The test is renamed
`a_directive_inside_a_connection_is_captured_or_refused_by_kind` and now pins
both halves — the conditional region is captured verbatim, any other directive
there is still an ordinary parse error. This is the only pre-existing test whose
expectation changed, and the only shape whose accept/refuse verdict moved
outside the seven target files (measured: see the Work log's sweep diff).
### A currently-passing file cannot be affected
Both recoveries are reached only from an `Err` arm, and a file that formats
today produces no such `Err`. The one exception is `at_outer_arm_split`, which
runs on the **success** path — so it was measured rather than argued: the
820-file corpus gate produces byte-identical per-file results before and after,
and the 3,943-file OpenTitan sweep's pass set is a strict superset with no file
moving out.
## Handshakes
### Consumed
- `Parser::verbatim_since(start, col)` — slices `source[span]` into a `RawText`
and drops the comment copies falling inside the span. Used unchanged.
- `Fmt::raw_text(raw)` / `Fmt::raw_lines(text, col)` — the verbatim printer.
Used unchanged; no formatter source file was touched by this round.
- `Parser::skip_conditional_arms` — `directive-split`'s arm skipper, reused by
the opening-shape scan with the same meaning.
- `Parser::open_conds` — read (never written) by `at_outer_arm_split`, which is
its third reader. `directive-split`'s rule that only `note_item_conditional`
and `split_conditional_item` may *write* it is preserved: this round adds no
writer, because an opening-split block is conditional-balanced.
- `ItemKind::Verbatim(RawText)` gained a **sixth** producer and
`StmtKind::Verbatim(RawText)` a **second** (after the concurrent assertions).
No signature changed, so no exhaustive match anywhere needed a new arm —
`format.rs`, `bind.rs`, `visit.rs`, `spans.rs` and the linter are untouched.
**No new AST variant, no new AST field.**
### Promised / changed for others
- **`crates/vlog_formatter/src/verify.rs` is untouched.** No normalization was
added and no forgiveness widened. Verbatim bytes need none: a captured block
is re-lexed as ordinary tokens on both sides, so every token inside it must
still match, and all seven newly-passing OpenTitan files go through the
runtime safety net (`lucisv --check`, which verifies) plus a two-pass
idempotency check.
- **Request to whoever next owns `crates/vlog_formatter/tests/verification.rs`:**
`directive-split` shipped ten invariant-#4 attack tests there even though it
too left `verify.rs` alone, on the grounds that a verbatim capture is
forgiveness-*adjacent*. The equivalent tests for this round were **not**
added, because `verification.rs` is Lane B's file this wave and a silent edit
would break the merge contract. The seven refusal shapes are pinned in
`parser.rs` instead (`the_opening_split_refuses_everything_it_does_not_model`)
and were re-run against the release binary. Adding the (input, corrupted
output) pairs to `verification.rs` after the merge is a QA-sized task and is
recommended.
- **New private parser surface only.** Two consts (`BODY_KEYWORDS`,
`TF_QUALIFIERS`), one enum plus its reader (`ConstructEnd`,
`construct_end`), two free functions (`directive_word_of` — extracted from
the existing `directive_word` so a harvested `RawText` can be classified —
and `take_since`), and seven `Parser` methods (`take_gap`,
`at_outer_arm_split`, `at_opening_split`, `scan_opening_split_extent`,
`past_end_label`, `capture_split`, `split_conditional_stmt`). Nothing is
`pub`. `split_conditional_item`'s body was split so `capture_split` is shared
by both shapes; its behaviour on the closing shape is unchanged.
- **Delivered: `formatter-bug-fixes` round 2's `take_before_open` request.**
See that README's Handshakes section, marked DELIVERED, and the work log
below. `Parser::take_before_open` and the empty-call `CallComments::dangling`
harvest now take only the comments written in the gap that ends at the
bracket (`Parser::take_gap`), instead of draining the whole pending queue.
### Requests to other clusters
- **`directives-in-lists`**: a function/task port list
(`Parser::parse_tf_ports`) still has no directive harvest, because `TfArg`
lists carry no `Vec<ListDirective>` and adding one is an AST change with
printer arms. `jtag_dtm_reg_block.sv:273` is therefore *captured verbatim*
rather than formatted. Teaching that list the existing harvest would be
strictly better output for the same file, and belongs to whoever owns the
`directives-in-lists` surface plus `format.rs`.
- **`StmtKind::Return` has no comment slot**, so `return // c` ⏎ `g();` still
refuses (see the formatter-bug-fixes note). Not a directive matter; recorded
because this round's parser change is what isolates it.
## Status / TODO
- [x] Baseline recorded: OpenTitan sweep 107 failures at `17633d2`, corpus gate
813/820, both re-run from a pristine scratchpad build of `HEAD`.
- [x] Parser: `at_opening_split` (the trigger), `scan_opening_split_extent`
(the extent), `past_end_label`, `construct_end` + `BODY_KEYWORDS` +
`TF_QUALIFIERS`.
- [x] Parser: `capture_split` extracted so both shapes share the rewind/walk.
- [x] Parser: `at_outer_arm_split`, the `take_list_directives` guard, and the
`directive_word_of` refactor it needs.
- [x] Parser: statement-level recovery in `parse_stmt_inner`
(`split_conditional_stmt`), opening shape only.
- [x] Handshake (item 2): `take_before_open` + empty-call `dangling` narrowed
to `take_gap`.
- [x] 10 new parser tests, including the 7-shape refusal test and the two
comment-ownership tests; one superseded test rewritten to pin both halves
(`vlog_parser` lib suite 224 → 234).
- [x] 7 cases in `crates/vlog_formatter/tests/cases/directive_in_statements.cases`
(the harness asserts idempotency on every one).
- [x] All 7 target OpenTitan files parse and format strict-clean; two-pass
idempotency and unchanged on-disk md5 confirmed for each.
- [x] Sweep 107 → 100, pass set a strict superset, no message changed on any
still-failing file.
- [x] Corpus gate byte-identical to baseline (813/820).
- [x] `cargo fmt --all`, `cargo clippy --all-targets`, `cargo test --workspace`
clean.
- [ ] **Not done, deliberately:** directive harvesting in function/task port
lists (needs an AST field — see Requests); body-opening heads other than
`function`/`task`; any canonical *layout* for the inside of a captured
region — it stays byte-for-byte; the invariant-#4 attack pairs in
`verification.rs` (Lane B's file — see Promised/changed).
## Work log
### 2026-08-29 — dev
**Setup.** Worktree branched at `34b766c`, fast-forwarded to `master`
(`17633d2`, Lane A merged) before any edit, so the round builds on the freed
`parser.rs`. All measurement against the real checkout at
`/Users/guoliangchen/repo/opentitan` (HEAD `0098135`), read-only — every probe
uses `--check`/`--stdout` with `--no-cache`, and each target file's md5 was
compared before and after.
**Baseline** (pristine `git archive HEAD` build in the scratchpad, so before and
after are the same corpus and the same commands): OpenTitan sweep **107**
failures over 3,943 files; corpus gate
`{"passing":813,"total":820,"pct":99.1,...}`.
**Item 1 — the design choice.** Verbatim capture, reached by two recoveries
that share one extent-capture step, rather than new grammar. Justified against
the three existing directive features' contracts in Assumptions above; the
short version is that the arms of a split region are rival spellings of one
construct, there is no tree that holds "either this or that", and the four
existing pass-through sites are all list-element boundaries that an expression
does not have. No AST variant and no AST field was added, so `format.rs`,
`bind.rs`, `spans.rs`, `visit.rs` and the linter are untouched — which is also
what kept this round inside its file-ownership list while Lane B held the
formatter.
Three things were learned by building it, each recorded above as an assumption:
1. The corpus writes the construct's terminator on **both** sides of the region
(`chip_if.sv` inside the arms, `chip_earlgrey_asic.sv` after them), so one
terminator rule is not enough — hence `terminated_in_arm`.
2. `directive-split`'s "the terminator is a `;`" assumption is **false for a
function header**. The first build of this round captured
`jtag_dtm_reg_block.sv`'s `function new(...)` header and orphaned its body,
moving the file's error from line 173 to line 280. `construct_end` is the
answer, and it refuses by default for every body-opening head it does not
model.
3. The two `tb.sv` files needed **no new recovery** — only that
`take_list_directives` stop hiding the seam from the recovery that already
existed. That is the smallest change in the round and the one that fixes the
two highest-value files.
**Item 1 — result.** All 7 target files clean:
| file | before | after |
|---|---|---|
| `hw/top_earlgrey/dv/env/chip_if.sv` | `1192:1: expected expression` | formats |
| `hw/top_darjeeling/dv/env/chip_if.sv` | `894:1: expected expression` | formats |
| `hw/top_earlgrey/rtl/autogen/chip_earlgrey_asic.sv` | `621:1: expected expression` | formats |
| `hw/top_earlgrey/rtl/autogen/chip_earlgrey_cw340.sv` | `502:1: expected expression` | formats |
| `hw/dv/sv/jtag_agent/jtag_dtm_reg_block.sv` | `173:1: expected expression` | formats |
| `hw/top_earlgrey/dv/tb/tb.sv` | `114:22: expected \`)\` (found "dut")` | formats |
| `hw/top_darjeeling/dv/tb/tb.sv` | `105:24: expected \`)\` (found "dut")` | formats |
Whole-sweep **107 → 100**. `comm -13` over the sorted failure lists is empty
(nothing regressed); `comm -23` is exactly those seven files; and no file that
still fails changed its message. Each of the seven was formatted twice through
`--stdout` and the passes compared byte-for-byte — **idempotent** — with the
checkout's md5 unchanged. Corpus gate re-run with both binaries against the
same pinned corpus: **813/820 both times, and `diff` over the two per-file
result tables is empty**, not merely the same total.
**Item 2 — the handshake.** Implemented as specified —
`take_before_open` keeps only comments with `span.start >= self.last_end()` —
and then found by bisection that it was not sufficient on its own: with
`before_open` fixed, the pinned shape's comment was swallowed one line later by
`CallComments::dangling`, the empty-`()` harvest, which drains the queue the
same way. Both now go through one narrow helper, `Parser::take_gap()`. The
"or better, justified" clause of the brief covers the second site; it is the
same defect at the same struct, and without it the handshake does not deliver.
Verified by composing this lane's `parser.rs` with Lane B's worktree in a
scratchpad copy — their files were read, never written — and running their whole
workspace suite: everything stays green **except**
`a_comment_before_a_call_in_a_condition_is_still_refused`, which flips from pass
to fail, i.e. the shape now formats:
```
if (
// why
!en() || b
) begin
```
and the real `hw/ip/keymgr/dv/env/keymgr_scoreboard.sv` — the 12th and last
bucket-2 file, which Lane B could not fix from inside `vlog_formatter` — formats
cleanly end to end. Lane B's `expect_divergence` attack pairs all still pass;
`verify.rs` is untouched by either lane. Marked DELIVERED in
`docs/features/formatter-bug-fixes/README.md`.
**Deviations from the brief, all flagged:**
1. **No formatter `.cases` entry proves the keymgr line-1254 shape in *this*
worktree**, because half the fix is Lane B's: `Fmt::header_parens` (their
round 2) is what gives a comment written after `if (` a home. At `17633d2`
that shape is refused with or without this round's parser change — confirmed
against the pristine baseline binary — so a case asserting it here would
fail. The parser side is pinned instead by two new parser tests
(`a_comment_after_an_opening_bracket_is_not_stolen_by_an_inner_call`, which
asserts both call comment slots are empty and the comment reaches the body's
leading comments where `header_parens` collects it, and
`a_comment_actually_written_before_a_bracket_is_still_taken` for the other
side), and end to end by the composed run above. **The `.cases` entry belongs
to the merged tree** and is the natural first QA task after the merge.
2. **Only one pinned refusal test exists**, not two. Lane B's README names one
(`a_comment_before_a_call_in_a_condition_is_still_refused`) and describes
`return // c` ⏎ `g();` as a second *symptom*, which is not pinned as a test.
That symptom is **not** fixed by this round and is refused identically before
and after: it needs a comment slot on `StmtKind::Return`. Recorded as a
request above.
3. **One pre-existing parser test's expectation changed**
(`a_directive_inside_a_connection_is_still_a_parse_error`), because the
behaviour it pinned is the behaviour this round adds. Rewritten to pin both
halves rather than deleted; rationale in Assumptions.
4. **`docs/features/formatter-bug-fixes/README.md` was edited** — the
Handshake-status edit the brief sanctions. This worktree holds the *trunk*
copy of that file, which does not yet contain Lane B's round-2 Handshakes
text, so the new `### Round 2's take_before_open request — DELIVERED`
subsection sits where Lane B also appends. **A merge conflict there is
expected and the resolution is to keep both blocks.**
**Gates.** `cargo fmt --all --check` clean, `cargo clippy --all-targets` clean
(no new warnings, no `#[allow]` added), `cargo test --workspace` green, corpus
gate exactly at baseline. No `git commit`, no `git push`.
## QA log
### 2026-08-29 — QA
**Verdict: SHIP.** No corruption, no capture-extent bug, no comment
relocation found across the adversarial charter. All claimed numbers
reproduced exactly. `vlog_parser` lib suite: 234 → 238 (4 new QA regression
tests added, all passing; see below).
**Gates**, all re-run from a fresh build in this worktree:
- `cargo fmt --all --check`: clean.
- `cargo clippy --all-targets`: clean, no new warnings.
- `cargo test --workspace --no-fail-fast`: green, every crate, 0 failures.
**Reproduction of the round's numbers**, against a pristine `17633d2` binary
built in a separate `git worktree` (never touching this lane's tree) for
every "before" comparison:
- OpenTitan sweep (`/Users/guoliangchen/repo/opentitan`, HEAD `0098135`,
read-only, `--no-cache --check`, both binaries against the identical
3,943-file list): baseline **107**, round **100**. `comm -13` (round-only
failures, i.e. regressions) is **empty**. `comm -23` (fixed) is **exactly**
the 7 named files. Joined the two failure tables on filename and diffed
the messages for every file failing in both: **zero** changed.
- The 7 target files: each formats (`--check` exit 0 or 1, never 2), each
two-pass idempotent (`--stdout` output fed back in produces byte-identical
output), and each file's on-disk md5 confirmed unchanged before/after.
- Corpus gate (`scripts/score.sh` against the real 820-file `corpus/`, not
reachable by name from inside a worktree — BSD `find` on this machine
does not descend into a directory given to it as a symlink without `-L`,
which `score.sh` doesn't pass, so the corpus has to be referenced by its
real path rather than a `corpus` symlink dropped in the worktree root):
baseline `{"passing":813,"total":820,...}`, round identical, and
`diff` over the two `-o details.tsv` per-file tables is **empty** —
not just the same count, the same outcome for every one of the 820 files.
- Composed-tree claim (Lane B's worktree,
`.claude/worktrees/agent-a8ee7330b649bc150` @ `d3deacf`, read-only —
rsynced to a scratch copy, Lane B's files untouched, only this lane's
`parser.rs` overlaid on top): `cargo test --workspace --no-fail-fast`
is green except exactly
`verification.rs::a_comment_before_a_call_in_a_condition_is_still_refused`,
which flips from pass to fail because the shape it pins now *formats* —
matching the dev's report precisely, one flip and no other change. Built
the composed release binary and confirmed
`hw/ip/keymgr/dv/env/keymgr_scoreboard.sv` formats end-to-end and is
two-pass idempotent.
**Adversarial testing** (the charter's three named sins: a capture that eats
too much, a refusal that became corruption, a comment that moved homes).
Built two probe harnesses — a temporary `vlog_parser` integration test
(deleted after use, not part of the final diff) dumping parsed-tree
summaries, and a set of standalone `.sv` files run through both the round
and baseline release binaries with `--stdout`/`--check`/idempotency:
- Nested `` `ifdef `` (with its own `` `elsif ``/`` `else ``) fully inside an
opening split's first arm, itself inside an outer already-open region:
captures the right byte range, `open_conds` lands back at exactly the
outer count, next item survives. No prior test combined all three levels
at once.
- A 4-arm `` `elsif `` chain in an opening split: captured through the final
`` `endif ``, not an intermediate arm.
- A block comment whose text contains the literal string `` `endif ``
inside the region: does not fool the extent scan (comments are never
`TokenKind::Directive`, so this was never actually at risk, but it is now
pinned).
- A string literal containing the literal text `` `endif `` as data, and a
string literal containing a bare `;`: neither confuses the bracket/`;`
scan, since both are lexed as single opaque tokens.
- `` `define ``/`` `include `` written inside the captured region: swept as
ordinary opaque directive tokens, included verbatim, no special handling
needed or present.
- The split construct as the last item of its `module`/`class` (no sibling
item follows): extent scan stops at its own terminator, never wanders
into `endmodule`/`endclass`.
- Two independent opening splits back-to-back in the same module: each
captured as its own `Verbatim` item; the first's capture does not bleed
into the second's region.
- Mismatched bracket nesting *across* arms (deliberately malformed,
adversarial input, not valid SV): the scanner follows only the first arm
as documented, produces a verbatim capture, formats and reparses clean —
no corruption, matching the documented "follow the first arm, skip the
rest whole" policy.
- Comment-ownership sweep for the `take_gap` handshake: comments in empty
call parens (both before and after), nested calls each with their own
comment, a comment between `!` and its callee, a bare macro call with a
comment inside its parens, a `$display` system-call comment, and a
three-comment instantiation connection list (before/between/trailing) —
diffed byte-for-byte between the baseline and round binaries. **All six
are identical**, including the still-refused `!en()`/`return` shapes
(refused by both, same diagnostic), confirming `take_gap` changed nothing
for any comment site outside the one it was built to fix.
One false alarm, recorded for the record: an ad hoc probe
(`` `ifdef ``/`` `else ``/`` `endif `` conditioning a bare positional call
argument with no comma, i.e. `f(` `` `ifdef A `` `1` `` `else `` `2`
`` `endif `` `);`) initially looked like a diagnostic-quality regression —
the round's error landed three lines away from the baseline's. Root cause
was the probe file itself, not the parser: it placed a bare `x = 1;`
directly as a *module item* (only legal inside a procedural block), an
unrelated pre-existing syntax error that the baseline never reached because
it failed earlier. Corrected to `initial begin ... end`, the shape formats
cleanly and idempotently on both sides — not a finding.
**Tests added** (`crates/vlog_parser/src/parser.rs`, `#[cfg(test)] mod
tests`, appended after the round's own directive-in-statements block; lib
suite 234 → 238, all green):
`a_nested_ifdef_with_its_own_elsif_survives_inside_an_opening_split_under_an_outer_region`,
`an_elsif_chain_in_an_opening_split_is_captured_through_the_final_endif`,
`a_block_comment_naming_endif_does_not_fool_the_extent_scan`,
`an_opening_split_that_is_the_last_item_does_not_eat_the_closing_keyword`.
None of these were failing before they were added correctly (the first one
initially failed on a test-construction mistake — a trailing `` `endif ``
that closed the "still open" outer region I meant to leave open, and a
wrong item index once the outer `` `ifdef `` became a sibling file item —
both fixed in the test, not the parser); they exist to guard the
adversarial coverage above against a future regression, since none of it
was pinned by the round's own 10 tests.
**Not independently re-verified**: the `verify.rs`/invariant-#4 attack-test
request the dev's Handshakes section files against `verification.rs`
(Lane B's file this wave) — correctly left undone here too, per the
merge-contract rule (`crates/vlog_formatter/tests/verification.rs` is
outside this lane's file-ownership list). Recommended as the first QA task
after the merge, as both this round's and Lane B's READMEs already say.
## Review
**2026-08-29 — lead.** Reviewed after QA's zero-finding SHIP; gates
re-run on the worktree. The round's craft shows in what it refused to
do: construct_end's Unknown → refuse arm turns "I don't understand
this head" into a clean error instead of a guess (the jtag
first-build bug caught by the dev's own testing is exactly why that
arm exists), and the tb.sv fix being three lines in
take_list_directives rather than a new recovery is the
smallest-change discipline paying out on the highest-value files.
Item 2's bisection — the specified fix necessary but not sufficient,
the second drain found and unified behind take_gap — is why
"implement exactly that, or better, justified" is written into every
such handoff. The composed-tree verification against Lane B's
worktree was the right way to prove a cross-lane delivery without a
cross-lane edit, and QA reproduced it independently. Deviations all
accepted; the two post-merge items (keymgr .cases entry, the
standing-template attack pairs in verification.rs) are the lead's and
are done in the merge commit's follow-up. Accepted; merged by the
lead. OpenTitan sweep: 151 at the wave's start, 100 after this round.
+439
View File
@@ -24,6 +24,21 @@ The five:
5. `always @( /* c */ * )` loses the comment: `parse_sens_list` discarded
comments written inside the parens of an implicit sensitivity list.
**Round 2 (2026-08-29, Lane B of the testbench-syntax wave).** The same
feature, extended to `syntax_coverage.md`'s bucket 2: the 12 real OpenTitan
files that parse with zero errors but whose *formatted output* the safety net
refused. Three more bugs, all in `format.rs`'s layout, none needing a
`verify.rs` change:
6. A line comment trailing the then-branch's `end` swallowed the `else` that
followed it (`end // addr_phase_write` + `else if (...) begin` came back as
one comment). 4 of the 12 files.
7. A comment written inside a statement header's parentheses (`if (// why` ⏎
`cond)`, `while (`, `repeat (`, `wait (`, `case (`) printed *after* the
`)`, moving it across a token. 7 of the 12 files.
8. `default;` — the case-item colon IEEE 1800 §12.5 makes optional — came
back as `default:`, inventing a token the source never wrote. 1 file.
## Assumptions
- The four `#SKIP` expected outputs are the spec. None of them was changed.
@@ -66,6 +81,46 @@ The five:
enclosing group in this printer. The hug only applies when the value already
contains a forced break, so no case without comments changed.
### Round 2 (2026-08-29)
- **`verify.rs` was not touched at all this round** (`git diff` on it is
empty), and no normalization was added or broadened. Every fix is a layout
change in `format.rs`; the safety net's judgement of all three shapes is
unchanged, and four crafted (input, corrupted output) pairs assert it still
rejects exactly the corruptions these bugs used to produce.
- **The parser's trivia attachment is taken as given.** Nothing between a
statement header's `(` and `)` owns trivia, so a comment written there is
queued and lands on the next node that takes meta — the body statement, or
a `case`'s first item. The formatter takes it back by *span* rather than
asking the parser to change: a leading comment of the body that starts
before the header's `)` was written inside the parentheses. This is Lane B's
file-set constraint made into a design point, and it is exact, because a
comment's byte span says unambiguously which side of the `)` it was on.
- **The `)` is found in the source, not in the AST**, by skipping whitespace
and comments forward from the end of the condition expression
(`skip_trivia`). Only trivia can stand there for `if`/`while`/`repeat`/
`wait`/`case`. If anything else turns up, the header prints its plain
parentheses and takes nothing, so an unrecognized shape behaves exactly as
it did before.
- **A cuddled `else` is a layout decision, not a token.** `end` keeps `else`
on its line unless the then-branch's own trailing comments end in a line
comment, which would swallow it. A block comment still cuddles
(`end /* why */ else`).
- `for`, `foreach` and `do ... while` are **not** covered: the first two do
not end their header in a single condition expression, and a `do`-`while`
has no body after its parentheses to take the comment back from. All three
still refuse cleanly and are pinned as refusals by a test.
- A comment written *before* a header's `(` (`if /* c */ (a)`) is also not
covered — the formatter has no offset for the `(`, so such a comment is
treated as if it were inside and the file is still refused, exactly as it
was before. No corpus use.
- **`default;` is read from the source too.** `CaseItem` records no `colon`
flag (the parser does `let _ = self.eat_sym(":")`), so `default_has_colon`
looks at the byte after the keyword. With a null body the `;` hugs the
keyword — `default;`, not `default ;` — while `default: ;` keeps both the
colon and the space it already had. Generate-case `default` reads the same
way.
## Handshakes
- **`vlog_parser::token::Comment` gained a position** (the handshake request
@@ -102,6 +157,80 @@ The five:
and the top-level `README.md` (another agent's scope) are untouched;
`cargo fmt` was run and left those files byte-identical.
### Round 2 (2026-08-29)
- **Nothing was changed outside `crates/vlog_formatter`.** Round 2 consumes
the AST exactly as it stands: `Comment.span`, `Expr.span`, `CaseItem.span`
and `Meta.leading`'s source order are the only new load-bearing surfaces,
and all four already existed. `git diff` on `crates/vlog_parser` and
`crates/vlog_semantic` is empty.
- **Open handshake request to whoever owns `vlog_parser/src/parser.rs`
(Lane A's file this wave).** `Parser::take_before_open` (`parser.rs:757`)
calls `take_dangling()`, which drains the *whole* pending-comment queue —
`pending_trailing`, `pending_leading` and the bracket token's own leading
comments — rather than only the comments actually written in front of the
bracket. So a comment written just after a statement header's `(` is
swallowed by the first call inside the condition and printed between that
call's callee and its own `(`:
```systemverilog
if (// If keymgr is not enabled in the current LC
!cfg.keymgr_vif.get_keymgr_en() || ...
```
comes back as `!cfg.keymgr_vif.get_keymgr_en // If keymgr ...` ⏎ `() ||`.
`header_parens` cannot take it back — it never reaches the body's leading
comments — and the formatter cannot hoist it out past the `!` without a
cutoff threaded through every `expr` call, which is far more machinery than
the parser fix. **Requested fix**: in `take_before_open`, keep only the
comments whose `span.start >= self.last_end()`, i.e. those written in the
gap that ends at the bracket, and leave the rest queued. `last_end()`
already exists (`parser.rs:611`). This is the last of the 12 bucket-2 files
(`hw/ip/keymgr/dv/env/keymgr_scoreboard.sv`); the shape is pinned as a
clean refusal by
`verification.rs::a_comment_before_a_call_in_a_condition_is_still_refused`,
which is the test that should flip to a `.cases` entry when the parser fix
lands.
- **Format-cache discipline** (`topo.md` §2.3): this round changes formatter
*output* for the shapes above, so the workspace version must be bumped at
release or a stale `.lucisv_cache` will skip files that would now format
differently. Flagged for the lead; no version was bumped here.
### Round 2's `take_before_open` request — **DELIVERED** (2026-08-29)
Filed by round 2 against whoever owns `crates/vlog_parser/src/parser.rs`;
answered by the `directive-in-statements` round (see
`docs/features/directive-in-statements/README.md`). The requested change and
one more site it needed:
- `Parser::take_before_open` no longer calls `take_dangling()`. It takes only
the comments whose `span.start >= self.last_end()` — the gap that ends at
the bracket — through a new narrow sibling, `Parser::take_gap()`. Exactly
the fix round 2 specified.
- **That alone was not enough.** `CallComments::dangling` (the inside of an
*empty* `()`, `parser.rs`'s postfix-call arm) drained the whole queue too,
so with `before_open` fixed the comment was swallowed one line later —
which is why the pinned shape's condition starts `!en()` and not `!en(x)`.
It now uses `take_gap()` as well. Both sites are `CallComments`; nothing
else changed.
Verified by composing this lane's parser with round 2's worktree in a
scratchpad copy (round 2's files read-only, never edited): the whole workspace
suite stays green except
`verification.rs::a_comment_before_a_call_in_a_condition_is_still_refused`,
which flips from pass to fail — i.e. the shape now formats — and the real
`hw/ip/keymgr/dv/env/keymgr_scoreboard.sv` formats cleanly, closing the 12th
and last bucket-2 file. That test should become a `.cases` entry at merge, as
round 2 predicted. Round 2's `expect_divergence` attack pairs all still pass:
`verify.rs` is untouched by either lane.
Still open, and **not** this handshake: `return // c` ⏎ `g();`, round 2's
"second, independent symptom". The parser no longer misplaces that comment
into the call, but nothing owns a comment written between `return` and its
expression, so it drifts and the safety net still refuses the file — refused
before this round and refused after, byte-identical either way. It needs a
comment slot on `StmtKind::Return`, which is an AST change with printer arms.
## Status / TODO
- [x] Bug 3 — closing block labels preserved (`end`, all `join` kinds,
@@ -131,6 +260,34 @@ The five:
The "re-enable the four `#SKIP` cases" item lives in the case-tables
README's TODO and is now satisfied.
### Round 2 (2026-08-29)
- [x] Bug 6 — a line comment trailing `end` no longer swallows the `else`
that follows it; a block comment still cuddles.
- [x] Bug 7 — a comment written inside an `if`/`while`/`repeat`/`wait`/`case`
header's parentheses is printed inside them, on the correct side of the
condition.
- [x] Bug 8 — `default;` keeps IEEE 1800 §12.5's optional colon off, and
`default: ;` keeps it on.
- [x] 11 of the 12 bucket-2 OpenTitan files format cleanly and are
idempotent; the whole checkout is unchanged on disk. Before/after in
the work log.
- [x] 11 new `.cases` entries (10 in `comments.cases`, 1 in
`statements.cases`) — each one asserts the output *and* that
re-formatting it is a fixed point, which is what the harness does.
- [x] 4 masked-corruption rejection pairs + an explicit
comments-never-dropped assertion in `verification.rs`, plus 4 pinned
refusals for the shapes deliberately left uncovered.
- [x] `cargo fmt --check` clean, `cargo clippy --all-targets` silent,
`cargo test --workspace` green, pinned corpus 813/820 (baseline 813,
zero verification errors).
- [ ] Not fixed, needs a change in `vlog_parser` (see Handshakes): a comment
after `if (` when the condition starts with a call —
`keymgr_scoreboard.sv`, the 12th file.
- [ ] Not fixed, no corpus evidence, pinned as refusals: a comment inside a
`for`/`foreach` header or a `do ... while (...)`; a comment written
between a header keyword and its `(`.
## Work log
### 2026-08-18 — dev agent
@@ -239,6 +396,109 @@ an indented banner comment) formats cleanly, and `lucisv` on its own output is
byte-identical. Every bug's original repro from the two feature READMEs was
re-run through the built CLI and now exits 0.
### 2026-08-29 — dev agent (Lane B, testbench-syntax wave)
**Scope.** `syntax_coverage.md`'s bucket 2: the 12 OpenTitan files that parse
with zero errors but whose formatted output the safety net refused. Measured
first, against the real checkout at `/Users/guoliangchen/repo/opentitan`
(`--no-cache --check` over all 3,943 `.sv`/`.svh`): **151 failures, 12 of them
`verification failed:`** — reproducing the sweep exactly. The 12 are three
shapes, not one:
| # | shape | files |
|---|---|---|
| 6 | `end // c` ⏎ `else …` — the trailing line comment swallows the `else` | 4 |
| 7 | a comment inside a statement header's `(...)` prints after the `)` | 7 |
| 8 | `default;` comes back as `default:` | 1 |
**Bug 6 — `end // c` then `else`.** `if_stmt` cuddled `else` onto the `end`
line whenever the then-branch was a block. `stmt_as_body` has already printed
the block's trailing comments by then, so ` else if (b) begin` landed *inside*
a line comment's text and `verify.rs` saw one comment reading
`// addr_phase_write else if (addr_phase_read) begin`. The whole fix is one
extra condition on `then_is_block`: a free `trailing_ends_line(&then.meta)`
that asks whether the last thing `trailing` prints is a `//` comment. A block
comment still cuddles, which is what the source wanted anyway.
**Bug 7 — comments inside a header's parentheses.** The header's `(` and `)`
are printed by `parens()` and belong to no node, so the parser has nowhere to
put a comment written between them: it stays in the pending queue and lands on
the next node that calls `take_meta` — the body statement (`if`, `while`,
`repeat`, `wait`) or the first case item (`case`). Printed there, the comment
sits after a `)` it was written before.
Fixed entirely on the formatter side, by span. `header_parens(cond, body_meta)`
finds the closing `)` with `skip_trivia` (forward from `cond.span.end`; only
whitespace and comments can stand there), takes every leading comment of the
body that starts before it, splits them at `cond.span.start` into before/after
buckets, and hands them to `paren_comments` — which is the existing
`ExprKind::Paren { before, after }` layout, factored out and now shared by both
callers rather than duplicated. It returns how many comments it consumed;
`stmt_as_body_from` / `leading_from` / `case_body` skip exactly that many.
`leading`, `stmt_as_body` and `case_body`'s old signature are all preserved as
`skip = 0` wrappers, so the twelve other `stmt_as_body` call sites are
untouched. When the source is not the expected shape (no `)` where one was
expected, or nothing to take) the function returns the plain `parens(cond)` and
takes nothing, so every input that formatted before formats identically.
`for`, `foreach` and `do ... while` were deliberately left out: the first two
do not end their header in one condition expression and the third has no body
after its parens. Confirmed they still refuse cleanly and pinned that with a
test, so a later round sees them change rather than appear.
**Bug 8 — `default;`.** `parse_case_body` does `let _ = self.eat_sym(":")`, so
the AST does not record whether the source wrote the colon, and `case_labels`
printed `default:` unconditionally — inventing a token. Since `CaseItem.span`
starts at the `default` keyword, `default_has_colon` reads the byte after it
(through the same `skip_trivia`) and prints what was written. With a null body
the `;` hugs the keyword, because `stmt_as_body` would otherwise lay the `;`
out as a body and produce `default ;`. `default: ;` is unchanged.
**`verify.rs` is untouched** — `git diff` on it is empty. Per `topo.md` §2.1's
standing template I added the rejection tests anyway: four crafted (input,
corrupted output) pairs asserting the net still refuses the comment merged into
`else if`, the comment moved across the `)`, `default;` → `default: ;` and its
mirror `default: ;` → `default;`.
**Before / after on the real OpenTitan checkout** (3,943 files, `--no-cache
--check`, nothing ever written — `git status` in the corpus shows only the
pre-existing `hw/ip/aes/dv/tb/tb.sv` modification `syntax_coverage.md` already
records):
| | before | after |
|---|---|---|
| total failures (exit 2) | 151 | 140 |
| `verification failed:` | 12 | **1** |
| `parse error:` / `lex error:` | 139 | 139 |
| crashes | 0 | 0 |
All 11 fixed files were additionally formatted twice through `--stdout` and the
two passes compared byte-for-byte: **idempotent**, and every checkout file's
`md5` is unchanged. Pinned 820-file corpus: **813 passing** (baseline 813),
zero verification errors, zero crashes — no regression.
**The 12th file, and why it is not mine to fix.**
`hw/ip/keymgr/dv/env/keymgr_scoreboard.sv` had *two* bucket-2 bugs; fixing the
first (the `end // addr_phase_write` / `else if` merge at line 643) uncovered a
second at line 1254 that is not a formatter layout bug at all. The comment
there is written after `if (` and the condition starts with a call, so
`Parser::take_before_open` — which drains the whole pending queue — hands it to
`CallComments::before_open`, and the formatter faithfully prints it between the
callee and its `(`. `header_parens` never sees it. Hoisting it back out of the
expression past the `!` would need a suppression cutoff threaded through every
`expr` call; the parser fix is one span check. Filed as an open handshake
(above) with the exact patch, out of Lane B's file set, and pinned as a clean
refusal by a test. Also confirmed the same parser bug bites
`return // c` ⏎ `g();`, which is a second, independent symptom.
**Deviation from the brief**: 11 of 12 files, not 12, for the reason above.
Nothing was worked around and no corruption ships — the 12th file is still
refused and left byte-identical, which is the correct behavior until the parser
lands its fix.
**Format-cache note for the lead**: formatter output changed, so the workspace
version must be bumped at release (`topo.md` §2.3). Not bumped here.
## QA log
### 2026-08-19 — QA agent
@@ -485,8 +745,187 @@ compliance (no unwrap/expect/panic in library paths, no new deps, no
un-explained `#[allow]`, TODO.md/README.md/`lucisv` untouched) all confirmed
by direct inspection, not just by trusting the work log's claims.
### 2026-08-29 — QA agent (Lane B, testbench-syntax wave)
**Scope**: round 2 only — the three bucket-2 fixes (bug 6 `end // c` + `else`,
bug 7 `header_parens`, bug 8 `default;`) — with the adversarial charter aimed
squarely at a dropped/merged comment, an invented/moved token, or a fix that
only works on the corpus shapes. Built a `--no-cache --stdout`/`--check`
attack harness (pass1 → pass2 byte comparison for idempotency) and ran ~30
hand-crafted `.sv` files beyond the committed cases, then reproduced every
number in the work log independently against the real checkouts.
**Tool chain** (workspace root, after adding the two regression tests below):
`cargo fmt --check` clean; `cargo clippy --all-targets` silent, no new
`#[allow]`; `cargo test --workspace` green — `vlog_formatter`'s
`verification.rs` at 119/119 (118 + 1 new), `cases.rs` 1/1 (672 total cases
across all `.cases` files, `grep -c '#SKIP'` zero everywhere). Confirmed
`git diff --stat` on `crates/vlog_parser`, `crates/vlog_semantic`,
`crates/vlog_formatter/src/verify.rs` is empty — the "verify.rs untouched"
claim holds.
**Shape-A attacks (`end // c` / `else`)** — 5 crafted files: nested three-deep
if-else-if chain with every `end` individually commented (correct, stable);
the comment text containing the literal word "else" (correct, not
mistaken for structure); a CRLF-terminated file with the same shape
(correct); a pure block comment before `else` (still cuddles, as designed).
**One real gap found** (below) with a mixed block+line trailing comment.
**Shape-B attacks (`header_parens`)** — 9 crafted files hitting the source
scan directly: a `)` inside a string literal in the condition
(`s == ")"`), a `)` inside a nested paren sub-expression, a `)` spelled
inside a block comment (`/* looks like ) but is not */`), comments on both
sides of the `cond.span.start` split simultaneously, a condition that is
itself a `Paren` (double parens), `case`/`while`/`repeat`/`wait` each with
both-sided comments, and a case with two commented items after the header to
attack the skip-count plumbing. **All format correctly, keep every comment
in its original stream position, and are idempotent — no corruption, no
double-print, no drop.** Also re-confirmed the two documented refusal
boundaries directly (not just via `cargo test`): a comment before the
statement keyword's `(` (`if /* c */ (a)`) refuses cleanly (`token stream
diverges ... input has comment ... output has symbol "("`), and a comment
before a call in the condition refuses cleanly, matching the Handshakes
description exactly.
**Shape-C attacks (`default`)** — 9 crafted files: `default ;` (extra space)
normalizes to `default;`; `default: ;` unchanged; `default begin end` /
`default: begin end` both correct with the colon exactly as written;
`default y = 9;` (no colon, non-null body — a shape not explicitly named in
the work log but legal per the same IEEE grammar) correctly keeps the colon
off; two `default`s in one `case` (illegal but tolerated) round-trips both
correctly; `default /* c */: y = 9;` (comment between keyword and colon)
refuses cleanly rather than dropping or moving the comment. **One
non-blocking style nit found** (below): a trailing comment on `default;`
breaks the hug. `default;` inside a `generate case` without `begin`/`end`
hits a **pre-existing parser error** ("expected item"), confirmed unrelated
— `default begin : gd end` in the same position parses and formats fine, so
this is generate-case's existing null-body restriction, not a regression
from this round.
**Refusal-pin sabotage check**: confirmed by inspection that `StmtKind::For`
and `StmtKind::DoWhile` were not touched by the diff at all (no
`header_parens` call added), so their pinned refusal test is exercising the
same pre-existing, unmodified comment-position divergence check from round
1 — not a vacuous pass against dead code.
**Masked-corruption template**: all four crafted pairs genuinely attack the
paths this round changed (else-swallow, comment-across-`)`, colon invented,
colon dropped) rather than generic corruptions; re-ran them independently
via `cargo test -p vlog_formatter the_bucket_two_corruptions_are_still_rejected`.
**Numbers reproduced independently**, all against the live checkouts, all
read-only (`--check`/`--stdout` only):
- OpenTitan (`/Users/guoliangchen/repo/opentitan` @ `0098135264`, the same
pre-existing `hw/ip/aes/dv/tb/tb.sv` local edit `syntax_coverage.md`
records, nothing else dirty): `lucisv --no-cache --check .` →
**exactly 1** `verification failed:` (`hw/ip/keymgr/dv/env/
keymgr_scoreboard.sv:1254`, byte-identical message to the Handshakes
quote). Total failure count differs slightly from the work log's 140
(146 here) — attributable to `.gitignore`/vendor-tree walk differences
between sweeps, not to this round; the load-bearing number (verification
failures) matches exactly.
- Grepped the whole checkout for the three trigger shapes independently of
the work log's file list (`end\s*//.*\n\s*else`, `(if|while|repeat|wait|
case)\s*\(\s*//`, `^\s*default\s*;`) and got **exactly 12** candidate
files. Ran each through format+idempotency: **10 format cleanly and are
pass1==pass2 idempotent**, `keymgr_scoreboard.sv` is the documented
refusal, and one grep hit (`spi_device_scoreboard.sv`) fails on an
unrelated pre-existing macro-expansion parse error
(`` `CREATE_TPM_CASE_STMT ``) before the formatter ever reaches the
bucket-2 shape — confirms "11 of 12" exactly, with the 12th grep hit
being a false positive from the search pattern, not a second bug.
- Corpus gate: fetched `tools/corpus_fetch.sh`'s four pinned repos (820
files: 131 + 613 + 35 + 41, matches exactly) and ran `scripts/score.sh`:
`{"passing":813,"total":820,...}` — the exact baseline, zero
`verification failed:` entries in `.score-results.tsv` (the 7 failures
are all pre-existing parse/lex errors, none in the `other` bucket is a
verification error).
**Findings**
*Should-fix*: none. No hard-invariant violation found in either crafted
attacks or the real checkouts.
*Nit / informational* (both non-blocking — the safety net holds in both
cases; regression tests added for both):
1. **`trailing_ends_line` (`format.rs`, the `Some(tr)` arm) checks whether
the *merged* trailing text starts with `//`, not whether it ends in a
line comment.** `Meta.trailing` merges several trailing comments into one
string (see `ast.rs:92-96`); a line comment must physically be last in
any such merge (nothing can follow `//` on the same source line), so the
correct test is "does the merge end in one", not "does it start with
one". For `end /* a */ // b` the merged text is `"/* a */ // b"`, which
does not start with `//`, so `trailing_ends_line` returns `false` and
`then_is_block` stays `true` — the `else` still tries to cuddle, exactly
reproducing the bug this round fixes, on the one merge shape the fix's
condition doesn't cover. **Not a corruption**: `verify.rs` catches it on
reparse (the output's one merged comment doesn't match the input's two)
and the file is refused, byte-identical, same as it was before this
round (this exact shape always cuddled unconditionally pre-fix too, so
it is not a regression — it is the fix's coverage boundary, undocumented
until now). Pinned as a refusal, not fixed — narrowing `is_line_comment`
into a "starts vs. ends" split is a real design decision (the merge
already lost the individual comments' boundaries) that belongs to
whoever next touches this heuristic, not a QA-scope patch. Regression
test: `crates/vlog_formatter/tests/verification.rs::
a_block_comment_merged_with_a_trailing_line_comment_before_else_is_still_refused`.
2. **A trailing comment on a colon-less `default;` breaks the hug and
inserts a space**: `default; // fallback` formats to `default ; //
fallback`. Root cause: `case_item`'s shortcut requires `is_bare(&item.
stmt.meta)`, and a comment trailing the null statement lands in `item.
stmt.meta.trailing`, which is not bare, so the shortcut is skipped and
the general `case_labels` + `stmt_as_body` path inserts its usual
`Doc::Line` between the label and the body. **Not a correctness issue**:
the comment is kept verbatim in its original stream position, `verify.rs`
accepts it (whitespace is not part of the token stream), and it is
idempotent. It does contradict the round's stated design point
("`default;`, not `default ;`") for this one sub-case. Pinned with an
exact-output case rather than fixed, since teaching the shortcut to also
fire with a bare-except-trailing-comment statement (and then print that
comment itself) is a small but real behavior change outside a
verify-and-report QA pass. Regression case:
`crates/vlog_formatter/tests/cases/statements.cases`, "a trailing
comment on a colon-less `default;` keeps the comment and the missing
colon".
**Regression tests added this pass** (2 files, both green):
- `crates/vlog_formatter/tests/verification.rs`:
`a_block_comment_merged_with_a_trailing_line_comment_before_else_is_still_refused`
(finding 1 above, pins the safe refusal).
- `crates/vlog_formatter/tests/cases/statements.cases`: one new case (finding
2 above, pins the current — correct but slightly odd — output).
**Overall verdict**: **SHIP.** Both bucket-2 fixes claimed (11/12 files,
verification failures 12→1) are reproduced exactly against the live
OpenTitan checkout and the pinned 813/820 corpus, `verify.rs` is
byte-for-byte untouched, and every crafted adversarial input across all
three shapes either formats correctly with every comment preserved in place
and idempotently, or is safely refused with the file left untouched — never
corrupted. The two findings are both informational nits with permanent
regression tests now guarding them; neither is a hard-invariant violation
and neither blocks merge.
## Review
**2026-08-29 — lead, round 2 (bucket-2 round-trip bugs).** Reviewed
after QA's SHIP; gates re-run on the worktree (fmt clean, formatter
suite green). Three shapes, three root causes, all fixed where the bug
lived — format.rs — with verify.rs, the parser and the semantics
provably untouched, and the standing template honored: rejection tests
added anyway, four of them attacking the fixed paths specifically.
The dev's best decision was the one it did NOT make: the twelfth file
is a parser bug (take_before_open draining the pending-comment queue),
and it was filed as a specified Handshake instead of a cross-lane
edit — the directive round is delivering it. QA's two informational
pins are accepted as filed: the block-plus-line trailing-comment
boundary stays a clean refusal (the safety net's job, done), and the
`default ; // comment` stray space is a style wrinkle, not a token
change. 11 of 12 files independently confirmed on the real checkout,
corpus exactly at baseline. Formatter output changed, so the release
bumps the workspace version per the format-cache rule — flagged and
carried. Accepted; merged by the lead.
**2026-08-19 — lead. Verdict: accepted and committed as-is; no lead fixes
needed.**
@@ -0,0 +1,437 @@
# out-of-class constraints
## Goal
Parse the **out-of-block constraint definition** — `constraint C::name { ... }`
written at file or package scope, the body of a class's `extern constraint`
prototype (IEEE 1800 §18.5.2) — in both strict and tolerant modes. It is the
constraint sibling of `function C::method(...)`, which lucisv has parsed since
the `classes` round. `syntax_coverage.md`'s bucket 1 measured it as the single
largest gap in the OpenTitan sweep: **45 files** blocked outright, and — the
real damage — a tolerant-mode recovery cascade that turned one construct into
up to **322** spurious diagnostics in a single buffer, because the parse error
lands one token into a construct whose body the recovery loop then resynchronizes
inside. A widely-`` `include``d DV base class in that state is not "slightly
degraded" in an editor; it is unusable for diagnostics.
## Assumptions
- **The scope prefix carries no meaning lucisv needs.** The whole item is an
`ItemKind::Verbatim` leaf, so nothing downstream asks which class a
constraint belongs to. The chain is consumed and discarded, exactly as the
body's `dist`/`solve`/`->` grammar is copied rather than modelled. If a
future round wants "go to the `extern constraint` prototype from its
definition," it will need a real node — see Handshakes.
- **Any `::` chain length is accepted** (`pkg::cls::name`), because
`parse_method_name` — the out-of-body method path being reused — accepts
one, and rejecting longer chains would be extra code buying nothing. The
corpus only exhibits the two-part form (88 of 88 occurrences across the 45
files; measured, not assumed).
- **No new legal-position check.** `constraint C::name { ... }` is now accepted
wherever a plain `constraint name { ... }` was, including inside a class
body, where the LRM does not permit it. lucisv is a formatter, not an
elaborator; the existing `parse_constraint` already accepts a bare
`constraint c;` prototype at file scope for the same reason. Being more
permissive than the LRM in a position no real code writes costs nothing and
keeps the change to one call.
- The `.cases` and fixture harnesses auto-discover their files, so a new
`.cases` file is additive (relied on when placing the formatter coverage —
see Handshakes).
## Handshakes
**Consumed, unchanged:**
- `classes` — `verbatim_since` / `skip_balanced` / `RawText`, and
`ItemKind::Verbatim` as the leaf. No change to any of them. This round is
the sixth producer of `ItemKind::Verbatim` and adds no variant, so the
`topo.md` §2.2 new-AST-variant checklist (formatter arm, `bind.rs` arm,
`spans.rs` arm, `visit.rs` arm) **does not apply**: every consumer already
has its `ItemKind::Verbatim` arm and none of them changed.
- `classes` — `parse_method_name`, the out-of-body `C::method` scoped-name
path, now called from `parse_constraint` as well. Its contract is unchanged
(it splits a `::` chain into scope + final name); this caller keeps neither
half.
- `error-recovery` — `parse_source_tolerant` is untouched. The cascade
collapse is a pure consequence of the construct parsing: no error node is
produced, so there is nothing to resynchronize from.
**Promised to others:**
- **Semantics / index: an out-of-block constraint contributes nothing** — no
symbol for the constraint name, no reference for any name inside the body,
no scope. This is *deliberately identical* to the in-class case, which
`class-semantics`'s README already states as rule 2 ("Verbatim members stay
opaque") and pins with a test. Mechanically it is the same
`ItemKind::Verbatim(_) => {}` arm in `bind.rs:372`, reached by the same item
walker; item position never entered into it. Verified empirically on the
shape (a class with `extern constraint`, its out-of-block definition, and an
out-of-body method): symbols are exactly `{Class my_seq, Var num_trans,
Function configure}`, zero references anywhere inside the constraint block,
and every offset in the file is panic-free for `definition_of` /
`symbol_at` / `reference_at`.
- **Request to the lead (not acted on):** if that promise should be *pinned*
rather than documented, the edit is one new test in
`crates/vlog_semantic/tests/classes.rs`, next to the existing
`constraint`/`covergroup` opacity test at line ~604, asserting the same
three facts on the out-of-block shape. Not written here because
`crates/vlog_semantic` is in this lane's file list only "if an arm is
needed", and no arm is needed.
- **Ownership note (flagged for merge):** requirement 3 of this lane's brief
asks for formatter snapshot + idempotency coverage, but
`crates/vlog_formatter/tests/*` belongs to Lane B. Resolved by adding
**one new file** and editing none:
`crates/vlog_formatter/tests/cases/out_of_class_constraints.cases`. The
`cases.rs` harness auto-discovers `tests/cases/*.cases` and asserts *both*
the expected output and idempotency of that output, so this single file
satisfies the requirement with zero textual overlap with Lane B's work.
- **Handed on:** `hw/dv/sv/cip_lib/seq_lib/cip_base_vseq.sv` — the worst
cascade in the corpus — now advances past this blocker to bucket 10
(`type_t'{...}`, a cast applied to an assignment-pattern literal) at
`cip_base_vseq.sv:1462`. That bucket belongs to TODO §11's mop-up round.
## Status / TODO
- [x] Parser: `parse_constraint` accepts an optional `Ident ::` scope chain
before the constraint name, via `parse_method_name`.
- [x] All 45 bucket-1 OpenTitan files stop failing on this construct;
44 parse and format clean, 1 advances to a different bucket.
- [x] No new failure anywhere in the 3,943-file sweep (set difference, not
just counts).
- [x] Tolerant cascade measured before and after with the standalone
`parse_source_tolerant` probe.
- [x] Parser unit tests (5) in `parser.rs`'s test module.
- [x] Tolerant regression test in `crates/vlog_parser/tests/error_recovery.rs`.
- [x] Span-walker coverage: a new `SOURCES` entry in
`crates/vlog_parser/tests/spans.rs` (byte coverage, span nesting,
name spans, token reconstruction — all reused, no new assertions needed).
- [x] Formatter snapshot + idempotency: 5 cases in a new
`out_of_class_constraints.cases`.
- [x] Corpus gate: 813/820, exactly the baseline, no regression.
- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test --workspace`.
- [ ] **Not done, deliberately:** no node for the constraint name, so
go-to-definition from `constraint C::x` to `extern constraint x;` does
not work. Same gap the in-class form has had since `classes`; closing it
is a real-AST decision, not a parser fix.
- [ ] **Not done, out of scope:** `cip_base_vseq.sv`'s next blocker
(bucket 10, cast-to-assignment-pattern).
## Work log
### 2026-08-29 — dev (Lane A)
**Root cause, confirmed by reading not by inference.** `parse_constraint`
(`crates/vlog_parser/src/parser.rs`) called `self.expect_name()?` — one
identifier — and then demanded `{` or `;`. On `constraint C::name {` that
fails at the `::`, reporting `expected `{` (found "::")` positioned on the
class name, one token *before* the real surprise. Exactly the diagnosis
`syntax_coverage.md` recorded.
**The fix is one call.** `self.expect_name()?` → `self.parse_method_name()?`.
`parse_method_name` is the existing out-of-body-method path (`function void
my_class::configure(...)`); it consumes a `::` chain and splits scope from
name. `parse_constraint` keeps neither, because the item it returns is a
`RawText` span. Plus a doc-comment paragraph saying why.
**Design choice: verbatim reuse, no new AST variant.** The brief's expectation
held up against the code. `ItemKind::Constraint` does not exist — a constraint
has always been an `ItemKind::Verbatim(RawText)` leaf (`classes`' deliberate
"don't model the grammar, copy the bytes"), and `parse_item_kind` already
dispatches `"constraint"` at item position (line 1332), which is the same
function that parses file-scope, package-scope and module-scope items. So the
out-of-block form was *already* routed to the right parser from the right
position; only the name grammar was too narrow. Consequences: no `ast.rs`
change, no `format.rs` arm, no `bind.rs` arm, no `spans.rs` arm, no
`visit.rs` arm, no `verify.rs` change (invariant 4 does not engage — nothing
in the safety net was widened). Blast radius: one function body.
**Measured on the real OpenTitan checkout** (`/Users/guoliangchen/repo/opentitan`,
3,943 `.sv`/`.svh` files, `--no-cache --check`, read-only; the tree's one
pre-existing modification, `hw/ip/aes/dv/tb/tb.sv`, was there before and after
and is not this round's).
| | before | after |
|---|---|---|
| files failing (whole sweep) | 151 | **107** |
| bucket-1 files failing on `expected `{` (found "::")` | 45 | **0** |
| bucket-1 files parsing + formatting clean | 0 | **44** |
| bucket-1 files advanced to a *different* bucket | — | 1 |
| files that newly fail (set difference) | — | **0** |
The single file that still fails, `hw/dv/sv/cip_lib/seq_lib/cip_base_vseq.sv`,
no longer fails on a constraint: it now reaches line 1462 and stops on
`addr_mask_t'{addr, mask}` — bucket 10, a distinct documented gap owned by the
mop-up round. This is the ordinary corpus-check "a fix advances a file into
the next bucket" outcome, and it is why the honest headline is *45 of 45
unblocked, 44 of 45 fully clean*.
**Tolerant-mode cascade, the LSP half.** Probed with a standalone crate
path-depending on this worktree's `vlog_parser` and calling
`parse_source_tolerant` directly (`syntax_coverage.md`'s method 1 — necessary
because `lucisv check`'s exit code deliberately discards `ParseDiagnostic`s).
Over the same 45 files:
| | before | after |
|---|---|---|
| total tolerant diagnostics | **1 349** | **1** |
| files with any diagnostic | 45 | 1 |
| mean per file | 30.0 | 0.02 |
| `cip_base_vseq.sv` (worst) | 322 | 1 *(the bucket-10 cast, not a cascade)* |
| `hmac_base_vseq.sv` | 274 | **0** |
| `aon_timer_base_vseq.sv` | 79 | **0** |
| `ac_range_check_base_vseq.sv` | 67 | **0** |
| `tl_seq_item.sv` | 60 | **0** |
The cascade does not shrink, it disappears: the construct parses, so no error
node is created and the recovery loop is never entered. The one surviving
diagnostic is a clean single-point report of a different, real gap.
**Formatter round-trip.** Idempotency was checked on all 45 real corpus files
by formatting each through stdin twice (never writing to the corpus):
**44 idempotent, 0 non-idempotent, 1 unformattable** (the bucket-10 file). For
each of the 44, every `constraint C::name` header present in the input is
present in the output — the verbatim capture reproduces the block byte for
byte, and `format_source`'s own token-equivalence check (invariant 1) passed
on all 44, which is what actually guarantees no comment or token was lost.
Layout behaviour matches the in-class constraint exactly and needed no printer
work: the block's *absolute* indent is re-set to its item position, its
*relative* interior layout is untouched (`classes`' documented rule).
**Corpus gate.** `scripts/corpus_gate.sh` against the pinned 820-file corpus:
`{"passing":813,"total":820,...}`, 0 verification errors, 0 crashes — exactly
the recorded baseline, no regression. The pinned corpus contains no
out-of-block constraint, which is precisely why this gap went unmeasured until
the full-OpenTitan sweep; the strict-superset rule holds.
**Tests added.**
- `crates/vlog_parser/src/parser.rs` (test module, new section):
- `an_out_of_block_constraint_is_a_file_scope_verbatim_item` — the leaf, and
that its text is its own source slice.
- `an_out_of_block_constraint_scope_may_be_a_chain` — `pkg::cls::name`.
- `an_out_of_block_constraint_lives_in_a_package_too` — package scope.
- `an_out_of_block_constraint_keeps_its_trailing_semicolon_and_comments` —
the stray `;` is inside the capture, the leading and trailing comments are
outside it and both survive (invariant 3).
- `an_in_class_constraint_still_rejects_a_scope_free_syntax_error` — the
widened name must not swallow `constraint c:: {` or `constraint 4::x`;
both still error, with the message pinned.
- `crates/vlog_parser/tests/error_recovery.rs`:
`out_of_block_constraints_do_not_cascade` — the miniature of the real shape
(class with two `extern constraint` prototypes and an `extern function`,
then their out-of-block definitions), asserting **zero** tolerant
diagnostics and strict/tolerant agreement.
- `crates/vlog_parser/tests/spans.rs`: one new `SOURCES` entry, which the
file's existing exhaustive walkers pick up for free — token/byte coverage,
span nesting, name-span slicing, source reconstruction.
- `crates/vlog_formatter/tests/cases/out_of_class_constraints.cases` (new
file): 5 cases — prototype + definition, package re-indent, scope chain with
a stray `;` and comments on both sides, empty body, and a body exercising
the constraint sub-grammar (`dist`, `->`, `foreach`, `if`/`else`). The
harness asserts expected-output *and* idempotency for each.
**Gates.** `cargo fmt --all -- --check` clean; `cargo clippy --all-targets`
clean (no new warnings, no `#[allow]`); `cargo test --workspace` green —
35 test binaries, 0 failures.
**Deviations from the brief.** One, declared above under Handshakes: the
formatter coverage requirement (3) lands in a directory Lane B owns. Handled
as a single new file with no edits to any existing Lane B file, flagged here
and in the lane report rather than done silently.
## QA log
### 2026-08-29 — QA (Lane A)
Verdict: **SHIP**. No corruption, no cascade regression, no gate slippage
found. One test added (see below); everything else in this entry is
verification, not redesign.
**Grammar-widening attacks** (charter item 1) — probed the built
`lucisv --stdout -` on adversarial inputs, all behaving safely (correct
error or correct accept, never a crash, never silent corruption):
- `constraint ::name { a == 0; }` → `1:12: expected identifier (found "::")`.
- `constraint C:: { a == 0; }` → `1:16: expected identifier (found "{")`
(already pinned by the dev's own
`an_in_class_constraint_still_rejects_a_scope_free_syntax_error`).
- `constraint pkg::cls::inner::deep_c { ... }` (3-part chain) — **accepts**.
Judged and pinned here: a 3+-part chain is not realizable SV (classes
don't nest, so the longest legal chain a real out-of-body definition can
have is `pkg::class::name`), but this is a pure-verbatim leaf — the chain
text is consumed and discarded, nothing downstream trusts its structure —
so accepting more than the LRM allows costs nothing and matches the
README's own Assumptions section, which already makes this call. Not a
defect.
- `constraint new { a == 0; }` (keyword-shaped name) — accepts, because
`"new"` is deliberately not a lexer keyword
(`crates/vlog_parser/src/token.rs:334`) and `expect_name` only checks
`TokenKind::Ident`. Pre-existing `expect_name` behavior, not a widening
`parse_method_name` introduces.
- Escaped identifiers on either side of `::` (`` \my-class ::name ``) —
accept; the lexer already tags an escaped identifier `Ident`
(`crates/vlog_parser/src/lexer.rs:301-314`), so this is old lexer behavior,
not new surface from this round.
- `constraint C::name;` (a scope on a *prototype*, no body) — **accepts**,
producing a verbatim `constraint C::name;` item. This shape doesn't occur
in the corpus and isn't a real `extern constraint` (those live in-class,
unscoped) — but same reasoning as the chain-depth point: pure verbatim
capture, no data trusted downstream, matches "no new legal-position check"
in Assumptions. Flagging it here so it's a documented, not accidental,
permissiveness.
- `constraint C::name { ... }` at **module scope** (illegal SV) — accepts,
exactly as the Assumptions section already states it would (the bare form
already had this permissiveness pre-round). Not new.
- `constraint` as the last token of the file, and `constraint C::name` with
no body at EOF — both give clean, correctly-positioned parse errors
(`expected identifier (found "<eof>")`, `` expected `{` (found "<eof>") ``),
no panic, no hang.
- `constraint 4::x { ... }` — `1:12: expected identifier (found "4")`
(already pinned by the dev's test of the same name).
None of these findings block shipping: every widened-acceptance case is
already named and justified in the feature's own Assumptions section, and
none of them can corrupt output because the whole item stays a byte-exact
verbatim span. No new test added for this item — the two shapes worth
pinning (`::` with no name, digit as scope) were already covered by the
dev's tests, and I've recorded the judgment on chain depth and the
prototype-with-scope shape here rather than in code, since they're accepted
permissiveness, not bugs.
**Verbatim integrity** (charter item 2) — built `lucisv` release binary from
this worktree and round-tripped by hand (format twice, diff outputs; also
compared against source where relevant):
- String containing `}` inside the body — idempotent, brace inside the
string does not confuse `skip_balanced`.
- Block comment containing `{`/`}` inside the body — idempotent.
- `` `ifdef ``/`` `else ``/`` `endif `` inside the body — idempotent (the
whole conditional is inside the verbatim span, never interpreted).
- CRLF line endings inside the body — idempotent; CRLF is normalized to LF
on the way in, which is pre-existing whole-file lexer behavior unrelated
to this round, not something this change introduces.
- A `constraint C::name { ... }` nested three packages deep with
inconsistent absolute indentation and extra relative indentation in the
body — confirmed the `RawText.col` dedent contract (topo §2.2) holds: the
block's absolute indent resets to its item position, every line's
*relative* offset from the original `constraint` line is preserved
exactly, and the result is idempotent.
- All 5 cases in the dev's new
`crates/vlog_formatter/tests/cases/out_of_class_constraints.cases` pass,
confirmed the harness (`crates/vlog_formatter/tests/cases.rs:178`) actually
asserts idempotency per case, not just expected output.
**Cascade honesty** (charter item 3) — built a standalone probe crate
depending on this worktree's `vlog_parser` (`parse_source_tolerant`
directly), run against the real `/Users/guoliangchen/repo/opentitan`
checkout, read-only throughout (`git status --porcelain` before and after:
only the pre-existing `hw/ip/aes/dv/tb/tb.sv` modification, untouched).
- Reproduced the dev's 5 named files exactly, both sides, via
`git stash`/`stash pop` on `crates/vlog_parser/src/parser.rs` alone:
| file | before | after |
|---|---|---|
| `cip_base_vseq.sv` | 322 | 1 (bucket-10, not a cascade) |
| `hmac_base_vseq.sv` | 274 | 0 |
| `aon_timer_base_vseq.sv` | 79 | 0 |
| `ac_range_check_base_vseq.sv` | 67 | 0 |
| `tl_seq_item.sv` | 60 | 0 |
- 5 more bucket-1 files of my own choosing (`alert_esc_seq_item.sv`,
`dv_base_env_cfg.sv`, `kmac_app_agent_cfg.sv`,
`adc_ctrl_filter_cfg.sv`, `aon_timer_common_vseq.sv`): before 3/40/1/10/5,
after all 0. Cascade collapse confirmed on a sample the dev didn't hand-pick.
- 20 files sampled from outside the failing set (mixed `dv/`/`rtl/`,
various IPs, one from `vendor/`) probed before and after the same
stash/pop: **byte-identical diagnostic counts both sides** (one file,
`rng_agent/rng_driver.sv`, carries 1 diagnostic both before and after —
pre-existing, unrelated to this change). No new tolerant diagnostic
anywhere in the sample.
**Strict-superset discipline** (charter item 4) — reproduced independently,
not trusted from the write-up:
- Corpus gate: `scripts/corpus_gate.sh` against
`/Users/guoliangchen/repo/verilogrustformatter/corpus` (the worktree has
no local `corpus/`, it's gitignored) → `{"passing":813,"total":820,...}`,
0 verification errors, 0 crashes. Exact match to the claimed baseline.
- Whole-sweep count: built the release binary with the fix stashed out and
back in, ran `lucisv --no-cache --check` over all 3,943 real-OpenTitan
`.sv`/`.svh` files both ways. **151 → 107**, exact match.
- Set difference: `comm -23` between the after-failing and before-failing
file lists → **0 newly-failing files**; `comm -13` → 44 newly-fixed files
(151 − 107 = 44, consistent). The 45th named file
(`cip_base_vseq.sv`) confirmed still failing, but on a *different*
diagnostic: `1462:65: expected `)` (found "'{")`, i.e. line 1462's
`addr_mask_t'{addr, mask}` — exactly the claimed bucket-10 advance, not a
constraint failure.
- Idempotency on all 44 newly-clean files (not the dev's sampled subset —
the full 44): scripted format-twice-and-diff over each; **0 failures, 0
non-idempotent**.
**The three flagged deviations** (charter item 5):
- (a) `crates/vlog_formatter/tests/cases/out_of_class_constraints.cases` —
`git status --porcelain` shows it `??` (untracked, new-file-only); no
existing Lane B file touched. Confirmed the harness exercises idempotency
for it (see above). Genuinely additive, as claimed.
- (b) `TODO.md` §11 — diffed the worktree's version against
`git show master:TODO.md`: the only difference is Lane A's own checkbox
(unchecked → checked) and one added summary line under Lane A's item.
Lane B's subsection and the "serial, after Lane A merges" section are
byte-identical to trunk. The trivially-parallel merge claim holds.
- (c) The un-pinned `vlog_semantic` opacity promise — per my small-fix
license and the charter's explicit instruction, added the test the dev
specified in Handshakes:
`crates/vlog_semantic/tests/classes.rs::an_out_of_block_constraint_is_absent_but_nothing_crashes`,
next to the existing `verbatim_members_are_absent_but_nothing_crashes`.
One correction while writing it: my first draft assumed the *out-of-block
definition* was the only opaque part and that the in-class `extern
constraint num_trans_c;` prototype would still produce a `num_trans_c`
symbol — it does not; the prototype is itself an `ItemKind::Verbatim`
leaf too (parsed by the same `parse_constraint`), so neither the
prototype nor the definition binds a symbol. Fixed the assertion to match
reality (confirmed by running the test against the actual analyzer output
before asserting) rather than the assumption. Test passes.
**Full gates** (charter item 6), re-run after adding the `vlog_semantic`
test: `cargo fmt --all -- --check` clean; `cargo clippy --all-targets`
clean, 0 warnings; `cargo test --workspace` green (35 test binaries, 0
failures, includes the new test); corpus gate 813/820 as above.
**Findings summary** (severity — all informational/non-blocking, nothing
found that requires rework):
- INFO: `parse_constraint` now accepts several shapes the OpenTitan corpus
never exercises and the LRM doesn't sanction (chains deeper than 2,
a scoped prototype with no body, module-scope placement) — all already
named as deliberate in the feature's Assumptions section and all
incapable of corrupting output, since the entire item is a byte-exact
verbatim capture. No action needed; recorded here so the judgment call is
visible to reviewers who don't re-derive it.
- INFO: the dev's Handshakes-proposed `vlog_semantic` test had a wrong
assumption baked into its own description (that `extern constraint
num_trans_c;` binds a symbol); the corrected version now pins the real
behavior (neither prototype nor definition binds a symbol).
**Tests added:** 1 —
`crates/vlog_semantic/tests/classes.rs::an_out_of_block_constraint_is_absent_but_nothing_crashes`.
## Review
**2026-08-29 — lead.** Reviewed after QA's clean SHIP; gates re-run on
the worktree. This round is the loop at its best-case: the analysis
sweep named the bucket, the fix is one line reusing a path the grammar
already had, the blast radius is zero by construction (verbatim leaf,
no new variant), and the payoff is the largest single coverage move
available — 45 files unblocked and a 1,349-diagnostic tolerant cascade
reduced to one honest report. QA's stash-based before/after on
previously-clean files is the check that matters for a grammar
widening (a cascade that moved would have hidden), and its correction
of the dev's own specified-but-wrong semantic test (extern prototypes
are verbatim too) is exactly why the QA leg exists. The deliberate
over-acceptances (deep scope chains, scoped prototypes, module-scope
placement) are recorded as judgment calls with the corruption argument
attached — acceptable for a byte-exact capture. Accepted; merged by
the lead. parser.rs is now free for the directive-split round.
File renamed without changes.
+4
View File
@@ -350,6 +350,10 @@ recursion-limit, whose edges sit in §2.1). Code edges:
| `classes ◀──▶ class-semantics` | handshake | classes shipped with the honest gap "no name inside a class body is indexed"; class-semantics closed it (see §2.5). |
| `classes ─▶ format-fences` | open request | `fence::scan_nested` has no `Class` arm, so a fence inside a class body is inert **for the formatter** (the `protected_regions` line-scan backstop still protects `--fix`). Filed, not fixed — §2.9. |
| `ansi-first-port ◀──▶ type-definition` | handshake | type-definition filed the "first port with no direction doesn't parse" request; ansi-first-port delivered it (parser + one `bind_data_type` arm + one `type_span` tweak), and type-definition's tests flipped. |
| `out-of-class-constraints ──▶ classes` | depends | Reuses the verbatim constraint capture and `parse_method_name` unchanged; one line in `parse_constraint`, no new AST variant, so none of the exhaustive-arm blast radius applies (2026-08-29 testbench wave, Lane A). |
| `directive-in-statements ──▶ directive-split / directives-in-lists / assertions` | depends | The mirror-image recovery: a directive OPENING inside a statement/expression, captured verbatim through `construct_end` (Semi / endfunction+label / Unknown → refuse) and `terminated_in_arm`; `take_list_directives` additionally stops harvesting an outer region's `` `else `` as a list element. No new AST variant (2026-08-29 testbench wave, serial round). |
| `directive-in-statements ◀──▶ formatter-bug-fixes` | handshake | formatter-bug-fixes round 2 filed the `take_before_open` pending-comment drain; directive-in-statements delivered it as `Parser::take_gap` (comments kept only when `span.start >= last_end()`, `CallComments::dangling` included — the specified fix alone was insufficient). The refusal pin flipped to a formats case on the merged tree, closing the last bucket-2 file (`keymgr_scoreboard.sv`). |
| `formatter-bug-fixes (round 2) ──▶ safety-net` | depends | Three comment-shape bugs fixed in `format.rs` (`then_is_block` trailing-line-comment cuddle guard, `Fmt::header_parens`, `default_has_colon`); `verify.rs` untouched, four masked-corruption rejection pairs added per the standing template, plus three more for the directive capture at merge (2026-08-29 testbench wave, Lane B + lead). |
| `lexer-cleanup ──▶ error-recovery / lint-rules-2` (QA logs) | depends | Fixes three lexer gaps: `@(* )` (TODO §1) plus the BOM and non-ASCII-honesty findings those two QA rounds filed; adds `ParsedSource::lex_error()` so `lucisv check` stops silently passing unlexable files. |
| `error-recovery ─▶ lucisv-server / linter-core` | depends (downstream) | `parse_source_tolerant` is the entry point the whole LSP and the linter stand on; the strict/tolerant split (shared grammar, no second parser) is the contract. |
| `name-spans ◀──▶ vlog-semantic` | handshake | vlog-semantic filed request 1 (spans on ~15 declaring nodes); name-spans delivered it, shrinking `scan.rs` to the `DataType` case (still open — §2.9). |
+15
View File
@@ -25,6 +25,21 @@ number; the full engineering notes live in the
quarter of a second. The index cache rebuilds once because its facts format
changed.
## 0.16.0 — 2026-08-29
The testbench-syntax release.
- **DV and testbench code parses much better**: out-of-class
constraints (`constraint C::name {...}`), `` `ifdef `` blocks that
split an assign or an instantiation, and more — 51 additional files
of a 3,943-file opentitan checkout now parse and format, and the
bogus-diagnostic cascades those files produced in the editor are
gone.
- **Comment-handling formatter fixes**: comments trailing `end`, inside
condition parentheses, and `default;` case items all format
faithfully now.
- No settings or index changes; caches re-verify once after updating.
## 0.15.0 — 2026-08-29
The interactive-latency release.
+9 -1
View File
@@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view,
then open a Verilog or SystemVerilog file. There is no separate server or CLI
setup.
The current release is **0.15.0**. Its platform packages include both
The current release is **0.16.0**. Its platform packages include both
`lucisv-server` and the `lucisv` command-line tool:
| Package target | Machines |
@@ -325,6 +325,14 @@ Every nesting color is a proper VS Code theme color:
}
```
## Release 0.16.0 highlights
Version 0.16.0 is the testbench-syntax release: out-of-class
constraints, `` `ifdef `` splitting statements, and comment-shape
formatter fixes — 51 more files of a real 4,000-file SoC parse, format
and diagnose cleanly, and testbench editing stops drowning in cascade
diagnostics.
## Release 0.15.0 highlights
Version 0.15.0 is the interactive-latency release:
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "lucisv",
"displayName": "lucisv — Verilog/SystemVerilog",
"description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.",
"version": "0.15.0",
"version": "0.16.0",
"publisher": "guoliangchen",
"author": "Guoliang Chen",
"license": "MIT",