Add comments-round: close the comment-attachment gaps

Meta.trailing is now Option<Comment> (line/col/span — delivers the
format-fences handshake; same-line fences stay deliberately inert),
and Meta::before_sep keeps a comment on its element's side of the
separator across every list kind, including the closing-bracket
buckets. take_before_sep is a no-op unless the cursor is on the
separator, which is why all 299 pre-existing cases stayed
byte-identical. Also fixes: EnumType::dangling comments parsed but
never printed (a latent invariant-#3 violation), the double-blank
between leading comments (six corpus files became fixed points), and
five documented expression refusals (replication interior,
compact-bracket operator position, assign-value, concat brace,
header imports via HeaderImport).

Reproducible acceptance metrics (HEAD-worktree control): line-
position comment injection refusals 2.3% -> 0.4%; exhaustive gap
probe 90 -> 22 refused; delimiter-position 61% -> 36%. Remaining
parked positions documented. verify.rs byte-identical; +7 rejection
tests; corpus 0 verification errors, 0 crashes, parse 468/820.

229 workspace tests, clippy silent. Dev: Opus agent; QA: Sonnet
agent (sabotage-verified pins, independent probes); review in
docs/features/comments-round/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-19 06:11:53 -07:00
1 parent 0ba29d4635
commit 982e37063b
9 files changed
+1318 -146

No files matched your search

+40 -9
View File
@@ -16,7 +16,17 @@ use crate::token::Comment;
#[derive(Debug, Clone, Default)]
pub struct Meta {
pub leading: Vec<Comment>,
pub trailing: Option<String>,
/// The comment written *after* the node and the separator that closes it
/// (`,` or `;`), on the same line. Several are merged into one, joined by
/// a space; the merged value keeps the first one's position and spans
/// from the first byte of the first to the last byte of the last.
pub trailing: Option<Comment>,
/// Comments written *between* the node and the separator that follows it
/// (`element /* c */,`). They print on the node's side of the separator,
/// which is where the source put them — printing them after it moves a
/// comment across a token and the safety net rejects the output. Empty
/// for a node no separator follows.
pub before_sep: Vec<Comment>,
pub blank_before: bool,
/// Attribute instances `(* ... *)` that preceded the node, verbatim.
pub attrs: Vec<RawText>,
@@ -119,11 +129,10 @@ pub enum ItemKind {
pub struct Module {
pub kw: String,
pub name: String,
/// 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>>,
/// One entry per `import` statement written in the header. 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<HeaderImport>,
/// `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>>,
@@ -137,6 +146,16 @@ pub struct Module {
pub end_label: Option<String>,
}
/// One `import` statement in a module header, with the comments written
/// around it. A header import is not an [`Item`], so it needs its own place
/// to keep them.
#[derive(Debug)]
pub struct HeaderImport {
pub meta: Meta,
/// The comma-separated paths of this one statement.
pub paths: Vec<String>,
}
#[derive(Debug)]
pub enum PortList {
/// No port list at all: `module m;`
@@ -331,6 +350,10 @@ pub enum SensList {
#[derive(Debug)]
pub struct SensItem {
/// Comments written around this item: `leading` before it (after the `(`
/// or the separator), `before_sep` between it and the separator that
/// follows — or the closing `)` for the last item.
pub meta: Meta,
/// The separator written before this item; `None` on the first item.
pub sep: Option<SensSep>,
pub edge: Option<String>,
@@ -390,6 +413,10 @@ pub struct Connection {
/// `None` for `.name` (implicit) and `.*`; `Some` for `.name(expr)`.
/// An explicitly empty connection `.name()` is `Some(Expr::Empty)`.
pub expr: Option<Expr>,
/// Comments written between the value and the connection's own `)`
/// (`.data_i (x /* verilator lint_off */)`). Printed back inside the
/// parens: after them they would sit in the enclosing list instead.
pub close_comments: Vec<Comment>,
/// Code extent of the connection.
pub span: TextRange,
}
@@ -406,7 +433,7 @@ pub struct GateInstantiation {
pub struct GateInstance {
pub meta: Meta,
pub name: Option<String>,
pub args: Vec<Expr>,
pub args: Vec<ExprItem>,
/// Code extent of the gate instance.
pub span: TextRange,
}
@@ -422,7 +449,9 @@ pub struct GenIf {
#[derive(Debug)]
pub enum GenElse {
If(Meta, GenIf),
/// `else if`: boxed because a `Meta` plus a whole `GenIf` inline makes
/// this variant several times the size of `Block`.
If(Meta, Box<GenIf>),
Block(GenBlock),
}
@@ -726,7 +755,9 @@ pub enum ExprKind {
Concat(Vec<ExprItem>),
Repl {
count: Box<Expr>,
inner: Vec<Expr>,
/// Elements carry their comments the way a concatenation's do, so a
/// comment inside a replication stays inside it.
inner: Vec<ExprItem>,
},
Paren {
inner: Box<Expr>,
+184 -41
View File
@@ -525,16 +525,48 @@ impl<'a> Parser<'a> {
leading.append(&mut tok.leading);
let blank_before =
leading.first().map(|c| c.blank_before).unwrap_or(self.tokens[self.pos].blank_before);
Meta { leading, trailing: None, blank_before, attrs: Vec::new() }
Meta { leading, blank_before, ..Meta::default() }
}
/// Harvest trailing comments accumulated since the last harvest.
fn take_trailing(&mut self) -> Option<String> {
if self.pending_trailing.is_empty() {
None
} else {
Some(self.pending_trailing.drain(..).map(|c| c.text).collect::<Vec<_>>().join(" "))
///
/// Several comments merge into one, joined by a space, as they always
/// have; the result keeps the first one's line/column (what the formatter
/// re-indents a multi-line one by) and spans the whole run.
fn take_trailing(&mut self) -> Option<Comment> {
let mut drained = self.pending_trailing.drain(..);
let mut first = drained.next()?;
for rest in drained {
first.text.push(' ');
first.text.push_str(&rest.text);
first.span.end = rest.span.end;
}
Some(first)
}
/// Move the comments written before the separator at the cursor onto the
/// element just parsed, so they print on the element's side of it.
///
/// A no-op when the cursor is not on that separator: the comments then
/// belong to the enclosing list's dangling bucket (before its closing
/// bracket) or to the next construct, and stealing them here would move
/// them backwards across a token.
fn take_before_sep(&mut self, meta: &mut Meta, sep: &str) {
if !self.cur().is_sym(sep) {
return;
}
self.take_before(meta);
}
/// The unconditional half of [`Parser::take_before_sep`], for callers that
/// recognize their own separator: an event list separates with a `,` or
/// with the `or` keyword, and both spellings occur in one list.
fn take_before(&mut self, meta: &mut Meta) {
if let Some(c) = meta.trailing.take() {
meta.before_sep.push(c);
}
let mut around = self.take_dangling();
meta.before_sep.append(&mut around);
}
/// Comments sitting right before a closing keyword (`end`, `endmodule`,
@@ -558,10 +590,14 @@ impl<'a> Parser<'a> {
/// Continue a comma-separated expression list whose first element is
/// already parsed, harvesting the comment written after each comma and
/// the one before the closing bracket.
fn parse_expr_list(&mut self, first: ExprItem) -> PResult<Vec<ExprItem>> {
/// the ones before `close` — the token that ends the list, which the
/// caller consumes (`}`, `)`, or the `:` of a case label list).
fn parse_expr_list(&mut self, first: ExprItem, close: &str) -> PResult<Vec<ExprItem>> {
let mut items = vec![first];
loop {
if let Some(last) = items.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
let more = self.eat_sym(",");
if let Some(last) = items.last_mut() {
if last.meta.trailing.is_none() {
@@ -569,6 +605,9 @@ impl<'a> Parser<'a> {
}
}
if !more {
if let Some(last) = items.last_mut() {
self.take_before_sep(&mut last.meta, close);
}
return Ok(items);
}
items.push(self.parse_expr_item()?);
@@ -909,7 +948,10 @@ impl<'a> Parser<'a> {
let name = self.expect_ident()?;
let mut imports = Vec::new();
while self.cur().is_kw("import") {
imports.push(self.parse_import_list()?);
let mut meta = self.take_meta();
let paths = self.parse_import_list()?;
meta.trailing = self.take_trailing();
imports.push(HeaderImport { meta, paths });
}
let mut param_ports = None;
let mut param_dangling = Vec::new();
@@ -920,6 +962,9 @@ impl<'a> Parser<'a> {
if !self.cur().is_sym(")") {
loop {
list.push(self.parse_param_port()?);
if let Some(last) = list.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
if !self.eat_sym(",") {
break;
}
@@ -1015,6 +1060,9 @@ impl<'a> Parser<'a> {
let mut ports = Vec::new();
loop {
ports.push(self.parse_ansi_port()?);
if let Some(last) = ports.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
if !self.eat_sym(",") {
break;
}
@@ -1041,6 +1089,7 @@ impl<'a> Parser<'a> {
let mut meta = self.take_meta();
let name = self.expect_ident()?;
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
meta.trailing = self.take_trailing();
ports.push(NonAnsiPort { meta, name, span });
@@ -1169,6 +1218,7 @@ impl<'a> Parser<'a> {
let unpacked = self.parse_dims()?;
let init = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None };
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
// Harvested on the last declarator too: a comment written before
// the `;` (`logic x /* verilator split_var */;`) belongs to the
@@ -1250,6 +1300,7 @@ impl<'a> Parser<'a> {
// Enum member ranges (`VAL[4]`) are rare; unsupported.
let value = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None };
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
meta.trailing = self.take_trailing();
members.push(EnumMember { meta, name, value, span });
@@ -1328,6 +1379,11 @@ impl<'a> Parser<'a> {
let rhs_comments = self.take_around(mark);
let rhs = self.parse_expr()?;
let span = self.span_from(start);
// The last pair's separator is the statement's `;`, so a comment
// written before it (`assign y = a /* c */;`) belongs on the
// value's side of it, not after it.
self.take_before_sep(&mut meta, ",");
self.take_before_sep(&mut meta, ";");
let more = self.eat_sym(",");
if more {
meta.trailing = self.take_trailing();
@@ -1387,6 +1443,9 @@ impl<'a> Parser<'a> {
if !self.cur().is_sym(")") {
loop {
list.push(self.parse_connection()?);
if let Some(last) = list.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
if !self.eat_sym(",") {
break;
}
@@ -1397,6 +1456,10 @@ impl<'a> Parser<'a> {
}
}
}
// Comments before the `)` of the override list belong inside it.
if let Some(last) = list.last_mut() {
self.take_before_sep(&mut last.meta, ")");
}
self.expect_sym(")")?;
params = Some(list);
}
@@ -1410,6 +1473,7 @@ impl<'a> Parser<'a> {
let conns = self.parse_connections()?;
self.expect_sym(")")?;
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
if more {
meta.trailing = self.take_trailing();
@@ -1431,6 +1495,9 @@ impl<'a> Parser<'a> {
let mut conns = Vec::new();
loop {
conns.push(self.parse_connection()?);
if let Some(last) = conns.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
if !self.eat_sym(",") {
break;
}
@@ -1440,11 +1507,10 @@ impl<'a> Parser<'a> {
}
}
}
// Comment on the closing-paren line belongs to the last conn.
// Comments before the closing `)` belong to the last conn: after
// it they would sit outside the connection list entirely.
if let Some(last) = conns.last_mut() {
if last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
self.take_before_sep(&mut last.meta, ")");
}
Ok(Connections::Named(conns))
} else {
@@ -1460,8 +1526,9 @@ impl<'a> Parser<'a> {
// An omitted connection (`u (a, , c)`) consumed no token, so
// this is the empty span where it would have started.
let span = self.span_from(start);
let more = self.eat_sym(",");
let mut meta = meta;
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
if more {
meta.trailing = self.take_trailing();
}
@@ -1470,6 +1537,9 @@ impl<'a> Parser<'a> {
break;
}
}
if let Some(last) = conns.last_mut() {
self.take_before_sep(&mut last.meta, ")");
}
Ok(Connections::Ordered(conns))
}
}
@@ -1482,11 +1552,18 @@ impl<'a> Parser<'a> {
if self.eat_sym(".") {
if self.eat_sym("*") {
let span = self.span_from(start);
return Ok(Connection { meta, name: "*".to_string(), expr: None, span });
return Ok(Connection {
meta,
name: "*".to_string(),
expr: None,
close_comments: Vec::new(),
span,
});
}
let name = self.expect_ident()?;
let mark = self.pending_trailing.len();
let paren_start = self.here();
let mut close_comments = Vec::new();
let expr = if self.eat_sym("(") {
if self.cur().is_sym(")") {
// `.name(/* unused */)`: the comments were written inside
@@ -1495,7 +1572,11 @@ impl<'a> Parser<'a> {
self.bump();
Some(self.expr_at(paren_start, ExprKind::Empty(inside)))
} else {
let value_mark = self.pending_trailing.len();
let e = self.parse_expr_or_type()?;
// `.name(x /* c */)`: written inside the parens, so it is
// printed inside them too.
close_comments = self.take_around(value_mark);
self.expect_sym(")")?;
Some(e)
}
@@ -1504,12 +1585,18 @@ impl<'a> Parser<'a> {
};
let span = self.span_from(start);
meta.trailing = self.take_trailing();
Ok(Connection { meta, name, expr, span })
Ok(Connection { meta, name, expr, close_comments, span })
} else {
let e = self.parse_expr_or_type()?;
let span = self.span_from(start);
meta.trailing = self.take_trailing();
Ok(Connection { meta, name: String::new(), expr: Some(e), span })
Ok(Connection {
meta,
name: String::new(),
expr: Some(e),
close_comments: Vec::new(),
span,
})
}
}
@@ -1542,15 +1629,12 @@ impl<'a> Parser<'a> {
self.expect_sym("(")?;
let mut args = Vec::new();
if !self.cur().is_sym(")") {
loop {
args.push(self.parse_expr()?);
if !self.eat_sym(",") {
break;
}
}
let first = self.parse_expr_item()?;
args = self.parse_expr_list(first, ")")?;
}
self.expect_sym(")")?;
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
if more {
meta.trailing = self.take_trailing();
@@ -1587,7 +1671,7 @@ impl<'a> Parser<'a> {
let meta = self.take_meta();
self.bump();
if self.cur().is_kw("if") {
Some(Box::new(GenElse::If(meta, self.parse_gen_if()?)))
Some(Box::new(GenElse::If(meta, Box::new(self.parse_gen_if()?))))
} else {
let _ = meta;
Some(Box::new(GenElse::Block(self.parse_gen_block()?)))
@@ -1629,7 +1713,7 @@ impl<'a> Parser<'a> {
Vec::new()
} else {
let first = self.parse_expr_item()?;
let labels = self.parse_expr_list(first)?;
let labels = self.parse_expr_list(first, ":")?;
self.expect_sym(":")?;
labels
};
@@ -1748,6 +1832,7 @@ impl<'a> Parser<'a> {
let unpacked = self.parse_dims()?;
let default = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None };
let span = self.span_from(start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
meta.trailing = self.take_trailing();
args.push(TfArg { meta, dir, ty, name, unpacked, default, span });
@@ -2100,7 +2185,7 @@ impl<'a> Parser<'a> {
Vec::new()
} else {
let first = self.parse_expr_item()?;
let labels = self.parse_expr_list(first)?;
let labels = self.parse_expr_list(first, ":")?;
self.expect_sym(":")?;
labels
};
@@ -2178,7 +2263,12 @@ impl<'a> Parser<'a> {
let start = self.here();
let name = self.expect_ident()?;
let expr = self.expr_at(start, ExprKind::Ident(name));
return Ok(SensList::List(vec![SensItem { sep: None, edge: None, expr }]));
return Ok(SensList::List(vec![SensItem {
meta: Meta::default(),
sep: None,
edge: None,
expr,
}]));
}
if self.cur().is_sym("(") && self.nth(1).is_sym("*") {
// `@( /* c */ * /* d */ )`: the comments belong to the star, not
@@ -2196,6 +2286,7 @@ impl<'a> Parser<'a> {
let mut items = Vec::new();
let mut sep = None;
loop {
let mut meta = self.take_meta();
let edge = {
let t = self.cur();
if t.is_kw("posedge") || t.is_kw("negedge") || t.is_kw("edge") {
@@ -2205,7 +2296,12 @@ impl<'a> Parser<'a> {
}
};
let expr = self.parse_expr()?;
items.push(SensItem { sep, edge, expr });
// Comments written before the separator — either spelling — or
// before the closing `)` stay on this item's side of it.
if self.cur().is_sym(",") || self.cur().is_kw("or") || self.cur().is_sym(")") {
self.take_before(&mut meta);
}
items.push(SensItem { meta, 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(",") {
@@ -2335,6 +2431,7 @@ impl<'a> Parser<'a> {
self.parse_expr()?
};
let item_span = self.span_from(item_start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
if more {
meta.trailing = self.take_trailing();
@@ -2345,9 +2442,7 @@ impl<'a> Parser<'a> {
}
}
if let Some(last) = ranges.last_mut() {
if last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
self.take_before_sep(&mut last.meta, "}");
}
self.expect_sym("}")?;
self.link()?;
@@ -2474,7 +2569,7 @@ impl<'a> Parser<'a> {
let first_expr = self.parse_expr_or_type()?;
let first =
ExprItem { meta, expr: first_expr, span: self.span_from(arg_start) };
args = self.parse_expr_list(first)?;
args = self.parse_expr_list(first, ")")?;
}
self.expect_sym(")")?;
expr = self.expr_at(start, ExprKind::Call { callee: Box::new(expr), args });
@@ -2581,10 +2676,8 @@ impl<'a> Parser<'a> {
if self.cur().is_sym("{") {
// Replication {N{a, b}}
self.bump();
let mut inner = vec![self.parse_expr()?];
while self.eat_sym(",") {
inner.push(self.parse_expr()?);
}
let inner_first = self.parse_expr_item()?;
let inner = self.parse_expr_list(inner_first, "}")?;
self.expect_sym("}")?;
self.expect_sym("}")?;
return Ok(self.expr_at(
@@ -2592,7 +2685,7 @@ impl<'a> Parser<'a> {
ExprKind::Repl { count: Box::new(first.expr), inner },
));
}
let items = self.parse_expr_list(first)?;
let items = self.parse_expr_list(first, "}")?;
self.expect_sym("}")?;
Ok(self.expr_at(start, ExprKind::Concat(items)))
}
@@ -2615,6 +2708,7 @@ impl<'a> Parser<'a> {
(None, key_or_val)
};
let item_span = self.span_from(item_start);
self.take_before_sep(&mut meta, ",");
let more = self.eat_sym(",");
if more {
meta.trailing = self.take_trailing();
@@ -2625,9 +2719,7 @@ impl<'a> Parser<'a> {
}
}
if let Some(last) = items.last_mut() {
if last.meta.trailing.is_none() {
last.meta.trailing = self.take_trailing();
}
self.take_before_sep(&mut last.meta, "}");
}
}
self.expect_sym("}")?;
@@ -3020,7 +3112,8 @@ mod tests {
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()]]);
let paths: Vec<&[String]> = m.imports.iter().map(|i| &i.paths[..]).collect();
assert_eq!(paths, vec![&["a::*".to_string()][..], &["b::t".into(), "c::u".into()][..]]);
}
#[test]
@@ -3075,6 +3168,56 @@ mod tests {
assert_eq!(comments.after.len(), 1, "one comment after the operator");
}
#[test]
fn a_comment_before_a_list_comma_lands_in_before_sep() {
let file = parse_ok("module m (input a /* pre */, /* post */ input b);\nendmodule");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let PortList::Ansi(ports) = &m.ports else { panic!("expected an ANSI port list") };
assert_eq!(ports[0].meta.before_sep.len(), 1, "written before the comma");
assert_eq!(ports[0].meta.before_sep[0].text, "/* pre */");
let trailing = ports[0].meta.trailing.as_ref().expect("written after the comma");
assert_eq!(trailing.text, "/* post */");
}
#[test]
fn a_comment_after_the_last_element_is_not_a_before_sep_comment() {
// No separator follows, so the comment stays where it always was —
// this is the case the whole existing suite pins, and the harvest must
// not start stealing it.
let file = parse_ok("module m (input a /* tail */);\nendmodule");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let PortList::Ansi(ports) = &m.ports else { panic!("expected an ANSI port list") };
assert!(ports[0].meta.before_sep.is_empty(), "nothing separates it from the `)`");
assert_eq!(ports[0].meta.trailing.as_ref().expect("a trailing comment").text, "/* tail */");
}
#[test]
fn a_trailing_comment_carries_its_own_span() {
// The handshake `docs/features/format-fences/README.md` asked for: a
// same-line comment now has a byte offset, so a fence written there
// can be located in the source.
let src = "module m;\n wire a; // vfmt: off\nendmodule\n";
let file = parse_ok(src);
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let trailing = m.items[0].meta.trailing.as_ref().expect("a trailing comment");
assert_eq!(&src[trailing.span.start as usize..trailing.span.end as usize], "// vfmt: off");
assert_eq!((trailing.line, trailing.col), (2, 11));
}
#[test]
fn several_trailing_comments_merge_into_one_spanning_run() {
let src = "module m;\n wire a; /* one */ /* two */\nendmodule\n";
let file = parse_ok(src);
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
let trailing = m.items[0].meta.trailing.as_ref().expect("a trailing comment");
assert_eq!(trailing.text, "/* one */ /* two */");
assert_eq!(
&src[trailing.span.start as usize..trailing.span.end as usize],
"/* one */ /* two */",
"the span runs from the first comment to the last"
);
}
// ------------------------------------------------------------------
// Error recovery
// ------------------------------------------------------------------