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:
1 parent
3325905f21
commit
dc2181e1a2
9 files changed
+1531
-141
No files matched your search
@@ -88,6 +88,14 @@ struct Fmt<'a> {
|
||||
_cfg: &'a Config,
|
||||
}
|
||||
|
||||
/// One operator of a flattened binary chain, with the comments written on
|
||||
/// either side of it.
|
||||
struct BinaryOp<'e> {
|
||||
op: &'e str,
|
||||
before: &'e [Comment],
|
||||
after: &'e [Comment],
|
||||
}
|
||||
|
||||
/// A list element ready for comma-list layout. Blank lines between elements
|
||||
/// are deliberately dropped, so only the comments ride along.
|
||||
struct ListItem {
|
||||
@@ -200,6 +208,23 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Append comments written between two tokens of an expression, each
|
||||
/// spaced off what precedes it. A line comment runs to end of line, so
|
||||
/// anything after it starts a new one — including the next comment, which
|
||||
/// would otherwise be swallowed into the first one's text.
|
||||
///
|
||||
/// Returns true when the last comment was a line comment, i.e. the caller
|
||||
/// must put whatever it emits next on a fresh line.
|
||||
fn inline_comments(&self, comments: &[Comment], docs: &mut Vec<Doc>) -> bool {
|
||||
let mut ends_line = false;
|
||||
for c in comments {
|
||||
docs.push(if ends_line { Doc::HardLine } else { text(" ") });
|
||||
docs.push(self.comment(c));
|
||||
ends_line = is_line_comment(&c.text);
|
||||
}
|
||||
ends_line
|
||||
}
|
||||
|
||||
fn with_meta(&self, meta: &Meta, doc: Doc) -> Doc {
|
||||
let mut docs = self.leading(meta);
|
||||
docs.push(doc);
|
||||
@@ -210,11 +235,30 @@ impl<'a> Fmt<'a> {
|
||||
/// Comma-separated list inside `open`/`close`, one per line when broken.
|
||||
/// `force_break` lays every element on its own line regardless of width.
|
||||
fn delimited(&self, open: &str, items: Vec<ListItem>, close: &str, force_break: bool) -> Doc {
|
||||
if items.is_empty() {
|
||||
self.delimited_dangling(open, items, &[], close, force_break)
|
||||
}
|
||||
|
||||
/// The same, plus the comments written after the last element and before
|
||||
/// `close`. They are printed inside the brackets, each on its own line:
|
||||
/// printed after `close` they would move across it in the token stream,
|
||||
/// and a `/* verilator lint_on */`-style pragma would cover the wrong
|
||||
/// region.
|
||||
fn delimited_dangling(
|
||||
&self,
|
||||
open: &str,
|
||||
items: Vec<ListItem>,
|
||||
dangling: &[Comment],
|
||||
close: &str,
|
||||
force_break: bool,
|
||||
) -> Doc {
|
||||
if items.is_empty() && dangling.is_empty() {
|
||||
return text(format!("{open}{close}"));
|
||||
}
|
||||
let mut inner: Vec<Doc> = vec![if force_break { Doc::HardLine } else { Doc::SoftLine }];
|
||||
let last = items.len() - 1;
|
||||
let mut inner: Vec<Doc> = Vec::new();
|
||||
if !items.is_empty() {
|
||||
inner.push(if force_break { Doc::HardLine } else { Doc::SoftLine });
|
||||
}
|
||||
let last = items.len().saturating_sub(1);
|
||||
let mut close_needs_hardline = force_break;
|
||||
for (i, item) in items.into_iter().enumerate() {
|
||||
if i > 0 {
|
||||
@@ -242,6 +286,11 @@ impl<'a> Fmt<'a> {
|
||||
inner.push(Doc::Line);
|
||||
}
|
||||
}
|
||||
for c in dangling {
|
||||
inner.push(Doc::HardLine);
|
||||
inner.push(self.comment(c));
|
||||
close_needs_hardline = true;
|
||||
}
|
||||
// Peek at blank_before flags is handled by leading comments already;
|
||||
// blank lines inside bracketed lists are dropped deliberately.
|
||||
let mut docs = vec![text(open), indent(inner)];
|
||||
@@ -397,28 +446,37 @@ impl<'a> Fmt<'a> {
|
||||
let mut docs = vec![text(format!("{} {}", m.kw, m.name))];
|
||||
let has_imports = !m.imports.is_empty();
|
||||
if has_imports {
|
||||
docs.push(indent(vec![
|
||||
Doc::HardLine,
|
||||
text(format!("import {};", m.imports.join(", "))),
|
||||
]));
|
||||
// One line per `import` statement the header wrote: folding two of
|
||||
// them into one comma-separated statement would rewrite a `;`.
|
||||
let mut lines = Vec::new();
|
||||
for paths in &m.imports {
|
||||
lines.push(Doc::HardLine);
|
||||
lines.push(text(format!("import {};", paths.join(", "))));
|
||||
}
|
||||
docs.push(indent(lines));
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
// After an import block the header continues at column 0, so the
|
||||
// usual single space before `#(`/`(` is dropped.
|
||||
let mut on_fresh_line = has_imports;
|
||||
if !m.param_ports.is_empty() {
|
||||
let items: Vec<ListItem> = m
|
||||
.param_ports
|
||||
.iter()
|
||||
.map(|p| ListItem::from_meta(&p.meta, self.param_port(p)))
|
||||
.collect();
|
||||
// A written-but-empty `#()` is printed back; a missing one stays
|
||||
// missing.
|
||||
if let Some(params) = &m.param_ports {
|
||||
let items: Vec<ListItem> =
|
||||
params.iter().map(|p| ListItem::from_meta(&p.meta, self.param_port(p))).collect();
|
||||
docs.push(text(if on_fresh_line { "#" } else { " #" }));
|
||||
docs.push(self.delimited("(", items, ")", false));
|
||||
docs.push(self.delimited_dangling("(", items, &m.param_dangling, ")", false));
|
||||
on_fresh_line = false;
|
||||
}
|
||||
match &m.ports {
|
||||
PortList::None => docs.push(text(";")),
|
||||
PortList::Empty => docs.push(text(if on_fresh_line { "();" } else { " ();" })),
|
||||
PortList::Empty => {
|
||||
if !on_fresh_line {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.delimited_dangling("(", Vec::new(), &m.port_dangling, ")", false));
|
||||
docs.push(text(";"));
|
||||
}
|
||||
PortList::Ansi(_) | PortList::NonAnsi(_) => {
|
||||
let items: Vec<ListItem> = match &m.ports {
|
||||
PortList::Ansi(ports) => ports
|
||||
@@ -434,7 +492,7 @@ impl<'a> Fmt<'a> {
|
||||
if !on_fresh_line {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.delimited("(", items, ")", false));
|
||||
docs.push(self.delimited_dangling("(", items, &m.port_dangling, ")", false));
|
||||
docs.push(text(";"));
|
||||
}
|
||||
}
|
||||
@@ -552,7 +610,7 @@ impl<'a> Fmt<'a> {
|
||||
let sep = if tight { op.clone() } else { format!(" {op} ") };
|
||||
concat(vec![self.expr_compact(lhs), text(sep), self.expr_compact(rhs)])
|
||||
}
|
||||
Expr::Ternary { cond, then, els } => concat(vec![
|
||||
Expr::Ternary { cond, then, els, .. } => concat(vec![
|
||||
self.expr_compact(cond),
|
||||
text(" ? "),
|
||||
self.expr_compact(then),
|
||||
@@ -602,6 +660,11 @@ impl<'a> Fmt<'a> {
|
||||
docs.push(item.doc);
|
||||
if let Some(tr) = item.trailing {
|
||||
docs.push(text(format!(" {tr}")));
|
||||
// The caller appends the `;`; a line comment runs to end of
|
||||
// line, so it has to go on the next one.
|
||||
if is_line_comment(&tr) {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
}
|
||||
return concat(docs);
|
||||
}
|
||||
@@ -622,7 +685,7 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
if let Some(tr) = item.trailing {
|
||||
inner.push(text(format!(" {tr}")));
|
||||
if i < last {
|
||||
if i < last || is_line_comment(&tr) {
|
||||
inner.push(Doc::HardLine);
|
||||
}
|
||||
} else if i < last {
|
||||
@@ -755,6 +818,19 @@ impl<'a> Fmt<'a> {
|
||||
// Module items
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// `lhs = rhs`, with any comments written after the `=` printed on the
|
||||
/// `=`'s line so they stay on that side of the value.
|
||||
fn assign_pair(&self, p: &AssignPair) -> Doc {
|
||||
if p.rhs_comments.is_empty() {
|
||||
return group(vec![self.expr(&p.lhs), text(" ="), self.assign_rhs(self.expr(&p.rhs))]);
|
||||
}
|
||||
let mut inner = Vec::new();
|
||||
let ends_line = self.inline_comments(&p.rhs_comments, &mut inner);
|
||||
inner.push(if ends_line { Doc::HardLine } else { text(" ") });
|
||||
inner.push(self.expr(&p.rhs));
|
||||
group(vec![self.expr(&p.lhs), text(" ="), indent(inner)])
|
||||
}
|
||||
|
||||
fn cont_assign(&self, a: &ContAssign) -> Doc {
|
||||
let mut docs = vec![text("assign ")];
|
||||
if let Some(delay) = &a.delay {
|
||||
@@ -762,15 +838,8 @@ impl<'a> Fmt<'a> {
|
||||
docs.push(self.expr(delay));
|
||||
docs.push(text(" "));
|
||||
}
|
||||
let items: Vec<ListItem> = a
|
||||
.assigns
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let d =
|
||||
group(vec![self.expr(&p.lhs), text(" ="), self.assign_rhs(self.expr(&p.rhs))]);
|
||||
ListItem::from_meta(&p.meta, d)
|
||||
})
|
||||
.collect();
|
||||
let items: Vec<ListItem> =
|
||||
a.assigns.iter().map(|p| ListItem::from_meta(&p.meta, self.assign_pair(p))).collect();
|
||||
if items.len() == 1 {
|
||||
let item = items.into_iter().next().unwrap();
|
||||
docs.push(item.doc);
|
||||
@@ -804,12 +873,11 @@ impl<'a> Fmt<'a> {
|
||||
|
||||
fn instantiation(&self, inst: &Instantiation) -> Doc {
|
||||
let mut docs = vec![text(inst.module.clone())];
|
||||
if !inst.params.is_empty() {
|
||||
let items: Vec<ListItem> = inst
|
||||
.params
|
||||
.iter()
|
||||
.map(|c| ListItem::from_meta(&c.meta, self.connection(c)))
|
||||
.collect();
|
||||
// An empty `#()` was written by hand and is reprinted as `#()`; a
|
||||
// missing one stays missing.
|
||||
if let Some(params) = &inst.params {
|
||||
let items: Vec<ListItem> =
|
||||
params.iter().map(|c| ListItem::from_meta(&c.meta, self.connection(c))).collect();
|
||||
docs.push(text(" #"));
|
||||
docs.push(self.delimited("(", items, ")", false));
|
||||
}
|
||||
@@ -894,7 +962,22 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
match &c.expr {
|
||||
None => text(format!(".{}", c.name)),
|
||||
Some(Expr::Empty) => text(format!(".{}()", c.name)),
|
||||
Some(Expr::Empty(comments)) => {
|
||||
let mut docs = vec![text(format!(".{}(", c.name))];
|
||||
let mut ends_line = false;
|
||||
for cm in comments {
|
||||
if ends_line {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(self.comment(cm));
|
||||
ends_line = is_line_comment(&cm.text);
|
||||
}
|
||||
if ends_line {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(text(")"));
|
||||
concat(docs)
|
||||
}
|
||||
Some(e) => concat(vec![
|
||||
text(format!(".{}(", c.name)),
|
||||
group(vec![indent(vec![Doc::SoftLine, self.expr(e)]), Doc::SoftLine]),
|
||||
@@ -1008,13 +1091,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 label = if item.labels.is_empty() {
|
||||
text("default:")
|
||||
} else {
|
||||
let labels: Vec<Doc> = item.labels.iter().map(|l| self.expr(l)).collect();
|
||||
concat(vec![concat(join(labels, text(", "))), text(":")])
|
||||
};
|
||||
let mut item_docs = vec![label];
|
||||
let mut item_docs = vec![self.case_labels(&item.labels)];
|
||||
self.gen_block(&mut item_docs, &item.body);
|
||||
body.push(concat(item_docs));
|
||||
if let Some(tr) = &item.meta.trailing {
|
||||
@@ -1211,24 +1288,23 @@ impl<'a> Fmt<'a> {
|
||||
concat(vec![text("@("), indent(inner), text(")")])
|
||||
}
|
||||
SensList::List(items) => {
|
||||
let any_edge = items.iter().any(|i| i.edge.is_some());
|
||||
let sep = if any_edge { text(" or ") } else { text(", ") };
|
||||
let parts: Vec<Doc> = items
|
||||
.iter()
|
||||
.map(|i| {
|
||||
let mut d = Vec::new();
|
||||
if let Some(e) = &i.edge {
|
||||
d.push(text(format!("{e} ")));
|
||||
}
|
||||
d.push(self.expr(&i.expr));
|
||||
concat(d)
|
||||
})
|
||||
.collect();
|
||||
// Each separator is printed as it was written: `,` and `or`
|
||||
// mean the same thing but are different tokens, and rewriting
|
||||
// one as the other is a token change the safety net rejects.
|
||||
let mut parts: Vec<Doc> = Vec::new();
|
||||
for i in items {
|
||||
match i.sep {
|
||||
Some(SensSep::Comma) => parts.push(text(", ")),
|
||||
Some(SensSep::Or) => parts.push(text(" or ")),
|
||||
None => {}
|
||||
}
|
||||
if let Some(e) = &i.edge {
|
||||
parts.push(text(format!("{e} ")));
|
||||
}
|
||||
parts.push(self.expr(&i.expr));
|
||||
}
|
||||
let mut docs = vec![text("@(")];
|
||||
docs.push(group(vec![
|
||||
indent(vec![Doc::SoftLine, concat(join(parts, sep))]),
|
||||
Doc::SoftLine,
|
||||
]));
|
||||
docs.push(group(vec![indent(vec![Doc::SoftLine, concat(parts)]), Doc::SoftLine]));
|
||||
docs.push(text(")"));
|
||||
concat(docs)
|
||||
}
|
||||
@@ -1454,14 +1530,46 @@ impl<'a> Fmt<'a> {
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// The `A, B:` head of a case item — `default:` when the list is empty.
|
||||
/// 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 {
|
||||
if labels.is_empty() {
|
||||
return text("default:");
|
||||
}
|
||||
let plain = labels.iter().all(|l| l.meta.leading.is_empty() && l.meta.trailing.is_none());
|
||||
if plain {
|
||||
let docs: Vec<Doc> = labels.iter().map(|l| self.expr(&l.expr)).collect();
|
||||
return concat(vec![concat(join(docs, text(", "))), text(":")]);
|
||||
}
|
||||
let last = labels.len() - 1;
|
||||
let mut docs = Vec::new();
|
||||
for (i, l) in labels.iter().enumerate() {
|
||||
if i > 0 {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
for c in &l.meta.leading {
|
||||
docs.push(self.comment(c));
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(self.expr(&l.expr));
|
||||
if i < last {
|
||||
docs.push(text(","));
|
||||
}
|
||||
if let Some(tr) = &l.meta.trailing {
|
||||
docs.push(text(format!(" {tr}")));
|
||||
if i == last && is_line_comment(tr) {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
}
|
||||
}
|
||||
docs.push(text(":"));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
fn case_item(&self, item: &CaseItem) -> Doc {
|
||||
let label = if item.labels.is_empty() {
|
||||
text("default:")
|
||||
} else {
|
||||
let labels: Vec<Doc> = item.labels.iter().map(|l| self.expr(l)).collect();
|
||||
concat(vec![concat(join(labels, text(", "))), text(":")])
|
||||
};
|
||||
self.stmt_as_body(label, &item.stmt)
|
||||
self.stmt_as_body(self.case_labels(&item.labels), &item.stmt)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -1490,20 +1598,26 @@ impl<'a> Fmt<'a> {
|
||||
Expr::Ident(s) => text(s.clone()),
|
||||
Expr::Number(s) => text(s.clone()),
|
||||
Expr::Str(s) => text(s.clone()),
|
||||
Expr::Empty => text(""),
|
||||
// Only reachable through `connection`, which handles the comments.
|
||||
Expr::Empty(_) => text(""),
|
||||
Expr::Unary { op, expr } => concat(vec![text(op.clone()), self.expr(expr)]),
|
||||
Expr::Binary { .. } => self.binary_chain(e),
|
||||
Expr::Ternary { cond, then, els } => group(vec![
|
||||
self.expr(cond),
|
||||
indent(vec![
|
||||
Doc::Line,
|
||||
text("? "),
|
||||
self.expr(then),
|
||||
Doc::Line,
|
||||
text(": "),
|
||||
self.expr(els),
|
||||
]),
|
||||
]),
|
||||
Expr::Ternary { cond, then, els, comments } => {
|
||||
if comments.is_empty() {
|
||||
return group(vec![
|
||||
self.expr(cond),
|
||||
indent(vec![
|
||||
Doc::Line,
|
||||
text("? "),
|
||||
self.expr(then),
|
||||
Doc::Line,
|
||||
text(": "),
|
||||
self.expr(els),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
self.ternary_with_comments(cond, then, els, comments)
|
||||
}
|
||||
Expr::Call { callee, args } => {
|
||||
concat(vec![self.expr(callee), self.expr_list("(", args, ")")])
|
||||
}
|
||||
@@ -1585,6 +1699,34 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A `? :` with comments written inside it. Each comment stays between the
|
||||
/// two tokens it was written between, and a line comment forces the break
|
||||
/// that follows it, so the layout can never fold a comment over the `?`,
|
||||
/// the `:` or an operand.
|
||||
fn ternary_with_comments(
|
||||
&self,
|
||||
cond: &Expr,
|
||||
then: &Expr,
|
||||
els: &Expr,
|
||||
comments: &TernaryComments,
|
||||
) -> Doc {
|
||||
let mut head = vec![self.expr(cond)];
|
||||
let hard = self.inline_comments(&comments.before_question, &mut head);
|
||||
let mut inner = vec![if hard { Doc::HardLine } else { Doc::Line }];
|
||||
inner.push(text("?"));
|
||||
let hard = self.inline_comments(&comments.after_question, &mut inner);
|
||||
inner.push(if hard { Doc::HardLine } else { text(" ") });
|
||||
inner.push(self.expr(then));
|
||||
let hard = self.inline_comments(&comments.before_colon, &mut inner);
|
||||
inner.push(if hard { Doc::HardLine } else { Doc::Line });
|
||||
inner.push(text(":"));
|
||||
let hard = self.inline_comments(&comments.after_colon, &mut inner);
|
||||
inner.push(if hard { Doc::HardLine } else { text(" ") });
|
||||
inner.push(self.expr(els));
|
||||
head.push(indent(inner));
|
||||
group(head)
|
||||
}
|
||||
|
||||
/// Flatten a left-nested chain of same-precedence binary operators so
|
||||
/// `a + b + c` breaks as one unit instead of stair-stepping. An operator
|
||||
/// carrying comments (written after the operand before it) starts its own
|
||||
@@ -1593,17 +1735,17 @@ impl<'a> Fmt<'a> {
|
||||
let Expr::Binary { op, .. } = e else { unreachable!() };
|
||||
let prec = Self::binary_prec(op);
|
||||
let mut operands: Vec<&Expr> = Vec::new();
|
||||
let mut ops: Vec<(&str, &[Comment])> = Vec::new();
|
||||
let mut ops: Vec<BinaryOp<'_>> = Vec::new();
|
||||
fn walk<'e>(
|
||||
e: &'e Expr,
|
||||
prec: u8,
|
||||
operands: &mut Vec<&'e Expr>,
|
||||
ops: &mut Vec<(&'e str, &'e [Comment])>,
|
||||
ops: &mut Vec<BinaryOp<'e>>,
|
||||
) {
|
||||
match e {
|
||||
Expr::Binary { lhs, op, rhs, comments } if Fmt::binary_prec(op) == prec => {
|
||||
walk(lhs, prec, operands, ops);
|
||||
ops.push((op, comments));
|
||||
ops.push(BinaryOp { op, before: &comments.before, after: &comments.after });
|
||||
operands.push(rhs);
|
||||
}
|
||||
_ => operands.push(e),
|
||||
@@ -1612,17 +1754,25 @@ impl<'a> Fmt<'a> {
|
||||
walk(e, prec, &mut operands, &mut ops);
|
||||
let mut docs = vec![self.expr(operands[0])];
|
||||
let mut cont = Vec::new();
|
||||
for ((op, comments), rhs) in ops.iter().zip(operands[1..].iter()) {
|
||||
if comments.is_empty() {
|
||||
cont.push(text(format!(" {op}")));
|
||||
cont.push(Doc::Line);
|
||||
for (op, rhs) in ops.iter().zip(operands[1..].iter()) {
|
||||
// Comments written before the operator stay on the left operand's
|
||||
// line; the operator then starts a new one.
|
||||
self.inline_comments(op.before, &mut cont);
|
||||
if op.before.is_empty() {
|
||||
cont.push(text(format!(" {}", op.op)));
|
||||
} else {
|
||||
for c in comments.iter() {
|
||||
cont.push(text(" "));
|
||||
cont.push(self.comment(c));
|
||||
}
|
||||
cont.push(Doc::HardLine);
|
||||
cont.push(text(format!("{op} ")));
|
||||
cont.push(text(op.op.to_string()));
|
||||
}
|
||||
// Comments written after the operator stay on the operator's line;
|
||||
// the right operand then starts a new one.
|
||||
let hard = self.inline_comments(op.after, &mut cont);
|
||||
if hard {
|
||||
cont.push(Doc::HardLine);
|
||||
} else if !op.after.is_empty() || !op.before.is_empty() {
|
||||
cont.push(text(" "));
|
||||
} else {
|
||||
cont.push(Doc::Line);
|
||||
}
|
||||
cont.push(self.expr(rhs));
|
||||
}
|
||||
|
||||
@@ -435,3 +435,267 @@ module m;
|
||||
assign ready = first // wait for the second one too
|
||||
&& second;
|
||||
endmodule
|
||||
====
|
||||
# comment after a binary operator stays on the operator's line
|
||||
module m;
|
||||
assign fetch_addr_d = (branch_i ? addr_i : {fetch_addr_q[31:2], 2'b00}) +
|
||||
// Current address + 4
|
||||
{{29{1'b0}}, (valid_new_req & ~valid_req_q), 2'b00};
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign fetch_addr_d = (branch_i ? addr_i : {fetch_addr_q[31:2], 2'b00}) + // Current address + 4
|
||||
{{29{1'b0}}, (valid_new_req & ~valid_req_q), 2'b00};
|
||||
endmodule
|
||||
====
|
||||
# comments on both sides of a binary operator
|
||||
module m;
|
||||
assign y = a // pre
|
||||
&& // post
|
||||
b;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign y = a // pre
|
||||
&& // post
|
||||
b;
|
||||
endmodule
|
||||
====
|
||||
# a block comment after an operator stays on its line
|
||||
module m;
|
||||
assign y = a && /* still true */ b;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign y = a && /* still true */ b;
|
||||
endmodule
|
||||
====
|
||||
# two line comments after an operator each keep their own line
|
||||
module m;
|
||||
assign y = a && // one
|
||||
// two
|
||||
b;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign y = a && // one
|
||||
// two
|
||||
b;
|
||||
endmodule
|
||||
====
|
||||
# comment between `=` and the value it assigns
|
||||
module m;
|
||||
assign skid_valid_d =
|
||||
// Branches invalidate the skid buffer
|
||||
branch_i;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign skid_valid_d = // Branches invalidate the skid buffer
|
||||
branch_i;
|
||||
endmodule
|
||||
====
|
||||
# several comments between `=` and the value
|
||||
module m;
|
||||
assign rx_timeout_count_d =
|
||||
// don't count if timeout feature not enabled
|
||||
// will never reach timeout val
|
||||
(uart_rxto_en == 1'b0) ? 24'd0 : count_q;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign rx_timeout_count_d = // don't count if timeout feature not enabled
|
||||
// will never reach timeout val
|
||||
(uart_rxto_en == 1'b0) ? 24'd0 : count_q;
|
||||
endmodule
|
||||
====
|
||||
# comment after the `?` of a ternary
|
||||
module m;
|
||||
assign y = cond ?
|
||||
// take the fast path
|
||||
a : b;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign y = cond
|
||||
? // take the fast path
|
||||
a
|
||||
: b;
|
||||
endmodule
|
||||
====
|
||||
# comment after the `:` of a ternary
|
||||
module m;
|
||||
assign y = cond ? a : // otherwise
|
||||
b;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign y = cond
|
||||
? a
|
||||
: // otherwise
|
||||
b;
|
||||
endmodule
|
||||
====
|
||||
# comments in every position inside a ternary
|
||||
module m;
|
||||
assign y = cond /* c1 */ ? /* c2 */ a /* c3 */ : /* c4 */ b;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign y = cond /* c1 */ ? /* c2 */ a /* c3 */ : /* c4 */ b;
|
||||
endmodule
|
||||
====
|
||||
# comment between two case labels
|
||||
module m;
|
||||
always_comb begin
|
||||
case (operator_i)
|
||||
// Adder OPs
|
||||
ALU_SUB,
|
||||
|
||||
// Comparator OPs
|
||||
ALU_EQ, ALU_NE,
|
||||
ALU_GE: y = 1'b1;
|
||||
default: y = 1'b0;
|
||||
endcase
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always_comb begin
|
||||
case (operator_i)
|
||||
// Adder OPs
|
||||
ALU_SUB,
|
||||
// Comparator OPs
|
||||
ALU_EQ,
|
||||
ALU_NE,
|
||||
ALU_GE:
|
||||
y = 1'b1;
|
||||
default: y = 1'b0;
|
||||
endcase
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# trailing comment on a case label
|
||||
module m;
|
||||
always_comb begin
|
||||
case (s)
|
||||
A, // first
|
||||
B: y = 1'b1;
|
||||
default: y = 1'b0;
|
||||
endcase
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always_comb begin
|
||||
case (s)
|
||||
A, // first
|
||||
B:
|
||||
y = 1'b1;
|
||||
default: y = 1'b0;
|
||||
endcase
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# comments before the closing paren of a parameter port list
|
||||
module prim_clock_buf #(
|
||||
// Turning off these verilator lints because keeping these parameters makes it
|
||||
/* verilator lint_off UNUSED */
|
||||
parameter bit NoFpgaBuf = 1'b0, // serves no function in generic
|
||||
parameter bit RegionSel = 1'b0 // serves no function in generic
|
||||
/* verilator lint_on UNUSED */
|
||||
) (
|
||||
input clk_i,
|
||||
output logic clk_o
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module prim_clock_buf #(
|
||||
// Turning off these verilator lints because keeping these parameters makes it
|
||||
/* verilator lint_off UNUSED */
|
||||
parameter bit NoFpgaBuf = 1'b0, // serves no function in generic
|
||||
parameter bit RegionSel = 1'b0 // serves no function in generic
|
||||
/* verilator lint_on UNUSED */
|
||||
) (input clk_i, output logic clk_o);
|
||||
endmodule
|
||||
====
|
||||
# a continued trailing comment before the closing paren of a port list
|
||||
module m (
|
||||
input logic a,
|
||||
output logic b // we are executing a taken branch
|
||||
// instruction
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m (
|
||||
input logic a,
|
||||
output logic b // we are executing a taken branch
|
||||
// instruction
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# comment inside an otherwise empty parameter port list
|
||||
module m #(
|
||||
/* nothing to override */
|
||||
) (input a);
|
||||
endmodule
|
||||
----
|
||||
module m #(
|
||||
/* nothing to override */
|
||||
) (input a);
|
||||
endmodule
|
||||
====
|
||||
# comment inside an otherwise empty port list
|
||||
module m (
|
||||
/* no ports */
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m (
|
||||
/* no ports */
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# comment inside an empty connection
|
||||
module m;
|
||||
edge_propagator_ack i_ack (
|
||||
.clk_tx_i,
|
||||
.ack_tx_o (/* unused */),
|
||||
.edge_o
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
edge_propagator_ack i_ack (.clk_tx_i, .ack_tx_o(/* unused */), .edge_o);
|
||||
endmodule
|
||||
====
|
||||
# block comment between a declarator and its semicolon
|
||||
module m;
|
||||
logic [7:0] data_state /* verilator split_var */;
|
||||
logic en_latch /* verilator clock_enable */;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
logic [7:0] data_state /* verilator split_var */;
|
||||
logic en_latch /* verilator clock_enable */;
|
||||
endmodule
|
||||
====
|
||||
# comment before the semicolon plus one after it
|
||||
module m;
|
||||
idx_t [7:0] index_nodes /* verilator split_var */; // propagates indices
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
idx_t [7:0] index_nodes /* verilator split_var */; // propagates indices
|
||||
endmodule
|
||||
====
|
||||
# comment before the semicolon of a parameter and a port declaration
|
||||
module m (a);
|
||||
input a /* async */;
|
||||
parameter int W = 8 /* width */;
|
||||
endmodule
|
||||
----
|
||||
module m (a);
|
||||
input a /* async */;
|
||||
parameter int W = 8 /* width */;
|
||||
endmodule
|
||||
@@ -198,3 +198,29 @@ module m;
|
||||
|
||||
sub u1 ();
|
||||
endmodule
|
||||
====
|
||||
# an empty parameter override list is written, so it is printed back
|
||||
module tb;
|
||||
picorv32 #(
|
||||
) uut (
|
||||
.clk(clk),
|
||||
.resetn(resetn)
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module tb;
|
||||
picorv32 #() uut (.clk(clk), .resetn(resetn));
|
||||
endmodule
|
||||
====
|
||||
# no override list at all stays absent
|
||||
module tb;
|
||||
sub u0 (.a(x));
|
||||
sub #() u1 (.a(x));
|
||||
sub #(.W(8)) u2 (.a(x));
|
||||
endmodule
|
||||
----
|
||||
module tb;
|
||||
sub u0 (.a(x));
|
||||
sub #() u1 (.a(x));
|
||||
sub #(.W(8)) u2 (.a(x));
|
||||
endmodule
|
||||
@@ -146,3 +146,51 @@ endpackage : p
|
||||
package p;
|
||||
localparam int W = 8;
|
||||
endpackage : p
|
||||
====
|
||||
# two header imports stay two statements (never merged into one)
|
||||
module prim_alert_rxtx_tb
|
||||
import prim_alert_pkg::*;
|
||||
import prim_mubi_pkg::mubi4_t;
|
||||
(
|
||||
input clk_i,
|
||||
output logic done_o
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module prim_alert_rxtx_tb
|
||||
import prim_alert_pkg::*;
|
||||
import prim_mubi_pkg::mubi4_t;
|
||||
(input clk_i, output logic done_o);
|
||||
endmodule
|
||||
====
|
||||
# a single header import with several paths keeps its one statement
|
||||
module m
|
||||
import a::*, b::t;
|
||||
(
|
||||
input clk_i
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m
|
||||
import a::*, b::t;
|
||||
(input clk_i);
|
||||
endmodule
|
||||
====
|
||||
# three header imports before a parameter list
|
||||
module m
|
||||
import a::*;
|
||||
import b::t;
|
||||
import c::u;
|
||||
#(
|
||||
parameter int W = 8
|
||||
) (
|
||||
input clk_i
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m
|
||||
import a::*;
|
||||
import b::t;
|
||||
import c::u;
|
||||
#(parameter int W = 8) (input clk_i);
|
||||
endmodule
|
||||
@@ -518,3 +518,43 @@ module m;
|
||||
end
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a comma-separated event list keeps its commas (never rewritten as `or`)
|
||||
module m;
|
||||
always_ff @(posedge clk_i, negedge rst_ni) begin
|
||||
q <= d;
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always_ff @(posedge clk_i, negedge rst_ni) begin
|
||||
q <= d;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a mixed event list keeps each separator as written
|
||||
module m;
|
||||
always @(posedge clk, negedge rst_n or a, b) q <= d;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always @(posedge clk, negedge rst_n or a, b) q <= d;
|
||||
endmodule
|
||||
====
|
||||
# a comma-separated event list without edges keeps its commas
|
||||
module m;
|
||||
always @(a, b, c) y = a & b & c;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always @(a, b, c) y = a & b & c;
|
||||
endmodule
|
||||
====
|
||||
# an `or`-separated event list without edges keeps `or`
|
||||
module m;
|
||||
always @(a or b or c) y = a & b & c;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always @(a or b or c) y = a & b & c;
|
||||
endmodule
|
||||
@@ -273,3 +273,79 @@ fn format_source_would_reject_a_non_equivalent_output() {
|
||||
let err = FormatError::Verification(expect_divergence(src, bad_output));
|
||||
assert!(err.to_string().starts_with("verification failed:"), "{err}");
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// corpus-bugs (2026-08-19): the four root causes the corpus check found were
|
||||
// all fixed in the parser/formatter, with no new forgiveness in `normalize`.
|
||||
// These pin that down: every shape the net used to catch is still caught, so a
|
||||
// future regression in the fixes shows up as a refusal, not as a rewritten
|
||||
// file. Per CLAUDE.md hard invariant #4 these are the attack tests that would
|
||||
// have been mandatory had any of the fixes been made in `verify.rs` instead.
|
||||
|
||||
#[test]
|
||||
fn an_event_list_comma_rewritten_as_or_is_still_rejected() {
|
||||
// Root cause A. `,` and `or` mean the same thing to a simulator, so a
|
||||
// normalization that collapsed them would have "fixed" the corpus files
|
||||
// while letting the formatter rewrite tokens at will.
|
||||
let input = "module m;\n always_ff @(posedge clk_i, negedge rst_ni) q <= d;\nendmodule\n";
|
||||
let output = "module m;\n always_ff @(posedge clk_i or negedge rst_ni) q <= d;\nendmodule\n";
|
||||
expect_divergence(input, output);
|
||||
// ...and the reverse rewrite too.
|
||||
expect_divergence(output, input);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merged_header_imports_are_still_rejected() {
|
||||
// Root cause C: two header `import` statements folded into one, turning a
|
||||
// `;` into a `,`.
|
||||
let input = "module m\n import a::*;\n import b::t;\n(input clk);\nendmodule\n";
|
||||
let output = "module m\n import a::*, b::t;\n(input clk);\nendmodule\n";
|
||||
expect_divergence(input, output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_empty_parameter_override_is_still_rejected() {
|
||||
// Root cause D: `#()` is two tokens, and dropping them is token loss even
|
||||
// though the instantiation means the same thing without them.
|
||||
let input = "module tb;\n sub #() u0 (.a(x));\nendmodule\n";
|
||||
let output = "module tb;\n sub u0 (.a(x));\nendmodule\n";
|
||||
expect_divergence(input, output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_moved_out_of_a_bracketed_list_is_still_rejected() {
|
||||
// Root cause B: the comment is not dropped here, only moved across the
|
||||
// `)` — which changes which region a `verilator lint_on` pragma covers.
|
||||
// Stream order is what makes that detectable, so it must stay compared.
|
||||
let input = "module m #(\n parameter int W = 8\n /* verilator lint_on UNUSED */\n) (input a);\nendmodule\n";
|
||||
let output = "module m #(\n parameter int W = 8\n)\n/* verilator lint_on UNUSED */\n(input a);\nendmodule\n";
|
||||
expect_divergence(input, output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_moved_across_a_binary_operator_is_still_rejected() {
|
||||
// Root cause B in expressions: moving a comment from after the operator to
|
||||
// before it keeps every token, so only the comment's position in the
|
||||
// stream catches it.
|
||||
let input = "module m;\n assign y = a && // note\n b;\nendmodule\n";
|
||||
let output = "module m;\n assign y = a // note\n && b;\nendmodule\n";
|
||||
expect_divergence(input, output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_moved_across_a_semicolon_is_still_rejected() {
|
||||
// Root cause B on declarations: `/* verilator split_var */` printed after
|
||||
// the `;` instead of before it applies to nothing.
|
||||
let input = "module m;\n logic x /* verilator split_var */;\nendmodule\n";
|
||||
let output = "module m;\n logic x; /* verilator split_var */\nendmodule\n";
|
||||
expect_divergence(input, output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_line_comments_merged_onto_one_line_are_still_rejected() {
|
||||
// The failure mode the new comment placement has to avoid: printing two
|
||||
// line comments on one physical line re-lexes as a single, longer comment.
|
||||
let input = "module m;\n assign y = a && // one\n // two\n b;\nendmodule\n";
|
||||
let output = "module m;\n assign y = a && // one // two\n b;\nendmodule\n";
|
||||
expect_divergence(input, output);
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,558 @@
|
||||
# corpus-bugs
|
||||
|
||||
## Goal
|
||||
|
||||
Fix the four formatter bugs the 820-file corpus check exposed, catalogued as
|
||||
root causes A–D in `docs/features/corpus-check/README.md` and re-measured at 46
|
||||
affected files after `macro-items` raised the parse rate to 468/820. Every one
|
||||
of them made the runtime safety net refuse output (exit 2), so each was a file
|
||||
`vfmt` could not format at all: an event list's `,` rewritten as `or`, comments
|
||||
moved out of port/parameter lists and out of expressions, two module-header
|
||||
`import` statements folded into one, and a hand-written empty `#()` dropped.
|
||||
Three of the four are token rewrites the net is right to reject; the fourth is
|
||||
comment motion. None of them is fixed by widening the net — this feature does
|
||||
not touch `verify.rs`'s normalizations at all. **Result: 46 verification
|
||||
errors → 0, with the parse rate unchanged at 468/820.**
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **The safety net is the spec, not the obstacle.** Every fix here makes the
|
||||
formatter emit what the input actually said; not one relaxes a check.
|
||||
`verify.rs` is byte-identical to `HEAD` (`git diff --quiet` confirmed); the
|
||||
only addition is seven new **rejection** tests in `tests/verification.rs`.
|
||||
- **A separator that is legal in two spellings is not the formatter's to
|
||||
choose.** `@(a, b)` and `@(a or b)` mean the same thing to a simulator and
|
||||
different things to a token stream. The same reasoning already governs the
|
||||
trailing `;` of a macro invocation (`macro-items`): reproduce what was
|
||||
written.
|
||||
- **An empty `#()` is meaningful text, not noise.** Verilog allows both
|
||||
`sub u (...)` and `sub #() u (...)`; the second is what picorv32's testbench
|
||||
writes, and rewriting it to the first loses two tokens. The formatter neither
|
||||
adds nor removes one.
|
||||
- **Comments before a list's closing `)` belong inside the list.** A comment
|
||||
written on its own line after the last parameter, or a
|
||||
`/* verilator lint_on */` pragma closing a bracketed region, is about the
|
||||
list. Letting it fall through to the *next* construct's leading comments
|
||||
moves it across the `)` in the token stream — which the net rejects, and
|
||||
rightly, because the pragma would then cover the wrong region. This is the
|
||||
same rule `take_dangling` already applies before `end`/`endmodule`.
|
||||
- **A comment between a construct's last token and its `;` belongs before the
|
||||
`;`.** `logic x /* verilator split_var */;` is a verilator pragma whose
|
||||
position is load-bearing.
|
||||
- **Comments inside an expression stay on the side of the operator they were
|
||||
written on.** `a && // why` and `a // why` + `&& b` are different streams.
|
||||
The parser therefore records "before the operator" and "after the operator"
|
||||
separately, and the same for the four gaps inside a `? :`. Guessing a single
|
||||
side would be a coin flip that the net catches half the time.
|
||||
- **Two line comments never share a printed line.** `// a // b` re-lexes as one
|
||||
comment, which is comment loss disguised as comment motion. Every place this
|
||||
feature prints a run of comments goes through `Fmt::inline_comments`, which
|
||||
puts a hard line after any line comment. Pinned by
|
||||
`two_line_comments_merged_onto_one_line_are_still_rejected`.
|
||||
- **Blank lines inside a bracketed or label list are dropped**, as
|
||||
`Fmt::delimited` already documents. `ibex_alu.sv`'s blank line between
|
||||
`ALU_SUB,` and `// Comparator OPs` does not survive; the comment and the
|
||||
order do.
|
||||
- **Comments inside a replication, inside a compactly-printed bracket
|
||||
expression, and between a *continuous assignment's* value and its `;` remain
|
||||
refusals** — see Corpus results. They are refusals, not corruption, and each
|
||||
needs its own design decision.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Changed in `vlog_parser::ast` (consumed by `vlog_formatter::format`):**
|
||||
|
||||
| item | before | after |
|
||||
|---|---|---|
|
||||
| `SensItem` | `{ edge, expr }` | `{ sep: Option<SensSep>, edge, expr }`; new `enum SensSep { Comma, Or }`. `sep` is the separator written *before* this item, `None` on the first. Any consumer printing an event list must interleave these instead of picking one spelling per list. |
|
||||
| `Module::imports` | `Vec<String>` | `Vec<Vec<String>>` — one entry per `import` statement. Print one `import ...;` line per entry. |
|
||||
| `Module::param_ports` | `Vec<ParamPort>` | `Option<Vec<ParamPort>>`. `None` = no `#(...)` written; `Some(vec![])` = a written `#()`. `is_empty()` no longer distinguishes them. |
|
||||
| `Module` | — | new `param_dangling` / `port_dangling: Vec<Comment>`: comments before the closing `)` of each header list. |
|
||||
| `PortList::Empty` | — | may now come with a non-empty `Module::port_dangling` (`module m (/* c */);`). |
|
||||
| `Parser::parse_port_list` | `-> PResult<PortList>` | `-> PResult<(PortList, Vec<Comment>)>` |
|
||||
| `Instantiation::params` | `Vec<Connection>` | `Option<Vec<Connection>>`, same meaning as `Module::param_ports`. |
|
||||
| `Expr::Binary` | `{ .., comments: Vec<Comment> }` | `{ .., comments: Box<BinaryComments> }` with `before` / `after` fields. Boxed to keep `Expr` small — otherwise `clippy::large_enum_variant` fires on `ItemKind`/`GenElse`. |
|
||||
| `Expr::Ternary` | `{ cond, then, els }` | `+ comments: Box<TernaryComments>` with the four positions `before_question` / `after_question` / `before_colon` / `after_colon`. Boxed for the same reason. |
|
||||
| `Expr::Empty` | unit variant | `Empty(Vec<Comment>)` — the comments written inside `.name(/* unused */)`. |
|
||||
| `CaseItem::labels`, `GenCaseItem::labels` | `Vec<Expr>` | `Vec<ExprItem>`, so each label carries its own leading/trailing comments. |
|
||||
| `AssignPair` | `{ meta, lhs, rhs }` | `+ rhs_comments: Vec<Comment>` — comments between the `=` and the value. |
|
||||
|
||||
New parser helper `Parser::take_around(mark)` collects "every comment written
|
||||
in the gap ending at the cursor". It **clamps `mark`**, which also removes a
|
||||
latent panic: the two pre-existing raw `pending_trailing.split_off(mark)` call
|
||||
sites (`parse_binary_inner`, the `Expr::Paren` arm) could underflow when a
|
||||
nested construct drained the pending list, and both now go through the helper.
|
||||
|
||||
New formatter helpers: `Fmt::delimited_dangling` (`delimited` delegates to it
|
||||
with an empty slice, so its eight other call sites are untouched),
|
||||
`Fmt::inline_comments`, `Fmt::case_labels`, `Fmt::ternary_with_comments`,
|
||||
`Fmt::assign_pair`, and the `BinaryOp` struct that carries an operator plus the
|
||||
comments on each side through `binary_chain`'s flattening walk.
|
||||
|
||||
**Consumed from `verify.rs`:** nothing new. **No normalization was added or
|
||||
broadened**, per CLAUDE.md hard invariant #4. The three token-rewrite bugs are
|
||||
fixed by emitting the right token; the comment bug by printing the comment
|
||||
where the input had it. The seven new tests assert the net still *rejects*
|
||||
every shape these fixes could plausibly have been "fixed" by forgiving instead
|
||||
— including both directions of the `,`↔`or` rewrite.
|
||||
|
||||
**Recursion/chain budgets (`docs/features/recursion-limit/README.md`):** no new
|
||||
budget is charged and none is needed. Nothing added here recurses or builds a
|
||||
left-nested chain. `SensSep` is a `Copy` enum on an existing leaf; the import
|
||||
change adds one `Vec` level inside a loop that was already flat; `params`
|
||||
becomes an `Option` around an existing `Vec`; the comment work moves
|
||||
already-allocated `Comment` values between existing nodes. The two new boxes
|
||||
(`BinaryComments`, `TernaryComments`) sit *beside* the existing `Box<Expr>`
|
||||
children, so root-to-leaf depth is unchanged — and both make `Expr` **smaller**
|
||||
than it was before this feature (48 and 32 bytes for those variants, against 64
|
||||
and 24+96 if left inline), which is why `clippy::large_enum_variant` is silent
|
||||
again.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] **A** — event-list `,` vs `or` preserved per separator (13 corpus files).
|
||||
- [x] **B** — comments in port/parameter lists, declarations, case labels and
|
||||
expressions (26 corpus files, six distinct shapes — see Work log).
|
||||
- [x] **C** — consecutive module-header `import`s stay separate statements
|
||||
(5 corpus files).
|
||||
- [x] **D** — a written empty `#()` is printed back (1 corpus file), plus the
|
||||
same bug found in the *module header* `#()` while fixing it.
|
||||
- [x] 28 new case-table entries (19 comments, 4 statements, 3 module_headers,
|
||||
2 instantiation) + 6 parser unit tests + 7 verification rejection tests.
|
||||
- [x] `cargo test --workspace` 111 passed (was 98), clippy silent, fmt clean.
|
||||
- [x] Corpus acceptance: 46 verification errors → **0**, parse rate held at
|
||||
468/820, corpus verified unmodified.
|
||||
- [x] 10 named corpus files (2–4 per bug) format and are a fixed point on the
|
||||
second pass.
|
||||
- [x] `TODO.md`: nothing to check off — none of these bugs has a backlog item.
|
||||
- [ ] **Not done, deliberately:** three of the four comment-placement refusals
|
||||
documented in `docs/features/formatter-bug-fixes/README.md` still refuse
|
||||
(replication, compact bracket expression, value-before-`;` in a
|
||||
*continuous assignment*). The fourth — a comment in a ternary branch —
|
||||
is fixed here as a side effect of `TernaryComments`. See Corpus results.
|
||||
- [ ] **Not done:** comments between `=` and the value are handled for
|
||||
continuous assignments only, not for procedural assignments or
|
||||
declarator initializers. No corpus file needs them; the shape is
|
||||
`x <= // c` ⏎ `y;`. Same fix, one field each, when someone asks.
|
||||
|
||||
## Corpus results
|
||||
|
||||
`./tools/corpus_check.sh corpus` against the same pinned 820-file corpus,
|
||||
release build, corpus verified unmodified afterwards (`git status --porcelain`
|
||||
clean in all four repos apart from the untracked `.vfmt-corpus-rev` stamps).
|
||||
|
||||
| metric | after macro-items | after corpus-bugs |
|
||||
|---|---|---|
|
||||
| **verification-error** | 46 (5.6%) | **0 (0.0%)** |
|
||||
| parsed (reached the formatter) | 468/820 (57.1%) | 468/820 (57.1%) |
|
||||
| formattable (parsed *and* passed the net) | 422/820 (51.5%) | **468/820 (57.1%)** |
|
||||
| would-reformat | 420 | 466 |
|
||||
| parse-error | 352 (42.9%) | 352 (42.9%) |
|
||||
| ok-unchanged | 2 | 2 |
|
||||
| crash | 0 | 0 |
|
||||
|
||||
```
|
||||
outcome files share
|
||||
-------------------- ----- -------
|
||||
ok-unchanged 2 0.2%
|
||||
would-reformat 466 56.8%
|
||||
parse-error 352 42.9%
|
||||
verification-error 0 0.0%
|
||||
other-error 0 0.0%
|
||||
crash 0 0.0%
|
||||
-------------------- ----- -------
|
||||
total 820 100.0%
|
||||
```
|
||||
|
||||
**Diffed the two TSVs by path, not just by count**: exactly 46 files moved
|
||||
`verification-error → would-reformat` and **nothing else changed status** — no
|
||||
parse regression, no file that was formatting before stopped. The script's own
|
||||
exit status is now 0 (it was 1).
|
||||
|
||||
### The 46, by root cause
|
||||
|
||||
Classified from the diagnostics before any code was written, since the
|
||||
corpus-check README's original 10/9/4/1 split predates `macro-items`:
|
||||
|
||||
| cause | files | shape |
|
||||
|---|---|---|
|
||||
| A | 13 | `@(posedge clk_i, negedge rst_ni)` → `or` |
|
||||
| B | 26 | six shapes, below |
|
||||
| C | 5 | two header `import`s merged, `;` → `,` |
|
||||
| D | 1 | `picorv32 #(\n) uut (` loses `#()` |
|
||||
|
||||
Bug B's 26 split six ways, which is why it was the bulk of the work:
|
||||
|
||||
| B shape | files | example |
|
||||
|---|---|---|
|
||||
| B1a comment before a list's closing `)` | 6 | `prim_clock_buf.sv`, `prim_fifo_async_simple.sv`, `ibex_controller.sv` |
|
||||
| B1b comment inside an empty connection | 2 | `edge_propagator.sv` `.ack_tx_o (/* unused */)` |
|
||||
| B2 comment between a declarator and its `;` | 3 | `prim_subst_perm.sv` `/* verilator split_var */` |
|
||||
| B3a comment after a binary operator | 7 | `ibex_prefetch_buffer.sv`, `ibex_trvk.sv` |
|
||||
| B3b comment between case labels | 2 | `ibex_alu.sv` `// Comparator OPs` |
|
||||
| B3c comment inside a ternary | 6 | `prim_sha2.sv`, `uart_core.sv`, `ibex_pmp.sv` |
|
||||
|
||||
Two files (`ibex_icache.sv`, `uart_core.sv`) needed a seventh shape that only
|
||||
surfaced once the first six were fixed: a comment written between `assign x =`
|
||||
and the value.
|
||||
|
||||
### Named-file acceptance
|
||||
|
||||
Each formatted into a scratch copy, then `--check`ed on the result. The corpus
|
||||
itself was never written to (`md5` before/after identical for every file).
|
||||
|
||||
| bug | file | before | after |
|
||||
|---|---|---|---|
|
||||
| A | `common_cells/src/cdc_4phase.sv` | `,` at 172:28 → `or` | fixed point |
|
||||
| A | `common_cells/src/sync.sv` | `,` at 27:30 → `or` | fixed point |
|
||||
| A | `ibex/shared/rtl/ram_1p.sv` | `,` at 46:28 → `or` | fixed point |
|
||||
| B | `…/prim_generic/rtl/prim_clock_buf.sv` | `/* verilator lint_on UNUSED */` at 13:3 moved | fixed point |
|
||||
| B | `…/prim/rtl/prim_subst_perm.sv` | `/* verilator split_var */` at 32:49 moved | fixed point |
|
||||
| B | `ibex/rtl/ibex_alu.sv` | `// Comparator OPs` at 64:7 moved | fixed point |
|
||||
| B | `ibex/rtl/ibex_prefetch_buffer.sv` | `// Current address + 4` at 171:25 moved | fixed point |
|
||||
| C | `…/fpv/tb/prim_alert_rxtx_tb.sv` | `;` at 9:27 → `,` | fixed point |
|
||||
| C | `…/fpv/tb/prim_alert_rxtx_async_tb.sv` | `;` at 9:27 → `,` | fixed point |
|
||||
| D | `picorv32/testbench_ez.v` | `#` at 47:11 dropped | fixed point |
|
||||
|
||||
Spot-checked the output text, not just the exit code: `prim_clock_buf.sv` keeps
|
||||
both `lint_off`/`lint_on` pragmas inside the `#( ... )`, `sync.sv` keeps
|
||||
`@(posedge clk_i, negedge rst_ni)`, `prim_alert_rxtx_tb.sv` keeps two `import`
|
||||
lines, `testbench_ez.v` keeps `picorv32 #() uut (`.
|
||||
|
||||
### Remaining refusals: none in this corpus
|
||||
|
||||
Zero files in the 820 refuse. The known comment-placement refusals from
|
||||
`docs/features/formatter-bug-fixes/README.md` were re-probed by hand, since the
|
||||
corpus no longer exercises them:
|
||||
|
||||
| refusal | still refuses? |
|
||||
|---|---|
|
||||
| comment inside a replication — `{2{a, // c` | yes |
|
||||
| comment inside a compact bracket expression — `x[a /* c */ + b]` | yes |
|
||||
| comment between a continuous assignment's value and its `;` — `assign y = a /* c */ ;` | yes |
|
||||
| comment in a ternary branch — `assign w = c ? a : // c` ⏎ `b;` | **no — fixed here** |
|
||||
|
||||
The fourth was listed as a nit in that feature's QA log and is fixed as a side
|
||||
effect of `TernaryComments`: `after_colon` is exactly the position it names.
|
||||
The other three are untouched and remain refusals, not corruption.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-19 — dev agent
|
||||
|
||||
Read `CLAUDE.md`, `README.md`, and the corpus-check, macro-items,
|
||||
formatter-bug-fixes and recursion-limit feature READMEs before touching code.
|
||||
Baseline: `cargo test --workspace` 98 passed, clippy silent, fmt clean;
|
||||
`tools/corpus_check.sh corpus` reproduces 46 verification errors exactly.
|
||||
|
||||
**Classified the 46 before writing anything.** The corpus-check README's
|
||||
10/9/4/1 split is pre-`macro-items`; the live numbers are 13/26/5/1, and bug B
|
||||
turned out to be six different shapes rather than one. Doing this first is what
|
||||
kept the work ordered — B3c (ternaries) would otherwise have looked like a
|
||||
surprise at the end.
|
||||
|
||||
**Bug A (event-list separator) — fixed.** `Fmt::sens_list` chose one separator
|
||||
for the whole list (`if any item has an edge { " or " } else { ", " }`), so a
|
||||
comma list with edges came out as `or`. The information simply was not in the
|
||||
AST. Added `SensSep` and `SensItem::sep`, set from whichever of `,`/`or` the
|
||||
parse loop ate, and replaced `join(parts, sep)` with an interleave. Mixed lists
|
||||
(`@(posedge clk, negedge rst_n or a, b)`) now round-trip each separator
|
||||
independently, which the old shape could not express at all.
|
||||
|
||||
**Bug C (merged header imports) — fixed.** `parse_module` did
|
||||
`imports.extend(parse_import_list())`, flattening every header `import` into one
|
||||
`Vec<String>` the formatter printed as a single `import a::*, b::t;`. A
|
||||
one-word parser fix (`extend` → `push`) once the type became `Vec<Vec<String>>`.
|
||||
Added a case asserting that a *single* import with several paths still stays one
|
||||
statement, since that is the behavior the naive fix would break.
|
||||
|
||||
**Bug D (dropped empty `#()`) — fixed.** `Instantiation::params` was a
|
||||
`Vec<Connection>` and the formatter tested `is_empty()`, so "no override list"
|
||||
and "an empty override list" were the same value. Made it `Option<Vec<_>>` —
|
||||
the `Option` carries "was it written", exactly like `MacroCall::semi`. **While
|
||||
there, found the same bug in the module header**: `module m #() (...);` also
|
||||
dropped its `#()`. No corpus file writes it, but it is the identical root cause
|
||||
in code I was already changing, so it rides along (`Module::param_ports` is now
|
||||
an `Option` too).
|
||||
|
||||
**Bug B — six shapes, fixed in increasing order of AST churn.**
|
||||
|
||||
- *B3a, comment after a binary operator.* `parse_binary_inner` already captured
|
||||
comments written *before* the operator; the corpus writes them *after*
|
||||
(`!is_sealing_cap && // Not sealing cap`). Added the mirror capture and
|
||||
taught `binary_chain` to print each side. Extracted `BinaryOp` so the
|
||||
flattening walk carries an operator plus both comment runs instead of a
|
||||
widening tuple.
|
||||
- *B3c, comments inside a ternary.* Four gaps, four vectors
|
||||
(`TernaryComments`), because a comment after `?` and one before `:` are not
|
||||
interchangeable. **Chose four explicit positions over one "somewhere inside"
|
||||
vector**: the latter cannot be printed back without guessing, and a wrong
|
||||
guess is a stream divergence, i.e. a refusal — the bug I was fixing.
|
||||
- *B3b, comments between case labels.* `labels: Vec<Expr>` had nowhere to hang
|
||||
a comment. Switched both `CaseItem` and `GenCaseItem` to `Vec<ExprItem>` and
|
||||
reused the existing `parse_expr_item`/`parse_expr_list` pair, which already
|
||||
harvests exactly the right comments. `Fmt::case_labels` keeps the current
|
||||
one-line rendering when no label carries a comment and goes one-per-line
|
||||
otherwise, so no existing case moved.
|
||||
- *B1b, comments in an empty connection.* `.ack_tx_o (/* unused */)` parsed to
|
||||
`Expr::Empty` and the comment drifted past the `)`. Made it
|
||||
`Expr::Empty(Vec<Comment>)` — the comments live on the node they describe
|
||||
rather than in a field on `Connection` that would be meaningless for every
|
||||
other variant.
|
||||
- *B2, comment before a declaration's `;`.* `parse_declarators` harvested a
|
||||
trailing comment only when a comma followed, so the last declarator's
|
||||
`/* verilator split_var */` fell through to the *item's* trailing and printed
|
||||
after the `;`. Now always harvested — safe because the `;` has not been
|
||||
consumed at that point, so nothing written after it can be picked up.
|
||||
`Fmt::declarators` puts a hard line after a *line* comment there, since the
|
||||
caller appends the `;` on the same line; that makes the pathological
|
||||
`logic x // note` ⏎ `;` idempotent instead of a refusal.
|
||||
- *B1a, comments before a list's closing `)`.* The largest change.
|
||||
`Fmt::delimited` grew a sibling `delimited_dangling` rather than a fifth
|
||||
parameter, so its eight unrelated call sites are untouched. `take_dangling`
|
||||
— which already existed for `end`/`endmodule` — is now also called before the
|
||||
`)` of the parameter-port list and both port-list flavors, and the comments
|
||||
land in two new `Module` fields. Also covered the empty-list case
|
||||
(`module m (/* c */);`), which needed `delimited_dangling` to stop
|
||||
short-circuiting on `items.is_empty()`.
|
||||
|
||||
**A seventh shape only appeared after the first six.** With B1a–B3c done the
|
||||
corpus was at 2 errors, both `assign x =` ⏎ `// comment` ⏎ `value`. Added
|
||||
`AssignPair::rhs_comments`. Worth recording: fixing comment motion is
|
||||
layered — each fix stops a comment drifting one step further, and the next
|
||||
resting place is only visible once the earlier one is gone.
|
||||
|
||||
**Two cross-cutting decisions.**
|
||||
|
||||
1. **One helper for printing a run of comments** (`Fmt::inline_comments`),
|
||||
used by the binary, ternary and assign paths. The reason is not tidiness: a
|
||||
naive `for c in comments { push(" "); push(comment) }` prints
|
||||
`// a // b` for two line comments, which re-lexes as *one* comment — comment
|
||||
loss the net would catch, but only as a refusal. The helper puts a hard line
|
||||
after any line comment. It is pinned by its own rejection test.
|
||||
2. **`take_around(mark)` clamps `mark`.** Writing it exposed that the two
|
||||
pre-existing raw `split_off(mark)` call sites can underflow — a nested
|
||||
construct's `take_trailing()` drains the pending list with `drain(..)`, so
|
||||
`len` can drop below `mark` and `split_off` would panic. Both call sites now
|
||||
go through the clamped helper. No `unwrap`/`expect`/`panic!` was added
|
||||
anywhere in library code.
|
||||
|
||||
**`verify.rs` was not touched, and did not need to be.** Confirmed with
|
||||
`git diff --quiet HEAD -- crates/vlog_formatter/src/verify.rs`. Every one of
|
||||
these bugs was the formatter emitting something the input did not say, so the
|
||||
net was right every time; there was never a case where the correct output
|
||||
failed a check. Added seven rejection tests anyway — one per root cause plus
|
||||
the comment-motion and merged-line-comment shapes — so that if someone later
|
||||
"fixes" a regression here by widening a normalization instead, those tests fail
|
||||
first. The `,`↔`or` test asserts *both* directions.
|
||||
|
||||
**Clippy fallout, and why the boxes are there.** Adding `after_op` to
|
||||
`Expr::Binary` and `TernaryComments` to `Expr::Ternary` grew `Expr` enough to
|
||||
trip `clippy::large_enum_variant` on `ItemKind` and `GenElse` (clean at `HEAD`,
|
||||
verified in a throwaway worktree). Boxing both comment groups fixes it and
|
||||
leaves those variants *smaller* than before this feature. Also dropped an
|
||||
unused `BinaryComments::is_empty` rather than keep a method with no caller.
|
||||
|
||||
Did not touch `tools/`, `corpus/` contents, `crates/vfmt/`, `CLAUDE.md`,
|
||||
`README.md` or `TODO.md` (no matching checkbox exists — these bugs were never
|
||||
backlog items). Did not run `git commit`/`git push`.
|
||||
|
||||
**Results:** `cargo test --workspace` **111 passed, 0 failed** (up from 98: +6
|
||||
`vlog_parser` parser unit, +7 `vlog_formatter` verification; the case table grew
|
||||
from 209 to 237 entries inside its single test). `cargo clippy --all-targets`
|
||||
silent. `cargo fmt --check` clean. Files touched:
|
||||
`crates/vlog_parser/src/{ast,parser}.rs`,
|
||||
`crates/vlog_formatter/src/format.rs`,
|
||||
`crates/vlog_formatter/tests/cases/{comments,statements,module_headers,instantiation}.cases`,
|
||||
`crates/vlog_formatter/tests/verification.rs`, this README.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-19 — QA agent
|
||||
|
||||
Verified every claim in the dev's Work log and Status/TODO against the code,
|
||||
a fresh release build, and independent corpus runs. **All claims pass.**
|
||||
Zero blocking findings — no masked corruption, no regression in the 237-case
|
||||
table, no panic reachable through the shipped binary.
|
||||
|
||||
**Tooling (exact numbers).**
|
||||
- `cargo test --workspace`: 111 passed, 0 failed (18+13+3+1+4+2+32+38 across
|
||||
the ten test binaries). `cargo clippy --all-targets`: silent. `cargo fmt
|
||||
--check`: clean.
|
||||
- `git diff --quiet HEAD -- crates/vlog_formatter/src/verify.rs`: exits 0 —
|
||||
byte-identical to `HEAD`, confirmed independently.
|
||||
- Case table: 209 → 237 entries, delta +28 split exactly
|
||||
comments+19/statements+4/module_headers+3/instantiation+2 per-file, matching
|
||||
the Work log's claim byte for byte.
|
||||
- `Box<BinaryComments>`/`Box<TernaryComments>` size claim reproduced exactly:
|
||||
built a throwaway crate against `vlog_parser` and measured
|
||||
`size_of::<BinaryComments>() == 48`, `size_of::<TernaryComments>() == 96`
|
||||
(raw structs); the *variant* sizes the Work log quotes (48 for
|
||||
`Expr::Binary`, 32 for `Expr::Ternary`) are the boxed-field arithmetic
|
||||
(8+24+8+8=48, 8+8+8+8=32) and check out.
|
||||
|
||||
**Corpus (independent re-run, fresh release builds).** Built the working
|
||||
tree's release binary and, in a separate `git worktree add --detach HEAD`
|
||||
(no `git stash` used — sandbox denied it), built `HEAD`'s release binary too,
|
||||
so both TSVs came from real independent runs rather than trusting the
|
||||
committed numbers:
|
||||
- `HEAD` binary: 46 verification-error, exit 1 — reproduces the pre-fix
|
||||
baseline exactly, including all 46 file paths and diagnostics quoted in the
|
||||
README's "The 46" table.
|
||||
- Working-tree binary: 0 verification-error, 468/820 parsed, 466
|
||||
would-reformat, exit 0.
|
||||
- Diffed both TSVs by path (`sort -k2,2 | cut -f1,2`, then `diff`): exactly 46
|
||||
`verification-error` lines removed and 46 `would-reformat` lines added, and
|
||||
the sorted path lists of the removed and added rows are byte-identical —
|
||||
confirmed with `diff removed_paths.txt added_paths.txt` (empty). No other
|
||||
row changed outcome.
|
||||
- Re-ran the working-tree binary a second time: output TSV byte-identical to
|
||||
the first (deterministic).
|
||||
- All four corpus repos `git status --porcelain` clean after both runs
|
||||
(only the untracked `.vfmt-corpus-rev` stamps, as documented).
|
||||
- Cleaned up the worktree (`git worktree remove --force`) after use; the main
|
||||
working tree's `git status` is unchanged from before this session.
|
||||
|
||||
**Adversarial round-trips (debug binary, scratchpad).** Built battery of
|
||||
hand-written inputs beyond the dev's own cases, each formatted twice and
|
||||
checked for idempotency:
|
||||
- Mixed 3-separator sens list `@(posedge a, negedge b or posedge c)`: each
|
||||
separator preserved, idempotent.
|
||||
- `#()` / `#(.W(8))` / absent, on both instantiations and module headers
|
||||
(including `module m #() (input a);`): all correct. (My first attempt used
|
||||
`#(.P(1))` on a module header, which is instantiation-override syntax, not
|
||||
legal in a header — parser correctly rejected it; not a bug, my test error.)
|
||||
- Two comments in one empty connection `.x(/* a */ /* b */)`: idempotent,
|
||||
both comments kept inside the parens.
|
||||
- Comment before the colon of a case label (`A // before colon\n:`) and after
|
||||
it (`A: // after colon`): both idempotent, sane placement.
|
||||
- Comments on *both* sides of a binary operator simultaneously
|
||||
(`a /* before */ && /* after */ b` and the line-comment variant): both
|
||||
idempotent — this exact combination isn't in the case table but the shared
|
||||
`inline_comments`/`BinaryComments{before,after}` machinery handles it
|
||||
correctly.
|
||||
- Block comment in an empty port list `module m (/* none */);`: idempotent.
|
||||
- Comment before the closing `}` of a concat/replication
|
||||
(`{a, b\n// c\n}`): **refuses cleanly** (exit 2, verification failure) —
|
||||
not one of the documented seven shapes (those cover `)`-closed lists, not
|
||||
`}`-closed ones), consistent with "refusal, not corruption."
|
||||
- Comments written between or after header `import` statements (a shape
|
||||
adjacent to bug C but not one of the documented seven — e.g. a comment on
|
||||
its own line between `import a::*;` and `import b::t;`, or a trailing
|
||||
comment on a non-final import): **refuses cleanly** (exit 2) rather than
|
||||
silently dropping or misplacing the comment. Non-blocking; flagging as a
|
||||
known gap in case a future corpus file exercises it — the README's
|
||||
Handshakes/Status section doesn't claim these are handled, and they aren't,
|
||||
correctly refusing instead of corrupting.
|
||||
|
||||
**Sabotage checks (2 of the 7 new rejection tests).** The 7 tests in
|
||||
`verification.rs` call `verify_equivalence` directly on hand-written
|
||||
`(input, output)` string pairs, so they exercise `verify.rs` alone — hacking
|
||||
`Fmt::inline_comments` (as suggested) would not touch them, since none of
|
||||
these seven go through the actual formatter. Adjusted the attack accordingly
|
||||
and sabotaged `verify.rs` itself twice, confirming each test is a real pin,
|
||||
not a vacuous pass:
|
||||
1. Widened `Item::matches` to treat the `,` symbol and `or` keyword as
|
||||
equivalent (a plausible future "forgive the spelling" mistake) →
|
||||
`an_event_list_comma_rewritten_as_or_is_still_rejected` failed with the
|
||||
expected panic message ("expected a divergence between..."). Reverted;
|
||||
`git diff --quiet HEAD -- crates/vlog_formatter/src/verify.rs` confirmed
|
||||
clean afterward.
|
||||
2. Added a `merge_adjacent_comments` pass in `lex_stream` that concatenates
|
||||
consecutive comment items (a plausible future "stop caring about comment
|
||||
splitting" mistake) → `two_line_comments_merged_onto_one_line_are_still_rejected`
|
||||
failed the same way. Reverted; `verify.rs` confirmed byte-identical to
|
||||
`HEAD` again.
|
||||
Both sabotages used only `verify.rs`; no other file was touched. Ran the full
|
||||
workspace suite after the final revert: 111 passed, 0 failed.
|
||||
|
||||
**`take_around` panic claim — reproduced the old panic directly**, not just
|
||||
read the code. Built `HEAD`'s parser in a separate worktree (pre-fix, with the
|
||||
two raw `pending_trailing.split_off(mark)` call sites) and constructed inputs
|
||||
that make a nested comment-harvest (`take_meta`/`take_trailing`, which
|
||||
unconditionally drain *all* of `pending_trailing`, not just what's past an
|
||||
outer `mark`) drain below an outer, already-captured `mark`:
|
||||
- `parse_binary_inner` site: `assign y = a + // note\n b(x) * c;` — the
|
||||
operator's own trailing comment (`// note`) gets pushed onto
|
||||
`pending_trailing`, inherited as a nonzero starting `mark` by the recursive
|
||||
`parse_binary(prec+1)` call for the right operand, then wiped out by the
|
||||
nested call argument's `take_meta()` before the next operator's harvest —
|
||||
`HEAD`'s binary panics: `` panicked while formatting: `at` split index
|
||||
(is 1) should be <= len (is 0) `` (exit 2, caught by `catch_unwind`, not a
|
||||
hard crash, but still a panic in library code). The working-tree binary
|
||||
formats it cleanly (exit 0) and idempotently.
|
||||
- `Expr::Paren` site: same idea one level deeper —
|
||||
`assign y = a + // note\n (b(x)) * c;` — reproduces the identical panic
|
||||
message on `HEAD`; the working-tree binary again formats cleanly and
|
||||
idempotently.
|
||||
Both call sites in the diff were read and confirmed to go through the new
|
||||
`take_around` helper, and both are now demonstrably panic-free on inputs that
|
||||
provably panicked before the fix. Cleaned up both worktrees afterward.
|
||||
|
||||
**Named-file acceptance and refusals — all confirmed.** Formatted all 10
|
||||
named corpus files into scratch copies (corpus files' md5 unchanged
|
||||
before/after every run); all 10 format, `--check` clean on the formatted
|
||||
result (fixed point). Spot-checked content, not just exit codes:
|
||||
`testbench_ez.v` line 44 keeps `picorv32 #() uut (`; `prim_clock_buf.sv` keeps
|
||||
both `lint_off`/`lint_on` pragmas inside `#( ... )`; `sync.sv` keeps
|
||||
`@(posedge clk_i, negedge rst_ni)`; `prim_alert_rxtx_tb.sv` keeps two separate
|
||||
`import` lines. The three documented remaining refusals (replication, compact
|
||||
bracket expression, comment between a continuous assignment's value and its
|
||||
`;`) all still refuse cleanly (exit 2, verification failure, no corruption).
|
||||
The ternary-branch case is confirmed fixed: `assign w = c ? a : // c\nb;`
|
||||
formats to a clean, idempotent `exit 0`.
|
||||
|
||||
**CLAUDE.md compliance.** Every `panic!`/`unwrap`/`expect` added in this diff
|
||||
is inside `#[cfg(test)] mod tests` in `parser.rs` (grepped the full diff for
|
||||
these patterns outside `+++`/test blocks — none found in library code paths).
|
||||
No `#[allow]` added anywhere. README has all seven required sections,
|
||||
Handshakes accurately describes every signature change I checked against the
|
||||
actual diff, and the Work log's specific factual claims (numbers, file
|
||||
paths, byte sizes) all independently verified as stated above.
|
||||
|
||||
**Overall disposition: PASS on every claim, no blocking findings.** The two
|
||||
non-blocking observations (concat/replication `}`-comment and header-import
|
||||
inter-statement comments both refuse rather than corrupt) are pre-existing
|
||||
gaps outside this feature's documented scope, not regressions — recorded here
|
||||
for visibility, not as required fixes.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-19 — lead. Verdict: accepted and committed as-is; no lead fixes
|
||||
needed. This round takes the 820-file corpus to zero verification errors
|
||||
and zero crashes — hard invariant #1 demonstrated at ecosystem scale.**
|
||||
|
||||
What distinguishes this round:
|
||||
|
||||
1. **The fixes are all "say what the input said."** Every one of the
|
||||
four root causes was the formatter inventing or discarding
|
||||
information (a separator, a `;`, an empty `#()`, a comment's
|
||||
position). The fixes make the AST carry the missing fact
|
||||
(`SensSep`, `Vec<Vec<String>>` imports, `Option<Vec>` params,
|
||||
comment fields) rather than special-casing the printer — the right
|
||||
layer every time.
|
||||
2. **verify.rs byte-identical to HEAD**, confirmed twice (dev and QA).
|
||||
The net was right on all 46 files; the 7 new rejection tests turn
|
||||
that judgment into pinned regression protection, and QA's sabotage
|
||||
checks prove they bite. This is hard-invariant #4 practiced, not
|
||||
just written down.
|
||||
3. **Discipline on discovery**: the same-root-cause module-header `#()`
|
||||
fix and the `take_around` panic clamp both rode along because the
|
||||
dev was already in that code — correctly judged; the panic claim was
|
||||
verified by QA the strong way (reproduce on pre-fix binary).
|
||||
4. Bug B's "one bug" turning into seven shapes (and the seventh only
|
||||
visible after six were fixed) is a good record of why comment
|
||||
attachment is the hardest part of this codebase — and why
|
||||
`Fmt::inline_comments` as the single printing path matters.
|
||||
|
||||
Dispositions on QA's non-blocking observations: both (concat
|
||||
`}`-comment, header-import inter-statement comments) join the
|
||||
documented-refusals list — refusals, not corruption; candidates for a
|
||||
future comments round alongside the two survivors from
|
||||
formatter-bug-fixes (replication, compact bracket, assign-value; the
|
||||
ternary one is fixed by this round's `TernaryComments`).
|
||||
|
||||
Corpus state after this round: 468/820 parse (57.1%), 466 would-reformat,
|
||||
2 ok-unchanged, 352 parse-error, **0 verification-error, 0 crash** —
|
||||
`corpus_check.sh` exits 0 for the first time. The remaining work is
|
||||
parse coverage (roadmap in README.md) and the LSP track (TODO §6).
|
||||
Reference in new issue
Block a user