Fix the four corpus-found formatter bugs: 46 verification errors -> 0

Every fix makes the AST carry a fact the formatter used to invent or
discard: SensSep preserves each event-list separator as written
(, stays , / or stays or, mixed lists round-trip); module-header
imports keep one statement per import; Instantiation::params and
Module::param_ports become Option<Vec> so empty #() survives; and
seven distinct comment-motion shapes (closing paren, empty
connection, declarator-to-;, after binary operator, case labels,
ternary, assign-to-value) keep comments where the source put them,
with Fmt::inline_comments as the single comment-run printer.

verify.rs is byte-identical: the net was right on all 46 refusing
files. Seven new rejection tests pin that judgment (sabotage-checked
by QA). Also removes a latent split_off underflow panic
(Parser::take_around) that QA reproduced on the pre-fix binary, and
fixes the ternary comment refusal from the earlier bug round.

Corpus after: 468/820 parse, 0 verification errors, 0 crashes —
corpus_check.sh exits 0 for the first time. Exactly 46 files moved
verification-error -> would-reformat by path diff; nothing else
changed. 111 workspace tests (was 98), case table 237 entries,
clippy silent.

Dev: Opus agent; QA: Sonnet agent (all claims independently
reproduced); review in docs/features/corpus-bugs/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-19 04:07:58 -07:00
1 parent 3325905f21
commit dc2181e1a2
9 files changed
+1531 -141

No files matched your search

+85 -12
View File
@@ -99,9 +99,19 @@ pub enum ItemKind {
pub struct Module {
pub kw: String,
pub name: String,
pub imports: Vec<String>,
pub param_ports: Vec<ParamPort>,
/// One entry per `import` statement written in the header, each holding
/// that statement's comma-separated paths. A header may write several
/// (`module m import a::*; import b::t; (...)`), and merging them into one
/// statement would replace a `;` with a `,`.
pub imports: Vec<Vec<String>>,
/// `None` when the header wrote no `#( ... )` at all; an empty `Some` is a
/// written-but-empty `#()`, which must be printed back.
pub param_ports: Option<Vec<ParamPort>>,
/// Comments written after the last parameter port and before the `)`.
pub param_dangling: Vec<Comment>,
pub ports: PortList,
/// Comments written after the last port and before the `)`.
pub port_dangling: Vec<Comment>,
pub items: Vec<Item>,
pub dangling: Vec<Comment>,
pub end_label: Option<String>,
@@ -265,6 +275,9 @@ pub struct AssignPair {
pub meta: Meta,
pub lhs: Expr,
pub rhs: Expr,
/// Comments written between the `=` and the right-hand side. Kept here so
/// they print on the `=`'s side of the value instead of drifting into it.
pub rhs_comments: Vec<Comment>,
}
#[derive(Debug)]
@@ -282,14 +295,30 @@ pub enum SensList {
#[derive(Debug)]
pub struct SensItem {
/// The separator written before this item; `None` on the first item.
pub sep: Option<SensSep>,
pub edge: Option<String>,
pub expr: Expr,
}
/// How two event-list items were separated in the source. Both spellings are
/// legal and mean the same thing, but rewriting one as the other changes the
/// token stream, so the formatter reproduces whichever was written.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SensSep {
/// `@(posedge clk, negedge rst_n)`
Comma,
/// `@(posedge clk or negedge rst_n)`
Or,
}
#[derive(Debug)]
pub struct Instantiation {
pub module: String,
pub params: Vec<Connection>,
/// The parameter override list, `None` when the source wrote no `#(...)`
/// at all. An empty `Some` is a written-but-empty `#()`, which must be
/// printed back: dropping it would lose two tokens.
pub params: Option<Vec<Connection>>,
pub instances: Vec<Instance>,
}
@@ -370,8 +399,9 @@ pub struct GenCase {
#[derive(Debug)]
pub struct GenCaseItem {
pub meta: Meta,
/// Empty means `default`.
pub labels: Vec<Expr>,
/// Empty means `default`. Each label carries the comments written around
/// it, so a comment between two labels stays between them.
pub labels: Vec<ExprItem>,
pub body: GenBlock,
}
@@ -545,8 +575,9 @@ pub enum TimingControl {
#[derive(Debug)]
pub struct CaseItem {
pub meta: Meta,
/// Empty means `default`.
pub labels: Vec<Expr>,
/// Empty means `default`. Each label carries the comments written around
/// it, so a comment between two labels stays between them.
pub labels: Vec<ExprItem>,
pub stmt: Stmt,
}
@@ -575,8 +606,9 @@ pub enum Expr {
Ident(String),
Number(String),
Str(String),
/// Explicitly empty (used for `.port()` connections).
Empty,
/// Explicitly empty (used for `.port()` connections), carrying any
/// comments written between the parens so they stay inside them.
Empty(Vec<Comment>),
Unary {
op: String,
expr: Box<Expr>,
@@ -585,14 +617,16 @@ pub enum Expr {
lhs: Box<Expr>,
op: String,
rhs: Box<Expr>,
/// Comments written between the left operand and the operator. They
/// force the chain to break, with the operator starting the new line.
comments: Vec<Comment>,
/// Boxed to keep `Expr` small, as for `TernaryComments`.
comments: Box<BinaryComments>,
},
Ternary {
cond: Box<Expr>,
then: Box<Expr>,
els: Box<Expr>,
/// Boxed to keep `Expr` small: a ternary with comments in it is rare,
/// but every `Expr` would otherwise carry four empty vectors.
comments: Box<TernaryComments>,
},
Call {
callee: Box<Expr>,
@@ -658,6 +692,45 @@ pub enum Expr {
},
}
/// Comments written next to a binary operator. Kept per side so neither
/// drifts across the operator: `a && // why` and `a // why` + `&& b` are
/// different token streams.
#[derive(Debug, Clone, Default)]
pub struct BinaryComments {
/// Between the left operand and the operator. These force the chain to
/// break, with the operator starting the new line.
pub before: Vec<Comment>,
/// Between the operator and the right operand. These force the chain to
/// break, with the right operand starting the new line.
pub after: Vec<Comment>,
}
/// Comments written inside a `cond ? then : els`, kept per position so the
/// formatter prints each back between the same two tokens it was written
/// between. Anywhere else they would drift across `?` or `:`.
#[derive(Debug, Clone, Default)]
pub struct TernaryComments {
/// Between the condition and `?`.
pub before_question: Vec<Comment>,
/// Between `?` and the then-branch.
pub after_question: Vec<Comment>,
/// Between the then-branch and `:`.
pub before_colon: Vec<Comment>,
/// Between `:` and the else-branch.
pub after_colon: Vec<Comment>,
}
impl TernaryComments {
/// True when nothing was written inside the `? :` — the common case, laid
/// out without any comment handling.
pub fn is_empty(&self) -> bool {
self.before_question.is_empty()
&& self.after_question.is_empty()
&& self.before_colon.is_empty()
&& self.after_colon.is_empty()
}
}
#[derive(Debug, Clone)]
pub struct PatternItem {
pub meta: Meta,
+195 -40
View File
@@ -341,6 +341,21 @@ impl Parser {
std::mem::take(&mut self.tokens[self.pos].leading)
}
/// Every comment written in the gap that ends at the cursor: the ones
/// trailing the tokens consumed since `mark`, then the ones sitting on
/// their own lines before the current token. Used where a construct must
/// keep a comment on a specific side of an operator it is about to
/// consume.
///
/// `mark` is clamped: a nested construct may have harvested the pending
/// comments already, leaving fewer than there were when `mark` was taken.
fn take_around(&mut self, mark: usize) -> Vec<Comment> {
let at = mark.min(self.pending_trailing.len());
let mut out = self.pending_trailing.split_off(at);
out.append(&mut self.take_leading_here());
out
}
/// Same for the comment written *after* the current token on its line.
fn take_trailing_here(&mut self) -> Vec<Comment> {
match self.tokens[self.pos].trailing.take() {
@@ -596,28 +611,32 @@ impl Parser {
let name = self.expect_ident()?;
let mut imports = Vec::new();
while self.cur().is_kw("import") {
imports.extend(self.parse_import_list()?);
imports.push(self.parse_import_list()?);
}
let mut param_ports = Vec::new();
let mut param_ports = None;
let mut param_dangling = Vec::new();
if self.cur().is_sym("#") {
self.bump();
self.expect_sym("(")?;
let mut list = Vec::new();
if !self.cur().is_sym(")") {
loop {
param_ports.push(self.parse_param_port()?);
list.push(self.parse_param_port()?);
if !self.eat_sym(",") {
break;
}
if let Some(last) = param_ports.last_mut() {
if let Some(last) = list.last_mut() {
if last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
}
}
}
param_dangling = self.take_dangling();
self.expect_sym(")")?;
param_ports = Some(list);
}
let ports = self.parse_port_list()?;
let (ports, port_dangling) = self.parse_port_list()?;
self.expect_sym(";")?;
let mut items = Vec::new();
while !self.cur().is_kw("endmodule") && !self.at_eof() {
@@ -626,7 +645,18 @@ impl Parser {
let dangling = self.take_dangling();
self.expect_kw("endmodule")?;
let end_label = self.parse_end_label()?;
Ok(Module { kw, name, imports, param_ports, ports, items, dangling, end_label })
Ok(Module {
kw,
name,
imports,
param_ports,
param_dangling,
ports,
port_dangling,
items,
dangling,
end_label,
})
}
fn parse_param_port(&mut self) -> PResult<ParamPort> {
@@ -658,14 +688,17 @@ impl Parser {
Ok(ParamPort { meta, kw, ty, is_type: false, name, unpacked, default })
}
fn parse_port_list(&mut self) -> PResult<PortList> {
/// The header port list plus the comments written before its closing `)`.
fn parse_port_list(&mut self) -> PResult<(PortList, Vec<Comment>)> {
if !self.cur().is_sym("(") {
return Ok(PortList::None);
return Ok((PortList::None, Vec::new()));
}
self.bump();
if self.cur().is_sym(")") {
// `module m (/* c */);` — the comments stay between the parens.
let dangling = self.take_dangling();
self.bump();
return Ok(PortList::Empty);
return Ok((PortList::Empty, dangling));
}
let ansi = {
let t = self.cur();
@@ -689,6 +722,8 @@ impl Parser {
}
}
}
// Comments on their own lines before the `)` belong inside it.
let dangling = self.take_dangling();
self.expect_sym(")")?;
// A trailing comment on the closing line belongs to the last port.
if let Some(last) = ports.last_mut() {
@@ -696,7 +731,7 @@ impl Parser {
last.meta.trailing = self.take_trailing();
}
}
Ok(PortList::Ansi(ports))
Ok((PortList::Ansi(ports), dangling))
} else {
let mut ports = Vec::new();
loop {
@@ -709,8 +744,9 @@ impl Parser {
break;
}
}
let dangling = self.take_dangling();
self.expect_sym(")")?;
Ok(PortList::NonAnsi(ports))
Ok((PortList::NonAnsi(ports), dangling))
}
}
@@ -824,9 +860,11 @@ impl Parser {
let unpacked = self.parse_dims()?;
let init = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None };
let more = self.eat_sym(",");
if more {
meta.trailing = self.take_trailing();
}
// Harvested on the last declarator too: a comment written before
// the `;` (`logic x /* verilator split_var */;`) belongs to the
// declaration, and the `;` has not been consumed yet, so nothing
// written after it can be picked up here.
meta.trailing = self.take_trailing();
out.push(Declarator { meta, name, unpacked, init });
if !more {
break;
@@ -970,13 +1008,15 @@ impl Parser {
loop {
let mut meta = self.take_meta();
let lhs = self.parse_unary()?;
let mark = self.pending_trailing.len();
self.expect_sym("=")?;
let rhs_comments = self.take_around(mark);
let rhs = self.parse_expr()?;
let more = self.eat_sym(",");
if more {
meta.trailing = self.take_trailing();
}
assigns.push(AssignPair { meta, lhs, rhs });
assigns.push(AssignPair { meta, lhs, rhs, rhs_comments });
if !more {
break;
}
@@ -1011,17 +1051,18 @@ impl Parser {
module.push_str("::");
module.push_str(&self.expect_ident()?);
}
let mut params = Vec::new();
let mut params = None;
if self.cur().is_sym("#") {
self.bump();
self.expect_sym("(")?;
let mut list = Vec::new();
if !self.cur().is_sym(")") {
loop {
params.push(self.parse_connection()?);
list.push(self.parse_connection()?);
if !self.eat_sym(",") {
break;
}
if let Some(last) = params.last_mut() {
if let Some(last) = list.last_mut() {
if last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
@@ -1029,6 +1070,7 @@ impl Parser {
}
}
self.expect_sym(")")?;
params = Some(list);
}
let mut instances = Vec::new();
loop {
@@ -1107,9 +1149,14 @@ impl Parser {
return Ok(Connection { meta, name: "*".to_string(), expr: None });
}
let name = self.expect_ident()?;
let mark = self.pending_trailing.len();
let expr = if self.eat_sym("(") {
if self.eat_sym(")") {
Some(Expr::Empty)
if self.cur().is_sym(")") {
// `.name(/* unused */)`: the comments were written inside
// these parens and are printed back inside them.
let inside = self.take_around(mark);
self.bump();
Some(Expr::Empty(inside))
} else {
let e = self.parse_expr_or_type()?;
self.expect_sym(")")?;
@@ -1238,10 +1285,8 @@ impl Parser {
let _ = self.eat_sym(":");
Vec::new()
} else {
let mut labels = vec![self.parse_expr()?];
while self.eat_sym(",") {
labels.push(self.parse_expr()?);
}
let first = self.parse_expr_item()?;
let labels = self.parse_expr_list(first)?;
self.expect_sym(":")?;
labels
};
@@ -1688,10 +1733,8 @@ impl Parser {
let _ = self.eat_sym(":");
Vec::new()
} else {
let mut labels = vec![self.parse_expr()?];
while self.eat_sym(",") {
labels.push(self.parse_expr()?);
}
let first = self.parse_expr_item()?;
let labels = self.parse_expr_list(first)?;
self.expect_sym(":")?;
labels
};
@@ -1766,7 +1809,11 @@ impl Parser {
if self.cur().kind == TokenKind::Ident {
// `@ident` without parens.
let name = self.expect_ident()?;
return Ok(SensList::List(vec![SensItem { edge: None, expr: Expr::Ident(name) }]));
return Ok(SensList::List(vec![SensItem {
sep: None,
edge: None,
expr: Expr::Ident(name),
}]));
}
if self.cur().is_sym("(") && self.nth(1).is_sym("*") {
// `@( /* c */ * /* d */ )`: the comments belong to the star, not
@@ -1782,6 +1829,7 @@ impl Parser {
}
self.expect_sym("(")?;
let mut items = Vec::new();
let mut sep = None;
loop {
let edge = {
let t = self.cur();
@@ -1792,11 +1840,16 @@ impl Parser {
}
};
let expr = self.parse_expr()?;
items.push(SensItem { edge, expr });
if self.eat_sym(",") || self.eat_kw("or") {
continue;
}
break;
items.push(SensItem { sep, edge, expr });
// Both separators are legal in the same list; each is kept as
// written so the formatter never rewrites one as the other.
sep = if self.eat_sym(",") {
Some(SensSep::Comma)
} else if self.eat_kw("or") {
Some(SensSep::Or)
} else {
break;
};
}
self.expect_sym(")")?;
Ok(SensList::List(items))
@@ -1821,13 +1874,30 @@ impl Parser {
}
fn parse_ternary_inner(&mut self) -> PResult<Expr> {
let mark = self.pending_trailing.len();
let cond = self.parse_binary(1)?;
if self.cur().is_sym("?") {
// Each of the four gaps inside a `? :` can hold comments; kept
// apart so none of them drifts across the `?` or the `:`.
let before_question = self.take_around(mark);
self.bump();
let after_question = self.take_around(mark);
let then = self.parse_expr()?;
let before_colon = self.take_around(mark);
self.expect_sym(":")?;
let after_colon = self.take_around(mark);
let els = self.parse_ternary()?;
Ok(Expr::Ternary { cond: Box::new(cond), then: Box::new(then), els: Box::new(els) })
Ok(Expr::Ternary {
cond: Box::new(cond),
then: Box::new(then),
els: Box::new(els),
comments: Box::new(TernaryComments {
before_question,
after_question,
before_colon,
after_colon,
}),
})
} else {
Ok(cond)
}
@@ -1912,12 +1982,19 @@ impl Parser {
}
// Comments between the operand and the operator belong to this
// node; left where they are they would drift past the operator.
let mut comments = self.pending_trailing.split_off(mark);
comments.append(&mut self.take_leading_here());
let before = self.take_around(mark);
let op = self.bump().text;
// Comments between the operator and the right operand belong here
// too; left where they are they would drift past the operand.
let after = self.take_around(mark);
let rhs = self.parse_binary(prec + 1)?;
self.link()?;
lhs = Expr::Binary { lhs: Box::new(lhs), op, rhs: Box::new(rhs), comments };
lhs = Expr::Binary {
lhs: Box::new(lhs),
op,
rhs: Box::new(rhs),
comments: Box::new(BinaryComments { before, after }),
};
}
Ok(lhs)
}
@@ -2082,8 +2159,7 @@ impl Parser {
} else {
inner
};
let mut after = self.pending_trailing.split_off(mark);
after.append(&mut self.take_leading_here());
let after = self.take_around(mark);
self.expect_sym(")")?;
Ok(Expr::Paren { inner: Box::new(inner), before, after })
}
@@ -2505,4 +2581,83 @@ mod tests {
.collect();
assert_eq!(semis, [false, true]);
}
#[test]
fn event_list_separators_are_recorded_as_written() {
let file =
parse_ok("module m;\nalways @(posedge clk, negedge rst_n or a, b) q <= d;\nendmodule");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let ItemKind::Always { stmt, .. } = &m.items[0].kind else { panic!("expected an always") };
let StmtKind::Timing { control: TimingControl::Event(SensList::List(items)), .. } =
&stmt.kind
else {
panic!("expected an event control")
};
let seps: Vec<Option<SensSep>> = items.iter().map(|i| i.sep).collect();
assert_eq!(
seps,
[None, Some(SensSep::Comma), Some(SensSep::Or), Some(SensSep::Comma)],
"each separator must be kept as written"
);
}
#[test]
fn header_imports_stay_separate_statements() {
let file =
parse_ok("module m\n import a::*;\n import b::t, c::u;\n(input clk);\nendmodule");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
assert_eq!(m.imports, vec![vec!["a::*".to_string()], vec!["b::t".into(), "c::u".into()]]);
}
#[test]
fn a_written_empty_parameter_list_is_distinguishable_from_none() {
let file = parse_ok("module m;\n sub #() u0 (.a(x));\n sub u1 (.a(x));\nendmodule");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let params: Vec<bool> = m
.items
.iter()
.map(|i| match &i.kind {
ItemKind::Instantiation(inst) => inst.params.is_some(),
other => panic!("expected an instantiation, got {other:?}"),
})
.collect();
assert_eq!(params, [true, false], "`#()` is Some(empty), no `#(...)` is None");
}
#[test]
fn comments_before_a_closing_paren_stay_with_their_list() {
let file = parse_ok(
"module m #(\n parameter int W = 8\n /* lint_on */\n) (\n input a\n // tail\n);\nendmodule",
);
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
assert_eq!(m.param_dangling.len(), 1, "the pragma belongs inside `#( ... )`");
assert_eq!(m.port_dangling.len(), 1, "the comment belongs inside the port list");
}
#[test]
fn comments_around_a_ternary_are_kept_per_position() {
let file =
parse_ok("module m;\nassign y = c /* a */ ? /* b */ x /* c */ : /* d */ z;\nendmodule");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let ItemKind::ContAssign(a) = &m.items[0].kind else { panic!("expected an assign") };
let Expr::Ternary { comments, .. } = &a.assigns[0].rhs else {
panic!("expected a ternary")
};
assert_eq!(comments.before_question.len(), 1);
assert_eq!(comments.after_question.len(), 1);
assert_eq!(comments.before_colon.len(), 1);
assert_eq!(comments.after_colon.len(), 1);
}
#[test]
fn comments_on_both_sides_of_a_binary_operator_are_kept_apart() {
let file = parse_ok("module m;\nassign y = a /* pre */ && /* post */ b;\nendmodule");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let ItemKind::ContAssign(a) = &m.items[0].kind else { panic!("expected an assign") };
let Expr::Binary { comments, .. } = &a.assigns[0].rhs else {
panic!("expected a binary expression")
};
assert_eq!(comments.before.len(), 1, "one comment before the operator");
assert_eq!(comments.after.len(), 1, "one comment after the operator");
}
}