Fix round-1 QA findings: Inline width in fits(), action-block nesting, comment gaps

printer::fits() now measures from a multi-line Doc::Inline's last line and
keeps measuring the rest of the group (a with {...} block no longer hides
an overflow). skip_action_stmt tracks begin/end, fork/join, case/endcase
nesting so a concurrent assertion's action block is captured whole.
Comments between bind/target/module and around randomize(...) with are
attached and reprinted instead of being refused by the safety net.
All 800 passing corpus files format byte-identically before and after.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-21 02:11:59 -07:00
1 parent e35da292bd
commit a4f8476894
14 files changed
+656 -57

No files matched your search

+3 -1
View File
@@ -363,7 +363,9 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
`docs/features/classes/README.md` `docs/features/classes/README.md`
- Concurrent assertions (IEEE 1800 §16): `assert`/`assume`/`cover`/`restrict - Concurrent assertions (IEEE 1800 §16): `assert`/`assume`/`cover`/`restrict
property ( ... )` with an optional `label:` prefix and an action block property ( ... )` with an optional `label:` prefix and an action block
(`else $error(...)`, `$info(...); else ...`, `else begin ... end`), wherever (`else $error(...)`, `$info(...); else ...`, `else begin ... end`, and any
statement that nests blocks: `if (c) begin ... end else ...`,
`fork ... join_none`, `case ... endcase`), wherever
a module item or a statement can appear — module and package bodies, a module item or a statement can appear — module and package bodies,
generate regions, `begin`/`end`, and at file scope. Plus `sequence ... generate regions, `begin`/`end`, and at file scope. Plus `sequence ...
endsequence` and `property ... endproperty` declarations. All of it is endsequence` and `property ... endproperty` declarations. All of it is
+5
View File
@@ -111,6 +111,11 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
instead of printing all comments then all attributes. Sweep 14 → 0; the instead of printing all comments then all attributes. Sweep 14 → 0; the
exhaustive per-line sweep's survivors are the shapes parked above plus exhaustive per-line sweep's survivors are the shapes parked above plus
a comment before `else` — see `docs/features/comments-round-2/README.md`. a comment before `else` — see `docs/features/comments-round-2/README.md`.
→ QA round-1 follow-up closed three more shapes with no node of their
own: between `bind` and its target (and before the bound module name),
before a call's `(` / inside an empty `()`, and on either side of a
postfix `with`. Still parked: a comment before a procedural statement's
`;`, and one inside a `bind`'s `: instance, list`.
- [x] **Two leading comments separated by one blank line come out - [x] **Two leading comments separated by one blank line come out
separated by two** (format-fences QA find, pre-existing): `leading` separated by two** (format-fences QA find, pre-existing): `leading`
pushes a HardLine after each comment and a BlankLine before the next. pushes a HardLine after each comment and a BlankLine before the next.
+42 -9
View File
@@ -253,6 +253,18 @@ impl<'a> Fmt<'a> {
Doc::Inline(raw.text.clone()) Doc::Inline(raw.text.clone())
} }
/// `<base> with ` — the head both postfix `with` forms share, with the
/// comments written on either side of the keyword printed back where they
/// were written. Anywhere else they would move across `with` and the
/// safety net would reject the output.
fn with_head(&self, base: &Expr, comments: &WithComments) -> Doc {
let mut docs = vec![self.expr(base)];
self.inline_comments_spaced(&comments.before_kw, &mut docs);
docs.push(text("with"));
self.inline_comments_spaced(&comments.after_kw, &mut docs);
concat(docs)
}
/// A macro invocation standing as an item or a statement. The invocation /// A macro invocation standing as an item or a statement. The invocation
/// itself is verbatim source — we do not expand macros, so re-spacing the /// itself is verbatim source — we do not expand macros, so re-spacing the
/// argument list would be guesswork — and the trailing `;` is reproduced /// argument list would be guesswork — and the trailing `;` is reproduced
@@ -1640,11 +1652,18 @@ impl<'a> Fmt<'a> {
/// instantiation written on its own would be. /// instantiation written on its own would be.
fn bind(&self, b: &BindDirective, depth: usize) -> Doc { fn bind(&self, b: &BindDirective, depth: usize) -> Doc {
let head = if b.instances.is_empty() { let head = if b.instances.is_empty() {
format!("bind {} ", b.target) b.target.clone()
} else { } else {
format!("bind {} : {} ", b.target, join_names(&b.instances)) format!("{} : {}", b.target, join_names(&b.instances))
}; };
concat(vec![text(head), self.instantiation(&b.inst, depth)]) // The comments around the head have no node of their own; each prints
// back between the two tokens it was written between.
let mut docs = vec![text("bind")];
self.inline_comments_spaced(&b.target_comments, &mut docs);
docs.push(text(head));
self.inline_comments_spaced(&b.module_comments, &mut docs);
docs.push(self.instantiation(&b.inst, depth));
concat(docs)
} }
fn instantiation(&self, inst: &Instantiation, depth: usize) -> Doc { fn instantiation(&self, inst: &Instantiation, depth: usize) -> Doc {
@@ -2781,8 +2800,22 @@ impl<'a> Fmt<'a> {
} }
self.ternary_with_comments(cond, then, els, comments) self.ternary_with_comments(cond, then, els, comments)
} }
ExprKind::Call { callee, args } => { ExprKind::Call { callee, args, comments } => {
concat(vec![self.expr(callee), self.expr_list("(", args, ")")]) if comments.is_empty() {
return concat(vec![self.expr(callee), self.expr_list("(", args, ")")]);
}
// A comment written around the brackets prints back between
// the same two tokens it was written between: after the
// callee, and inside the empty `()` that had nowhere else to
// put it.
let mut docs = vec![self.expr(callee)];
if !comments.before_open.is_empty() {
self.inline_comments_spaced(&comments.before_open, &mut docs);
}
let items: Vec<ListItem> =
args.iter().map(|i| ListItem::from_meta(&i.meta, self.expr(&i.expr))).collect();
docs.push(self.delimited_dangling("(", items, &comments.dangling, ")", false));
concat(docs)
} }
// `new src` — one space, never a break: the source handle is a // `new src` — one space, never a break: the source handle is a
// postfix expression that breaks internally if it must. // postfix expression that breaks internally if it must.
@@ -2873,11 +2906,11 @@ impl<'a> Fmt<'a> {
text("}"), text("}"),
]), ]),
ExprKind::Postfix { expr, op } => concat(vec![self.expr(expr), text(op.clone())]), ExprKind::Postfix { expr, op } => concat(vec![self.expr(expr), text(op.clone())]),
ExprKind::With { base, arg } => { ExprKind::With { base, arg, comments } => {
concat(vec![self.expr(base), text(" with "), self.expr(arg)]) concat(vec![self.with_head(base, comments), self.expr(arg)])
} }
ExprKind::WithConstraint { base, block } => { ExprKind::WithConstraint { base, block, comments } => {
concat(vec![self.expr(base), text(" with "), self.with_block(block)]) concat(vec![self.with_head(base, comments), self.with_block(block)])
} }
ExprKind::Inside { lhs, ranges } => { ExprKind::Inside { lhs, ranges } => {
concat(vec![self.expr(lhs), text(" inside "), self.expr_list("{", ranges, "}")]) concat(vec![self.expr(lhs), text(" inside "), self.expr_list("{", ranges, "}")])
+43 -6
View File
@@ -134,12 +134,23 @@ impl Printer {
let Some((mode, d)) = stack.pop() else { return true }; let Some((mode, d)) = stack.pop() else { return true };
match d { match d {
Doc::Text(s) => width -= s.chars().count() as isize, Doc::Text(s) => width -= s.chars().count() as isize,
Doc::Inline(s) => match s.split_once('\n') { Doc::Inline(s) => {
// Only the first line shares the current line; if it // Only the first line shares the current line, and it has
// fits, the rest of the group starts after a break. // to fit on it. What follows the text keeps writing on
Some((head, _)) => return width - head.chars().count() as isize >= 0, // the line its *last* line ends on (that is what `print`
None => width -= s.chars().count() as isize, // does), so measuring continues from there rather than
}, // stopping here — otherwise a group whose tail overflows
// would be judged to fit.
if let Some((head, _)) = s.split_once('\n') {
if width < head.chars().count() as isize {
return false;
}
let last = s.rsplit_once('\n').map_or(0, |(_, l)| l.chars().count());
width = self.max_width as isize - last as isize;
} else {
width -= s.chars().count() as isize;
}
}
Doc::Concat(items) | Doc::Indent(items) => { Doc::Concat(items) | Doc::Indent(items) => {
for it in items.iter().rev() { for it in items.iter().rev() {
stack.push((mode, it)); stack.push((mode, it));
@@ -217,6 +228,32 @@ mod tests {
assert_eq!(p(8, d), "foo(\n barbarbar\n)"); assert_eq!(p(8, d), "foo(\n barbarbar\n)");
} }
/// A multi-line `Inline` does not end the line: whatever follows it keeps
/// writing on the line its last line ends on, so the group's fit check has
/// to keep measuring past it — from that line's width, not from the
/// indent. QA round-1 finding.
fn inline_group(tail: &str) -> Doc {
group(vec![
text("if ("),
Doc::Inline("with {\n x == 1;\n} ".into()),
indent(vec![Doc::SoftLine, text(tail)]),
text(")"),
])
}
#[test]
fn group_stays_flat_when_the_tail_after_an_inline_fits() {
assert_eq!(p(20, inline_group("&& ok")), "if (with {\n x == 1;\n} && ok)");
}
#[test]
fn group_breaks_when_the_tail_after_an_inline_overflows() {
assert_eq!(
p(20, inline_group("&& far_too_long_to_fit")),
"if (with {\n x == 1;\n}\n && far_too_long_to_fit)"
);
}
#[test] #[test]
fn hard_line_forces_break() { fn hard_line_forces_break() {
let d = group(vec![text("a"), Doc::HardLine, text("b")]); let d = group(vec![text("a"), Doc::HardLine, text("b")]);
@@ -265,3 +265,52 @@ module m;
assert property (@(posedge clk_i) disable iff (!rst_ni) some_very_long_signal_name_here |-> ##[1:3] another_quite_long_signal_name); assert property (@(posedge clk_i) disable iff (!rst_ni) some_very_long_signal_name_here |-> ##[1:3] another_quite_long_signal_name);
endmodule endmodule
==== ====
# an action block whose pass statement is an `if` with a `begin ... end`
# body: the block -- and the `else` after it -- belong to the assertion,
# and the item after it survives
module m;
always @(posedge clk)
assert property (@(posedge clk) a |-> b)
if (cond) begin
x = 1;
end
else y = 2;
wire w;
endmodule
----
module m;
always @(posedge clk)
assert property (@(posedge clk) a |-> b)
if (cond) begin
x = 1;
end
else y = 2;
wire w;
endmodule
====
# an action block that is a `fork ... join_none`, `disable fork` inside it
# (which names the enclosing block rather than opening one)
module m;
always @(posedge clk)
assert property (a |-> b)
fork
begin
disable fork;
end
join_none
else $error("no");
wire w;
endmodule
----
module m;
always @(posedge clk)
assert property (a |-> b)
fork
begin
disable fork;
end
join_none
else $error("no");
wire w;
endmodule
====
@@ -293,3 +293,27 @@ module m;
end end
endmodule endmodule
==== ====
# comments written where the directive has no node to hang them on: between
# `bind` and the target, and between the target (or the instance list) and
# the module name
module m;
bind /*c1*/ dut /*c2*/ checker_mod c_inst (.clk(clk));
bind dut : u_a, u_b /*c3*/ checker_mod c2_inst (.clk(clk));
endmodule
----
module m;
bind /*c1*/ dut /*c2*/ checker_mod c_inst (.clk(clk));
bind dut : u_a, u_b /*c3*/ checker_mod c2_inst (.clk(clk));
endmodule
====
# a *line* comment after `bind` ends its line, so the target starts the next
module m;
bind // the target is the design under test
dut checker_mod c_inst (.clk(clk));
endmodule
----
module m;
bind // the target is the design under test
dut checker_mod c_inst (.clk(clk));
endmodule
====
@@ -576,3 +576,66 @@ module m;
initial x = 1; initial x = 1;
endmodule endmodule
==== ====
#a with-block condition whose tail still fits stays on the block's last line
class c;
task t;
if (req.randomize() with {
addr == 32'h1000;
} && cfg.enable_the_long_named_feature_flag && other_condition_name_goes_right_here) begin
z = 1;
end
endtask
endclass
----
class c;
task t;
if (req.randomize() with {
addr == 32'h1000;
} && cfg.enable_the_long_named_feature_flag && other_condition_name_goes_right_here) begin
z = 1;
end
endtask
endclass
====
#a with-block condition whose tail overflows wraps (printer fits() past a multi-line Inline)
class c;
task t;
if (req.randomize() with {
addr == 32'h1000;
} && cfg.enable_the_long_named_feature_flag && other_condition_name_goes_right_here_ok) begin
z = 1;
end
endtask
endclass
----
class c;
task t;
if (
req.randomize() with {
addr == 32'h1000;
} && cfg.enable_the_long_named_feature_flag && other_condition_name_goes_right_here_ok
) begin
z = 1;
end
endtask
endclass
====
# comments at every boundary of a `randomize() with { ... }` and of an
# array-method `with (expr)`: before the `(`, inside the empty `()`, before
# `with`, and between `with` and the block
class c;
task t;
y = x.randomize /*c1*/ ( /*c2*/ ) /*c3*/ with /*c4*/ {a == 1;};
z = q.sum() /*c5*/ with /*c6*/ (item.w);
endtask
endclass
----
class c;
task t;
y = x.randomize /*c1*/ (
/*c2*/
) /*c3*/ with /*c4*/ {a == 1;};
z = q.sum() /*c5*/ with /*c6*/ (item.w);
endtask
endclass
====
+45
View File
@@ -771,9 +771,16 @@ pub struct BindDirective {
/// the source may have written around the dots — the same caveat /// the source may have written around the dots — the same caveat
/// [`Instantiation::module_span`] carries for `::`. /// [`Instantiation::module_span`] carries for `::`.
pub target_span: TextRange, pub target_span: TextRange,
/// Comments written between `bind` and the target name. They have no node
/// of their own to hang on — the target is a bare string — so they are
/// kept here and printed back between the same two tokens.
pub target_comments: Vec<Comment>,
/// The `: u_a, u_b` instance list that narrows a module target to /// The `: u_a, u_b` instance list that narrows a module target to
/// particular instances. Empty when the source wrote no `:`. /// particular instances. Empty when the source wrote no `:`.
pub instances: Vec<Name>, pub instances: Vec<Name>,
/// Comments written between the target (or the instance list) and the
/// module name of the instantiation, for the same reason.
pub module_comments: Vec<Comment>,
/// The instantiation being bound, identical in shape to a standalone one. /// The instantiation being bound, identical in shape to a standalone one.
pub inst: Instantiation, pub inst: Instantiation,
} }
@@ -1343,6 +1350,10 @@ pub enum ExprKind {
Call { Call {
callee: Box<Expr>, callee: Box<Expr>,
args: Vec<ExprItem>, args: Vec<ExprItem>,
/// Boxed to keep `Expr` small, as for `TernaryComments`: a call with
/// comments written around its brackets is rare, and there is one
/// `Call` in every other line of real code.
comments: Box<CallComments>,
}, },
/// A shallow copy, IEEE 1800 §8.12: `new instr_template[name]` (corpus /// A shallow copy, IEEE 1800 §8.12: `new instr_template[name]` (corpus
/// `ibex/vendor/google_riscv-dv/src/isa/riscv_instr.sv:238`). The payload /// `ibex/vendor/google_riscv-dv/src/isa/riscv_instr.sv:238`). The payload
@@ -1441,6 +1452,8 @@ pub enum ExprKind {
With { With {
base: Box<Expr>, base: Box<Expr>,
arg: Box<Expr>, arg: Box<Expr>,
/// Boxed to keep `Expr` small, as for `TernaryComments`.
comments: Box<WithComments>,
}, },
/// `expr with { ... }` — the inline constraint block of a `randomize` /// `expr with { ... }` — the inline constraint block of a `randomize`
/// call (IEEE 1800 §18.7). The block is a `constraint` body written in an /// call (IEEE 1800 §18.7). The block is a `constraint` body written in an
@@ -1449,6 +1462,8 @@ pub enum ExprKind {
WithConstraint { WithConstraint {
base: Box<Expr>, base: Box<Expr>,
block: RawText, block: RawText,
/// Boxed to keep `Expr` small, as for `TernaryComments`.
comments: Box<WithComments>,
}, },
/// A named call argument: the `.ptr(ral.ovrd)` of /// A named call argument: the `.ptr(ral.ovrd)` of
/// `csr_wr(.ptr(ral.ovrd), .value(x))`. `value` is [`ExprKind::Empty`] /// `csr_wr(.ptr(ral.ovrd), .value(x))`. `value` is [`ExprKind::Empty`]
@@ -1506,6 +1521,36 @@ pub struct TernaryComments {
pub after_colon: Vec<Comment>, pub after_colon: Vec<Comment>,
} }
/// Comments written where a call's argument list has no element to carry
/// them: before the `(`, and inside an empty `()`. Both are kept so the
/// formatter can print them back between the same two tokens — dropped or
/// moved, the safety net rejects the output.
#[derive(Debug, Clone, Default)]
pub struct CallComments {
/// Between the callee and the `(` (`x.randomize /*c*/ ()`).
pub before_open: Vec<Comment>,
/// Inside an empty argument list (`x.randomize(/*c*/)`). A list with
/// elements carries its own comments on them, so this is empty there.
pub dangling: Vec<Comment>,
}
impl CallComments {
/// True when nothing was written around the brackets — the common case.
pub fn is_empty(&self) -> bool {
self.before_open.is_empty() && self.dangling.is_empty()
}
}
/// Comments written around the `with` of a postfix `with (expr)` or
/// `with { ... }`, kept per position for the reason [`TernaryComments`] gives.
#[derive(Debug, Clone, Default)]
pub struct WithComments {
/// Between the base expression and `with`.
pub before_kw: Vec<Comment>,
/// Between `with` and the `(` or `{` that follows it.
pub after_kw: Vec<Comment>,
}
impl TernaryComments { impl TernaryComments {
/// True when nothing was written inside the `? :` — the common case, laid /// True when nothing was written inside the `? :` — the common case, laid
/// out without any comment handling. /// out without any comment handling.
+193 -33
View File
@@ -138,6 +138,16 @@ const MEMBER_QUALIFIERS: &[&str] = &[
"var", "var",
]; ];
/// Keywords that open a statement block [`Parser::skip_action_stmt`] skips as
/// one unit. `fork` counts only where it opens a block: `disable fork` and
/// `wait fork` name the enclosing one.
const BLOCK_OPENERS: &[&str] = &["begin", "fork", "case", "casex", "casez", "randcase"];
/// Keywords that close one of [`BLOCK_OPENERS`]. Which opener a closer belongs
/// to is not checked — the scan only counts — so unbalanced input runs to the
/// end of the file and reports a clean error there.
const BLOCK_CLOSERS: &[&str] = &["end", "join", "join_any", "join_none", "endcase"];
const ASSIGN_OPS: &[&str] = const ASSIGN_OPS: &[&str] =
&["=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", "<<<=", ">>>="]; &["=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", "<<<=", ">>>="];
@@ -1590,10 +1600,10 @@ impl<'a> Parser<'a> {
/// second grammar (`dist`, `soft`, constraint `if`, `->`) that /// second grammar (`dist`, `soft`, constraint `if`, `->`) that
/// [`Parser::parse_constraint`] declines to model — so it gets exactly /// [`Parser::parse_constraint`] declines to model — so it gets exactly
/// the same treatment: skip to the matching brace and copy the bytes out. /// the same treatment: skip to the matching brace and copy the bytes out.
/// The `with` keyword itself is left outside the capture; the formatter /// The `with` keyword itself is left outside the capture — the caller has
/// writes it back. /// already consumed it, together with the comments written on either side
/// of it — and the formatter writes it back.
fn parse_with_constraint(&mut self) -> PResult<RawText> { fn parse_with_constraint(&mut self) -> PResult<RawText> {
self.expect_kw("with")?;
let start = self.here(); let start = self.here();
let col = self.cur().col; let col = self.cur().col;
self.expect_sym("{")?; self.expect_sym("{")?;
@@ -1677,27 +1687,22 @@ impl<'a> Parser<'a> {
} }
/// One `statement_or_null` of an action block, skipped verbatim: a /// One `statement_or_null` of an action block, skipped verbatim: a
/// `begin ... end` block, or everything through the next `;`. Brackets are /// `begin ... end` block, or everything through the next `;`.
/// skipped as units so a `;` written inside one cannot end the scan early. ///
/// Brackets *and* the block keywords ([`BLOCK_OPENERS`] /
/// [`BLOCK_CLOSERS`]) are skipped as units, so neither a `;` nor an `end`
/// written inside one ends the scan early: the pass statement of
/// `assert property (p) if (c) begin x = 1; end else y = 2;` is the whole
/// `if`, not `if (c) begin x = 1;`. A statement that ends with a block
/// ends *there* — no `;` follows one — unless an `else` continues it.
///
/// The scan never runs past the end of the file and never stands still:
/// every arm consumes at least one token, and `at_eof` is checked on every
/// turn, so unbalanced input is a clean parse error.
fn skip_action_stmt(&mut self) -> PResult<()> { fn skip_action_stmt(&mut self) -> PResult<()> {
if self.cur().is_kw("begin") { // How many block keywords are open. Zero means the scan is looking for
self.bump(); // the statement's own terminator.
let mut depth = 1usize; let mut depth = 0usize;
while depth > 0 {
if self.at_eof() {
return self.error("expected `end`");
}
let t = self.cur();
if t.is_kw("begin") {
depth += 1;
} else if t.is_kw("end") {
depth -= 1;
}
self.bump();
}
self.parse_label()?;
return Ok(());
}
loop { loop {
if self.at_eof() { if self.at_eof() {
return self.error("expected `;`"); return self.error("expected `;`");
@@ -1712,7 +1717,30 @@ impl<'a> Parser<'a> {
} else if t.is_sym("{") { } else if t.is_sym("{") {
self.bump(); self.bump();
self.skip_balanced("{", "}")?; self.skip_balanced("{", "}")?;
} else if self.eat_sym(";") { } else if (t.is_kw("disable") || t.is_kw("wait")) && self.nth(1).is_kw("fork") {
// `disable fork` / `wait fork` name the enclosing block; they
// do not open one.
self.bump();
self.bump();
} else if BLOCK_OPENERS.iter().any(|k| t.is_kw(k)) {
depth += 1;
self.bump();
} else if BLOCK_CLOSERS.iter().any(|k| t.is_kw(k)) {
if depth == 0 {
// A closer with nothing open: the action statement is
// missing its terminator and the scan has reached the end
// of the block the assertion itself sits in.
return self.error("expected `;`");
}
depth -= 1;
self.bump();
if depth == 0 {
self.parse_label()?;
if !self.eat_kw("else") {
return Ok(());
}
}
} else if depth == 0 && self.eat_sym(";") {
return Ok(()); return Ok(());
} else { } else {
self.bump(); self.bump();
@@ -2643,6 +2671,10 @@ impl<'a> Parser<'a> {
/// `bind <target> [: <inst>, ...] <module> [#(...)] <name> (...);` /// `bind <target> [: <inst>, ...] <module> [#(...)] <name> (...);`
fn parse_bind(&mut self) -> PResult<BindDirective> { fn parse_bind(&mut self) -> PResult<BindDirective> {
self.bump(); // `bind` self.bump(); // `bind`
// The target is a bare string, so a comment written before it has no
// node to attach to: harvest it here, where source order is still
// known, rather than letting it drift onto the instance below.
let target_comments = self.take_dangling();
let start = self.here(); let start = self.here();
let mut target = self.expect_ident()?; let mut target = self.expect_ident()?;
while self.cur().is_sym(".") { while self.cur().is_sym(".") {
@@ -2660,8 +2692,9 @@ impl<'a> Parser<'a> {
} }
} }
} }
let module_comments = self.take_dangling();
let inst = self.parse_instantiation()?; let inst = self.parse_instantiation()?;
Ok(BindDirective { target, target_span, instances, inst }) Ok(BindDirective { target, target_comments, target_span, instances, module_comments, inst })
} }
fn parse_instantiation(&mut self) -> PResult<Instantiation> { fn parse_instantiation(&mut self) -> PResult<Instantiation> {
@@ -4180,6 +4213,12 @@ impl<'a> Parser<'a> {
); );
} }
} else if t.is_sym("(") { } else if t.is_sym("(") {
// Comments written around the brackets have no element to
// attach to: before the `(`, and inside an empty `()`.
let mut comments = CallComments {
before_open: self.take_before_open("("),
..CallComments::default()
};
self.bump(); self.bump();
let mut args = Vec::new(); let mut args = Vec::new();
if !self.cur().is_sym(")") { if !self.cur().is_sym(")") {
@@ -4200,22 +4239,42 @@ impl<'a> Parser<'a> {
let first = let first =
ExprItem { meta, expr: first_expr, span: self.span_from(arg_start) }; ExprItem { meta, expr: first_expr, span: self.span_from(arg_start) };
args = self.parse_expr_list(first, ")")?; args = self.parse_expr_list(first, ")")?;
} else {
comments.dangling = self.take_dangling();
} }
self.expect_sym(")")?; self.expect_sym(")")?;
expr = self.expr_at(start, ExprKind::Call { callee: Box::new(expr), args }); expr = self.expr_at(
start,
ExprKind::Call { callee: Box::new(expr), args, comments: Box::new(comments) },
);
} else if t.is_kw("with") { } else if t.is_kw("with") {
let mut comments =
WithComments { before_kw: self.take_dangling(), ..WithComments::default() };
if self.nth(1).is_sym("{") { if self.nth(1).is_sym("{") {
self.expect_kw("with")?;
comments.after_kw = self.take_before_open("{");
let block = self.parse_with_constraint()?; let block = self.parse_with_constraint()?;
expr = self expr = self.expr_at(
.expr_at(start, ExprKind::WithConstraint { base: Box::new(expr), block }); start,
ExprKind::WithConstraint {
base: Box::new(expr),
block,
comments: Box::new(comments),
},
);
} else { } else {
self.bump(); // with self.bump(); // with
// `( expression )` — an ordinary parenthesized primary, comments.after_kw = self.take_before_open("(");
// which is what IEEE 1800 §7.12 spells here. // `( expression )` — an ordinary parenthesized primary,
// which is what IEEE 1800 §7.12 spells here.
let arg = self.parse_primary()?; let arg = self.parse_primary()?;
expr = self.expr_at( expr = self.expr_at(
start, start,
ExprKind::With { base: Box::new(expr), arg: Box::new(arg) }, ExprKind::With {
base: Box::new(expr),
arg: Box::new(arg),
comments: Box::new(comments),
},
); );
} }
} else if t.is_sym("'") && self.nth(1).is_sym("(") { } else if t.is_sym("'") && self.nth(1).is_sym("(") {
@@ -4530,6 +4589,12 @@ mod tests {
} }
} }
/// The texts of a comment slot, for the tests that pin where a comment
/// with no node of its own was attached.
fn texts(comments: &[Comment]) -> Vec<&str> {
comments.iter().map(|c| c.text.as_str()).collect()
}
/// The message of the parse error `src` must produce. /// The message of the parse error `src` must produce.
fn parse_err(src: &str) -> String { fn parse_err(src: &str) -> String {
let toks = tokenize(src).expect("lex error"); let toks = tokenize(src).expect("lex error");
@@ -4793,6 +4858,18 @@ mod tests {
assert_eq!(b.inst.instances[0].name, "u"); assert_eq!(b.inst.instances[0].name, "u");
} }
#[test]
fn the_comments_around_a_binds_head_are_kept() {
// QA round-1: the target is a bare string, so these two positions had
// no node to attach to and the comments drifted onto the instance.
let file = parse_ok("module m;\n bind /*c1*/ dut /*c2*/ chk u (.*);\nendmodule\n");
let ItemKind::Bind(b) = &module_of(&file).items[0].kind else {
panic!("expected a bind directive")
};
assert_eq!(texts(&b.target_comments), ["/*c1*/"]);
assert_eq!(texts(&b.module_comments), ["/*c2*/"]);
}
#[test] #[test]
fn bind_is_still_a_usable_identifier() { fn bind_is_still_a_usable_identifier() {
// `bind` is not in the lexer's keyword table, so a method called // `bind` is not in the lexer's keyword table, so a method called
@@ -5844,6 +5921,56 @@ mod tests {
assert!(matches!(items[1].kind, ItemKind::DataDecl(_)), "the next item was swallowed"); assert!(matches!(items[1].kind, ItemKind::DataDecl(_)), "the next item was swallowed");
} }
#[test]
fn an_action_block_keeps_a_nested_begin_end_whole() {
// QA round-1: the scan used to stop at the first `;` inside the
// nested block, leaving its `end` (and the `else`) behind.
let src = "module m;\n assert property (a |-> b)\n if (c) begin\n x = 1;\n end\n else y = 2;\n wire w;\nendmodule\n";
let f = parse_ok(src);
let items = &module_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") };
assert_eq!(
raw.text,
"assert property (a |-> b)\n if (c) begin\n x = 1;\n end\n else y = 2;"
);
assert!(matches!(items[1].kind, ItemKind::DataDecl(_)), "the next item was swallowed");
}
#[test]
fn an_action_block_may_be_a_fork_or_a_case() {
// `disable fork` / `wait fork` name the enclosing block rather than
// opening one, so neither may push the scan's block depth.
let fork = "fork\n x = 1;\n begin\n disable fork;\n wait fork;\n end\n join_none";
let case = "case (s)\n 1: x = 1;\n default: begin\n y = 2;\n end\n endcase";
for body in [fork, case] {
let src =
format!("module m;\n assert property (a)\n {body}\n wire w;\nendmodule\n");
let f = parse_ok(&src);
let items = &module_of(&f).items;
let ItemKind::Verbatim(raw) = &items[0].kind else {
panic!("expected a verbatim block for {body}")
};
assert_eq!(raw.text, format!("assert property (a)\n {body}"));
assert!(matches!(items[1].kind, ItemKind::DataDecl(_)), "the next item was swallowed");
}
}
#[test]
fn an_unbalanced_action_block_is_a_clean_error() {
// Never past the end of the file, never a loop.
assert_eq!(
parse_err(
"module m;\n assert property (a)\n if (c) begin\n x = 1;\nendmodule\n"
),
"expected `;` (found \"<eof>\")"
);
// A closer with nothing open ends the scan where it stands.
assert_eq!(
parse_err("module m;\n initial begin\n assert property (a)\n end\nendmodule\n"),
"expected `;` (found \"end\")"
);
}
#[test] #[test]
fn both_halves_of_an_action_block_are_captured() { fn both_halves_of_an_action_block_are_captured() {
let f = parse_ok( let f = parse_ok(
@@ -6510,7 +6637,7 @@ mod tests {
let StmtKind::Assign { rhs, .. } = &initial_stmts(&f)[0].kind else { let StmtKind::Assign { rhs, .. } = &initial_stmts(&f)[0].kind else {
panic!("expected an assignment") panic!("expected an assignment")
}; };
let ExprKind::WithConstraint { base, block } = &rhs.kind else { let ExprKind::WithConstraint { base, block, .. } = &rhs.kind else {
panic!("expected a with-constraint, got {:?}", rhs.kind) panic!("expected a with-constraint, got {:?}", rhs.kind)
}; };
// The `with` keyword is outside the capture; the braces are inside. // The `with` keyword is outside the capture; the braces are inside.
@@ -6526,13 +6653,46 @@ mod tests {
let StmtKind::Assign { rhs, .. } = &initial_stmts(&f)[0].kind else { let StmtKind::Assign { rhs, .. } = &initial_stmts(&f)[0].kind else {
panic!("expected an assignment") panic!("expected an assignment")
}; };
let ExprKind::With { base, arg } = &rhs.kind else { let ExprKind::With { base, arg, .. } = &rhs.kind else {
panic!("expected a with-expression, got {:?}", rhs.kind) panic!("expected a with-expression, got {:?}", rhs.kind)
}; };
assert!(matches!(base.kind, ExprKind::Call { .. })); assert!(matches!(base.kind, ExprKind::Call { .. }));
assert!(matches!(arg.kind, ExprKind::Paren { .. })); assert!(matches!(arg.kind, ExprKind::Paren { .. }));
} }
#[test]
fn the_comments_around_a_calls_brackets_and_a_with_are_kept() {
// QA round-1: four positions with no node of their own — before the
// `(`, inside an empty `()`, before `with`, and after it.
let f = parse_ok(
"module m;\n initial begin\n x = o.randomize /*c1*/ ( /*c2*/ ) /*c3*/ with /*c4*/ {\n y > 1;\n };\n end\nendmodule\n",
);
let StmtKind::Assign { rhs, .. } = &initial_stmts(&f)[0].kind else {
panic!("expected an assignment")
};
let ExprKind::WithConstraint { base, comments, .. } = &rhs.kind else {
panic!("expected a with-constraint, got {:?}", rhs.kind)
};
assert_eq!(texts(&comments.before_kw), ["/*c3*/"]);
assert_eq!(texts(&comments.after_kw), ["/*c4*/"]);
let ExprKind::Call { comments, .. } = &base.kind else { panic!("expected a call") };
assert_eq!(texts(&comments.before_open), ["/*c1*/"]);
assert_eq!(texts(&comments.dangling), ["/*c2*/"]);
}
#[test]
fn an_argument_carries_its_own_comments_and_the_call_carries_none() {
// A list with elements has somewhere to put them, so the call's own
// slots stay empty — two homes for one comment would print it twice.
let f = parse_ok("module m;\n initial begin\n f( /*c*/ a);\n end\nendmodule\n");
let StmtKind::ExprStmt(e) = &initial_stmts(&f)[0].kind else {
panic!("expected an expression statement, got {:?}", initial_stmts(&f)[0].kind)
};
let ExprKind::Call { args, comments, .. } = &e.kind else { panic!("expected a call") };
assert!(comments.is_empty(), "the call kept comments the argument owns");
assert_eq!(texts(&args[0].meta.leading), ["/*c*/"]);
}
#[test] #[test]
fn a_with_that_opens_neither_a_paren_nor_a_brace_is_not_a_postfix_segment() { fn a_with_that_opens_neither_a_paren_nor_a_brace_is_not_a_postfix_segment() {
// The stream expression's `with [range]` is still unsupported, and // The stream expression's `with [range]` is still unsupported, and
+3 -3
View File
@@ -847,11 +847,11 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) {
check_expr(src, expr, here); check_expr(src, expr, here);
} }
ExprKind::InsideMacro { lhs, .. } => check_expr(src, lhs, here), ExprKind::InsideMacro { lhs, .. } => check_expr(src, lhs, here),
ExprKind::With { base, arg } => { ExprKind::With { base, arg, .. } => {
check_expr(src, base, here); check_expr(src, base, here);
check_expr(src, arg, here); check_expr(src, arg, here);
} }
ExprKind::WithConstraint { base, block } => { ExprKind::WithConstraint { base, block, .. } => {
check_expr(src, base, here); check_expr(src, base, here);
assert_inside(src, "with constraint block", block.span, here); assert_inside(src, "with constraint block", block.span, here);
} }
@@ -868,7 +868,7 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) {
check_expr(src, then, here); check_expr(src, then, here);
check_expr(src, els, here); check_expr(src, els, here);
} }
ExprKind::Call { callee, args } => { ExprKind::Call { callee, args, .. } => {
check_expr(src, callee, here); check_expr(src, callee, here);
for a in args { for a in args {
assert_inside(src, "argument", a.span, here); assert_inside(src, "argument", a.span, here);
+2 -2
View File
@@ -1052,7 +1052,7 @@ impl<'a> Binder<'a> {
self.bind_expr(then, scope); self.bind_expr(then, scope);
self.bind_expr(els, scope); self.bind_expr(els, scope);
} }
ExprKind::Call { callee, args } => { ExprKind::Call { callee, args, .. } => {
self.bind_expr(callee, scope); self.bind_expr(callee, scope);
for a in args { for a in args {
self.bind_expr(&a.expr, scope); self.bind_expr(&a.expr, scope);
@@ -1113,7 +1113,7 @@ impl<'a> Binder<'a> {
} }
// The set is a macro invocation this crate makes no claims about. // The set is a macro invocation this crate makes no claims about.
ExprKind::InsideMacro { lhs, .. } => self.bind_expr(lhs, scope), ExprKind::InsideMacro { lhs, .. } => self.bind_expr(lhs, scope),
ExprKind::With { base, arg } => { ExprKind::With { base, arg, .. } => {
self.bind_expr(base, scope); self.bind_expr(base, scope);
self.bind_expr(arg, scope); self.bind_expr(arg, scope);
} }
+54
View File
@@ -165,6 +165,10 @@ the same two grammar rules and cost nothing:
workspace) all clean. workspace) all clean.
- [x] Idempotency swept by hand over all 712 passing corpus files, not just - [x] Idempotency swept by hand over all 712 passing corpus files, not just
the 13 new ones. the 13 new ones.
- [x] QA round-1: `skip_action_stmt` tracks `begin`/`end`, `fork`/`join*` and
`case`/`endcase` nesting, so an action block that is an `if` with a
`begin ... end` body (with or without `else`) is captured whole
(3 parser tests + 2 cases).
- [ ] **Not done, deliberately:** canonical layout for property/sequence - [ ] **Not done, deliberately:** canonical layout for property/sequence
expressions; `expect property`; `cover sequence`; `default clocking` / expressions; `expect property`; `cover sequence`; `default clocking` /
`default disable iff` (interface cluster's). `default disable iff` (interface cluster's).
@@ -278,6 +282,56 @@ Files changed:
- `README.md` — "Supported syntax" bullet, roadmap items 7/7b/8 - `README.md` — "Supported syntax" bullet, roadmap items 7/7b/8
- `docs/features/assertions/README.md` — this file - `docs/features/assertions/README.md` — this file
### 2026-08-21 — dev (response to QA round 1)
The round-1 finding below — `skip_action_stmt`'s generic branch tracking
brackets but not `begin`/`end`, so an action block like `if (c) begin x = 1;
end else y = 2;` ended at the first `;` *inside* the nested block — is fixed.
`skip_action_stmt` is now one loop with a block-keyword depth counter beside
the bracket skipping. It counts the openers `BLOCK_OPENERS` (`begin`, `fork`,
`case`/`casex`/`casez`/`randcase`) against the closers `BLOCK_CLOSERS`
(`end`, `join`/`join_any`/`join_none`, `endcase`), and:
- a `;` ends the statement only at depth 0, so a `;` inside a nested block no
longer ends the scan;
- a statement that *ends* with a block ends there — no `;` follows one — and
the scan then reads the optional `end : label` and continues only if an
`else` follows, which is what makes the `if`/`else` shape whole;
- `disable fork` / `wait fork` are matched as a pair and skipped: they name
the enclosing block rather than opening one, and counting them would have
broken the very common UVM `fork ... join_none` + `disable fork` action
block;
- a closer at depth 0 (nothing open) is a clean `expected ';'` error where it
stands, which is both a better position than the old run-to-EOF and the
reason the counter can never underflow.
The termination argument the QA log asked about still holds and is now in the
doc comment: `at_eof` is checked on every turn and every arm consumes at
least one token, so unbalanced input is a clean parse error, never a loop and
never a read past the end of the file. Both directions are pinned by
`an_unbalanced_action_block_is_a_clean_error`.
Tests: three parser tests (`an_action_block_keeps_a_nested_begin_end_whole`,
`an_action_block_may_be_a_fork_or_a_case`,
`an_unbalanced_action_block_is_a_clean_error`) and two cases in
`assertions.cases` (the `if`/`begin`/`end`/`else` shape and a
`fork ... join_none` with `disable fork` inside), each with a following item
asserted to survive so a future over-greedy scan is caught.
The old special case that required the pass statement's *first* token to be
`begin` is gone — it is now just depth 1 on the first token — so the previous
begin-block behaviour is unchanged, `begin`-first or not.
Score unchanged before and after
(`{"passing":800,"total":820,"pct":97.6,...}`), passing set identical, all
800 passing files byte-identical against the pre-change binary, two-pass
idempotency sweep clean.
Files changed: `crates/vlog_parser/src/parser.rs` (`skip_action_stmt`, the
two new consts, 3 tests), `crates/vlog_formatter/tests/cases/assertions.cases`
(2 cases).
## QA log ## QA log
### 2026-08-21 — round-1 adversarial QA ### 2026-08-21 — round-1 adversarial QA
+51
View File
@@ -105,6 +105,11 @@ instantiation too (`bind.cases`, "implicit named *parameter* overrides").
### Promised / requested ### Promised / requested
- **`BindDirective::target_comments` / `::module_comments`** (QA round-1 fix):
the comments written between `bind` and the target, and between the target
(or the `: instance, list`) and the module name. Both are plain
`Vec<Comment>` fields, so no consumer had to change; only `Fmt::bind`
reads them.
- **New AST variant `ItemKind::Bind(BindDirective)`** in - **New AST variant `ItemKind::Bind(BindDirective)`** in
`crates/vlog_parser/src/ast.rs`. Two exhaustive matches in other crates `crates/vlog_parser/src/ast.rs`. Two exhaustive matches in other crates
needed an arm; both got the minimal one: needed an arm; both got the minimal one:
@@ -149,6 +154,11 @@ instantiation too (`bind.cases`, "implicit named *parameter* overrides").
- [x] `cargo fmt --all`, `cargo clippy --all-targets`, `cargo test` all clean. - [x] `cargo fmt --all`, `cargo clippy --all-targets`, `cargo test` all clean.
- [x] Score after: 699/820 (85.2%), passing set a strict superset. - [x] Score after: 699/820 (85.2%), passing set a strict superset.
- [x] `TODO.md` and `README.md` updated. - [x] `TODO.md` and `README.md` updated.
- [x] QA round-1: comments between `bind` and the target, and before the
module name, are preserved (2 cases + 1 parser test).
- [ ] A comment written *inside* the `: instance, list` is still a clean
exit-2 refusal — `instances: Vec<Name>` has no `Meta` and no corpus
file writes one. See the 2026-08-21 work log entry.
## Work log ## Work log
@@ -196,6 +206,47 @@ instantiation too (`bind.cases`, "implicit named *parameter* overrides").
from `counter_properties.sv:96`), so nothing in this category is left over; from `counter_properties.sv:96`), so nothing in this category is left over;
those files belong to the `assertions` owner. those files belong to the `assertions` owner.
### 2026-08-21 — dev (response to QA round 1)
The round-1 finding below (a comment between `bind` and its target is dropped
internally and the file becomes unformattable) is fixed, together with its
sibling position (between the target — or the `: instance, list` — and the
module name of the instantiation).
Both positions sit between two tokens that no node owns: the target is a bare
`String`, so a comment written there had nowhere to attach and drifted onto
the instance below, which moves it across tokens and `verify_equivalence`
rightly refused the output. `BindDirective` now carries `target_comments` and
`module_comments`, harvested in `parse_bind` with the same `take_dangling`
the rest of the parser uses, and `Fmt::bind` prints each back where it was
written (`Fmt::inline_comments_spaced`, so a *line* comment ends its line and
the target starts the next one). Both round-trip and are idempotent; two
cases in `bind.cases` pin them, plus a parser test
(`the_comments_around_a_binds_head_are_kept`).
The QA note's "same class of gap ... after the module name / before the
instance name" turned out **not** to reproduce: `checker_mod /*c3*/ c_inst
/*c4*/ (.clk(clk));` already round-trips, because those two positions are the
instance's `meta.leading` and `conn_comments`, which `parse_instantiation`
has always harvested.
**Still refused, deliberately:** a comment written *inside* the `: instance,
list` (`bind dut : /*x*/ u_a chk u (.*);`). `instances: Vec<Name>` has no
`Meta`, and giving one to a list nothing else needs — no corpus file writes a
comment there — is the abstraction-for-a-second-user-that-does-not-exist the
project rules forbid. It stays a clean exit-2 refusal with the input
untouched, not corruption.
Score unchanged before and after
(`{"passing":800,"total":820,"pct":97.6,...}`), passing set identical, and
all 800 passing corpus files format to byte-identical output against the
pre-change binary; the two-pass idempotency sweep over them is clean.
Files changed: `crates/vlog_parser/src/ast.rs` (two fields on
`BindDirective`), `crates/vlog_parser/src/parser.rs` (`parse_bind` + 1 test),
`crates/vlog_formatter/src/format.rs` (`Fmt::bind`),
`crates/vlog_formatter/tests/cases/bind.cases` (2 cases).
## QA log ## QA log
### 2026-08-21 — round-1 adversarial QA ### 2026-08-21 — round-1 adversarial QA
+79 -3
View File
@@ -129,9 +129,21 @@ its input bytes exactly is trivially token-equivalent.
- **`Doc::Inline(String)`** (`vlog_formatter::doc`): verbatim text spliced - **`Doc::Inline(String)`** (`vlog_formatter::doc`): verbatim text spliced
into the *middle* of a line, newlines and all. Unlike `Doc::Verbatim` it into the *middle* of a line, newlines and all. Unlike `Doc::Verbatim` it
does not force enclosing groups to break, and unlike `Doc::Text` the does not force enclosing groups to break, and unlike `Doc::Text` the
printer measures it correctly (`fits` charges only its first line, `print` printer measures it correctly: `fits` charges its first line against the
resumes measuring from its last). `align::flat_width` returns `None` for it, current width and then goes on measuring the rest of the group from the
as it does for the other break-carrying docs. width of its *last* line, which is where `print` resumes (QA round-1 fix —
the first version stopped measuring at the first line and let an
overflowing tail through). `align::flat_width` returns `None` for it, as it
does for the other break-carrying docs.
- **Comment slots on three `ExprKind` variants** (QA round-1 fix):
`Call { comments: Box<CallComments> }` (before the `(`, and inside an empty
`()`), `With`/`WithConstraint { comments: Box<WithComments> }` (before
`with`, and between `with` and the `(` / `{`). Every consumer matched these
variants with named fields; `vlog_semantic::bind` and
`vlog_parser/tests/spans.rs` got a `..` in the pattern and nothing else.
The comments live outside the nodes' code extents, so no span invariant
changes.
- **`token::is_keyword` gained `randcase` and `let`** — a lexer-level change - **`token::is_keyword` gained `randcase` and `let`** — a lexer-level change
shared with the `lexer-cleanup` feature. See Assumptions. shared with the `lexer-cleanup` feature. See Assumptions.
@@ -190,6 +202,13 @@ another feature's region, so they are written here rather than made:
- [x] 30 formatter cases in `crates/vlog_formatter/tests/cases/dv_statements.cases`, - [x] 30 formatter cases in `crates/vlog_formatter/tests/cases/dv_statements.cases`,
14 parser unit tests, 1 linter case, 2 new span-invariant sources 14 parser unit tests, 1 linter case, 2 new span-invariant sources
- [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test` clean - [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test` clean
- [x] QA round-1: `fits()` keeps measuring past a multi-line `Doc::Inline`,
from its last line's width
- [x] QA round-1: comments before a call's `(`, inside an empty `()`, and on
either side of a postfix `with`
- [ ] comment between an expression statement and its `;` — not a `with`
gap (`y = a + 1 /*c*/;` refuses the same way); needs a slot on the
statement, and is the shape TODO.md already parks
- [ ] `let` at *statement* position (a block item declaration, §11.12) — no - [ ] `let` at *statement* position (a block item declaration, §11.12) — no
corpus file writes one; it is an "unsupported statement starting with corpus file writes one; it is an "unsupported statement starting with
keyword `let`" error keyword `let`" error
@@ -296,6 +315,63 @@ Files changed:
- `crates/vlog_linter/tests/cases/case_missing_default.lint` — randcase case - `crates/vlog_linter/tests/cases/case_missing_default.lint` — randcase case
- `README.md`, `TODO.md` - `README.md`, `TODO.md`
### 2026-08-21 — dev (response to QA round 1)
Two of the round-1 findings in the QA log below were this cluster's; both are
fixed. Score unchanged at `{"passing":800,"total":820,"pct":97.6,...}` before
and after, with the passing set identical (`comm` both ways empty) and — the
stronger check for a printer change — **every one of the 800 files formats to
exactly the same bytes as the pre-change binary** (built from `HEAD` in a
scratch tree and diffed file by file). The 800-file two-pass idempotency
sweep is clean.
- **`fits()` vs a multi-line `Doc::Inline` (printer.rs).** Confirmed exactly
as reported: `fits` returned on the Inline's first line, so a group whose
tail continued on the block's *last* line was judged to fit however long
that tail was. `fits` now charges the first line, refuses the group if that
line alone overflows, then **resets the remaining width to
`max_width - <last line's width>` and keeps measuring** the rest of the
group — which is precisely what `print` does when it resumes. The QA repro
now wraps at `--line-length 40`, and the control case (a short tail after
the same block) still comes out flat. Two printer unit tests pin both
directions (`group_stays_flat_when_the_tail_after_an_inline_fits`,
`group_breaks_when_the_tail_after_an_inline_overflows`) and two
`dv_statements.cases` entries pin it end to end at the default 100 columns
(`cases.rs` has no per-case config knob — every case runs on
`Config::default()` — so the cases are built to overflow at 100).
- **`align::flat_width` was checked and deliberately left alone.** It answers
`None` for *any* `Doc::Inline`, which makes the row unalignable; `row_of`
turns that into `None`, and `align_groups` treats a `None` row as a group
boundary whose plan stays `None`, so the row prints flush. That is
conservative but correct in the direction that matters (no row is ever
padded from a width nobody measured). The only pessimism is a *single-line*
Inline, which does have an honest flat width; no corpus file writes one
inside an alignable row, so under "simplicity first" it stays as it is
rather than growing a special case with no user.
- **Comments at the `randomize()`/`with` boundaries.** Four positions had no
node to attach to and so were rejected by the safety net: before a call's
`(`, inside an empty `()`, before `with`, and between `with` and the `(` /
`{`. `ExprKind::Call` gained `comments: Box<CallComments>` and both `with`
forms gained `comments: Box<WithComments>` — boxed for the reason
`TernaryComments` already gives — harvested with the existing
`take_before_open` / `take_dangling` helpers and printed back between the
same two tokens by `Fmt::with_head` and the `Call` arm. An argument list
with elements keeps carrying its own comments (a second home would print
one comment twice); a parser test pins that too.
- **Still refused, deliberately:** a comment between an expression statement
and its `;` (`y = x.randomize() with {a == 1;} /*c*/;`). It is not a
`with`-specific gap at all — `y = a + 1 /*c*/;` refuses identically — and
placing it needs a slot on the *statement*, not on `Expr`. It is the shape
TODO.md already parks as "a comment before a procedural statement's `;`".
Files changed: `crates/vlog_formatter/src/printer.rs` (the `fits` arm + 2
tests), `crates/vlog_parser/src/ast.rs` (`CallComments`, `WithComments`, the
three new fields), `crates/vlog_parser/src/parser.rs` (harvest points,
`parse_with_constraint` no longer eats its own `with`, 2 tests),
`crates/vlog_formatter/src/format.rs` (`with_head`, the `Call` arm),
`crates/vlog_semantic/src/bind.rs` + `crates/vlog_parser/tests/spans.rs`
(`..` in the three patterns), `tests/cases/dv_statements.cases` (3 cases).
## QA log ## QA log
### 2026-08-21 — round-1 adversarial QA ### 2026-08-21 — round-1 adversarial QA