Fix comment drops before brackets and attribute/comment reordering
Resolves the owner's comment-drop report (comments-round-2). Three root causes: (1) a comment between a module header's imports and its #( landed as the first parameter port's leading comment, printed inside the brackets -- fixed by take_before_open (the opening-bracket twin of take_before_sep, no-op unless the cursor is on the bracket) feeding new bracket-comment slots on Module/Instantiation/Instance; (2) Meta kept attributes and leading comments in two lists and the formatter emitted list order, swapping (* attr *) with an adjacent comment -- fixed by merging on span.start, with the fence check hoisted so fenced items still emit attrs as source bytes only; (3) found in the sweep survivors: a lone instance's leading comments were parsed and never printed (latent invariant-#3 violation). Acceptance: the reported 14 corpus insertion failures -> 0; the exhaustive 62k-trial per-line sweep fixed 95 positions with 0 newly refusing; all 240 survivors are in families already parked by comments-round and refuse on HEAD too. verify.rs byte-identical (8 new rejection tests, sabotage-verified); corpus TSV md5 unchanged; fences suite untouched and green. 524 workspace tests. Dev: Opus agent; QA: Sonnet agent (14/14 reproduced, HEAD-diffed sweep, attack pass on every new slot); review in docs/features/comments-round-2/README.md. Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
832bf4afc6
commit
3a503e1cf7
7 files changed
+985
-24
No files matched your search
@@ -80,6 +80,13 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
|
||||
2.3% → 0.4%. Still refused (documented, not hacked around):
|
||||
`[a : b]`-style bracket interiors and a comment before a *procedural*
|
||||
statement's `;` — see `docs/features/comments-round/README.md`.
|
||||
→ Round 2 closed the two shapes a plain line-insertion sweep still hit
|
||||
(14 of 989 trials): a comment before a module/instantiation head's `#(`
|
||||
or `(` (four new `Vec<Comment>` fields), and a comment written next to
|
||||
an `(* attribute *)`, which `Fmt::leading` now interleaves by span
|
||||
instead of printing all comments then all attributes. Sweep 14 → 0; the
|
||||
exhaustive per-line sweep's survivors are the shapes parked above plus
|
||||
a comment before `else` — see `docs/features/comments-round-2/README.md`.
|
||||
- [x] **Two leading comments separated by one blank line come out
|
||||
separated by two** (format-fences QA find, pre-existing): `leading`
|
||||
pushes a HardLine after each comment and a BlankLine before the next.
|
||||
|
||||
@@ -243,15 +243,7 @@ impl<'a> Fmt<'a> {
|
||||
fn leading_comments(&self, meta: &Meta) -> Vec<Doc> {
|
||||
let mut docs = Vec::new();
|
||||
for c in &meta.leading {
|
||||
let doc = match self.slot(c) {
|
||||
Slot::Covered => continue,
|
||||
Slot::Opens(r) => self.verbatim(r),
|
||||
Slot::Normal => self.comment(c),
|
||||
};
|
||||
if !docs.is_empty() {
|
||||
docs.push(if c.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
}
|
||||
docs.push(doc);
|
||||
self.push_comment(&mut docs, c);
|
||||
}
|
||||
if !docs.is_empty() {
|
||||
docs.push(Doc::HardLine);
|
||||
@@ -259,16 +251,82 @@ impl<'a> Fmt<'a> {
|
||||
docs
|
||||
}
|
||||
|
||||
/// Leading comments (each on its own line) preceding a node.
|
||||
/// Append one leading comment — or, when it opens a fenced region, that
|
||||
/// region's source bytes — with the break that separates it from whatever
|
||||
/// precedes it. Covered comments are already inside emitted bytes.
|
||||
fn push_comment(&self, docs: &mut Vec<Doc>, c: &Comment) {
|
||||
let doc = match self.slot(c) {
|
||||
Slot::Covered => return,
|
||||
Slot::Opens(r) => self.verbatim(r),
|
||||
Slot::Normal => self.comment(c),
|
||||
};
|
||||
Self::push_leading(docs, doc, c.blank_before);
|
||||
}
|
||||
|
||||
/// Leading comments and `(* ... *)` attributes preceding a node, each on
|
||||
/// its own line, in the order the source wrote them.
|
||||
///
|
||||
/// The two are stored in separate lists but interleave in the source
|
||||
/// (`(* keep *)` ⏎ `// why` ⏎ `logic x;`), so they are merged by span:
|
||||
/// printing every comment and then every attribute moves a comment across
|
||||
/// an attribute in the token stream, which the safety net rejects.
|
||||
fn leading(&self, meta: &Meta) -> Vec<Doc> {
|
||||
let mut docs = self.leading_comments(meta);
|
||||
for attr in &meta.attrs {
|
||||
docs.push(self.raw_text(attr));
|
||||
let mut docs = Vec::new();
|
||||
let mut attrs = meta.attrs.iter().peekable();
|
||||
for c in &meta.leading {
|
||||
while let Some(attr) = attrs.next_if(|a| a.span.start < c.span.start) {
|
||||
Self::push_leading(&mut docs, self.raw_text(attr), false);
|
||||
}
|
||||
self.push_comment(&mut docs, c);
|
||||
}
|
||||
for attr in attrs {
|
||||
Self::push_leading(&mut docs, self.raw_text(attr), false);
|
||||
}
|
||||
if !docs.is_empty() {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs
|
||||
}
|
||||
|
||||
/// Append one leading comment or attribute, with the break that separates
|
||||
/// it from the previous one. The break goes *before* the second entry
|
||||
/// rather than after the first: a `HardLine` followed by a `BlankLine` is
|
||||
/// three newlines, so writing both turned one blank line into two.
|
||||
fn push_leading(docs: &mut Vec<Doc>, doc: Doc, blank_before: bool) {
|
||||
if !docs.is_empty() {
|
||||
docs.push(if blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
}
|
||||
docs.push(doc);
|
||||
}
|
||||
|
||||
/// Comments written between a construct's head and the bracket that opens
|
||||
/// one of its lists (`module m` ⏎ `// why` ⏎ `#(`, `sub u` ⏎ `// why` ⏎
|
||||
/// `(...)`). They print on the head's side of the bracket, which is where
|
||||
/// the source put them.
|
||||
///
|
||||
/// `on_fresh_line` says whether the caller has already broken the line;
|
||||
/// the return value says the same for whatever it emits next, since a line
|
||||
/// comment runs to end of line and the bracket cannot follow it.
|
||||
fn bracket_comments(
|
||||
&self,
|
||||
comments: &[Comment],
|
||||
docs: &mut Vec<Doc>,
|
||||
on_fresh_line: bool,
|
||||
) -> bool {
|
||||
let mut fresh = on_fresh_line;
|
||||
for c in comments {
|
||||
if !fresh {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.comment(c));
|
||||
fresh = is_line_comment(&c.text);
|
||||
if fresh {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
}
|
||||
fresh
|
||||
}
|
||||
|
||||
fn trailing(&self, meta: &Meta) -> Vec<Doc> {
|
||||
let mut docs = Vec::new();
|
||||
let ends_line = self.inline_comments(&meta.before_sep, &mut docs);
|
||||
@@ -479,8 +537,10 @@ impl<'a> Fmt<'a> {
|
||||
/// comment. Comments before the `off` fence are still emitted; comments
|
||||
/// are never dropped.
|
||||
fn item_docs(&self, item: &Item) -> Vec<Doc> {
|
||||
let mut docs = self.leading_comments(&item.meta);
|
||||
if self.is_fenced(item.span) {
|
||||
// The item's own bytes, its attributes included, are emitted
|
||||
// verbatim by the fence; only its leading comments are ours.
|
||||
let mut docs = self.leading_comments(&item.meta);
|
||||
// The last comment asked for a line break before code that is not
|
||||
// coming. Whoever emits the next unit separates it itself.
|
||||
if matches!(docs.last(), Some(Doc::HardLine)) {
|
||||
@@ -488,10 +548,7 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
return docs;
|
||||
}
|
||||
for attr in &item.meta.attrs {
|
||||
docs.push(self.raw_text(attr));
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
let mut docs = self.leading(&item.meta);
|
||||
docs.push(self.item_kind(&item.kind));
|
||||
docs.extend(self.trailing(&item.meta));
|
||||
docs
|
||||
@@ -581,6 +638,7 @@ impl<'a> Fmt<'a> {
|
||||
// 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;
|
||||
on_fresh_line = self.bracket_comments(&m.param_comments, &mut docs, on_fresh_line);
|
||||
// A written-but-empty `#()` is printed back; a missing one stays
|
||||
// missing.
|
||||
if let Some(params) = &m.param_ports {
|
||||
@@ -590,6 +648,7 @@ impl<'a> Fmt<'a> {
|
||||
docs.push(self.delimited_dangling("(", items, &m.param_dangling, ")", false));
|
||||
on_fresh_line = false;
|
||||
}
|
||||
let on_fresh_line = self.bracket_comments(&m.port_comments, &mut docs, on_fresh_line);
|
||||
match &m.ports {
|
||||
PortList::None => docs.push(text(";")),
|
||||
PortList::Empty => {
|
||||
@@ -1017,20 +1076,29 @@ impl<'a> Fmt<'a> {
|
||||
|
||||
fn instantiation(&self, inst: &Instantiation) -> Doc {
|
||||
let mut docs = vec![text(inst.module.clone())];
|
||||
let mut on_fresh_line = self.bracket_comments(&inst.param_comments, &mut docs, false);
|
||||
// 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(text(if on_fresh_line { "#" } else { " #" }));
|
||||
docs.push(self.delimited("(", items, ")", false));
|
||||
on_fresh_line = false;
|
||||
}
|
||||
docs.push(text(" "));
|
||||
if let [only] = &inst.instances[..] {
|
||||
// The common case: no extra indent level, so a connection list
|
||||
// that breaks lines up under the instance itself.
|
||||
// that breaks lines up under the instance itself. The comments
|
||||
// before the instance name print here — the multi-instance branch
|
||||
// below has `leading` for them, and this one had nowhere at all.
|
||||
if !self.bracket_comments(&only.meta.leading, &mut docs, on_fresh_line) {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.instance(only));
|
||||
} else {
|
||||
if !on_fresh_line {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
// Several instances share one declaration: keep them on one line
|
||||
// if they fit, otherwise one per line, indented under the head.
|
||||
let last = inst.instances.len() - 1;
|
||||
@@ -1069,7 +1137,9 @@ impl<'a> Fmt<'a> {
|
||||
docs.push(self.dim(d));
|
||||
}
|
||||
}
|
||||
docs.push(text(" "));
|
||||
if !self.bracket_comments(&instance.conn_comments, &mut docs, false) {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.connections(&instance.conns));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
@@ -980,3 +980,214 @@ endmodule
|
||||
module m;
|
||||
assign y = a inside {1 /* one */, 2};
|
||||
endmodule
|
||||
====
|
||||
# a comment before a module header's #( stays before it
|
||||
module m
|
||||
// why these defaults
|
||||
#(parameter int P = 1) (input a);
|
||||
endmodule
|
||||
----
|
||||
module m // why these defaults
|
||||
#(parameter int P = 1) (input a);
|
||||
endmodule
|
||||
====
|
||||
# a block comment before a module header's #( keeps the header on one line
|
||||
module m /* generic */ #(parameter int P = 1) (input a);
|
||||
endmodule
|
||||
----
|
||||
module m /* generic */ #(parameter int P = 1) (input a);
|
||||
endmodule
|
||||
====
|
||||
# a comment before a module header's port list stays before it
|
||||
module m
|
||||
import p::*;
|
||||
// the ports
|
||||
(input a);
|
||||
endmodule
|
||||
----
|
||||
module m
|
||||
import p::*;
|
||||
// the ports
|
||||
(input a);
|
||||
endmodule
|
||||
====
|
||||
# a comment before an instantiation's #( stays before it
|
||||
module m;
|
||||
sub
|
||||
// override the width
|
||||
#(.WIDTH(8)) u (.a(b));
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
sub // override the width
|
||||
#(.WIDTH(8)) u (.a(b));
|
||||
endmodule
|
||||
====
|
||||
# a comment before an instantiation's #( survives the override list breaking
|
||||
module m;
|
||||
sub
|
||||
// the long way round
|
||||
#(.AAAAAAAAAAAAAAAA(1), .BBBBBBBBBBBBBBBB(2), .CCCCCCCCCCCCCCCC(3), .DDDDDDDDDDDDDDDD(4)) u (.a(b));
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
sub // the long way round
|
||||
#(
|
||||
.AAAAAAAAAAAAAAAA(1),
|
||||
.BBBBBBBBBBBBBBBB(2),
|
||||
.CCCCCCCCCCCCCCCC(3),
|
||||
.DDDDDDDDDDDDDDDD(4)
|
||||
) u (.a(b));
|
||||
endmodule
|
||||
====
|
||||
# a comment before an instance's connection list stays before it
|
||||
module m;
|
||||
sub u
|
||||
// hook it up
|
||||
(.a(b));
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
sub u // hook it up
|
||||
(.a(b));
|
||||
endmodule
|
||||
====
|
||||
# a comment before an instantiation's #( inside a generate block
|
||||
module m;
|
||||
for (genvar i = 0; i < 4; i++) begin : g
|
||||
sub
|
||||
// per bit
|
||||
#(.W(i)) u (.a(b));
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
for (genvar i = 0; i < 4; i++) begin : g
|
||||
sub // per bit
|
||||
#(.W(i)) u (.a(b));
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a comment written after an attribute stays after it
|
||||
(* DONT_TOUCH = "yes" *)
|
||||
// keep the tool honest
|
||||
module m (input a);
|
||||
endmodule
|
||||
----
|
||||
(* DONT_TOUCH = "yes" *)
|
||||
// keep the tool honest
|
||||
module m (input a);
|
||||
endmodule
|
||||
====
|
||||
# an attribute written between two comments stays between them
|
||||
// before
|
||||
(* keep *)
|
||||
// after
|
||||
module m;
|
||||
wire x;
|
||||
endmodule
|
||||
----
|
||||
// before
|
||||
(* keep *)
|
||||
// after
|
||||
module m;
|
||||
wire x;
|
||||
endmodule
|
||||
====
|
||||
# an attribute between two comments on a declaration
|
||||
module m;
|
||||
// before
|
||||
(* keep *)
|
||||
// after
|
||||
logic x;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
// before
|
||||
(* keep *)
|
||||
// after
|
||||
logic x;
|
||||
endmodule
|
||||
====
|
||||
# a comment between two attributes stays between them
|
||||
module m;
|
||||
(* a *)
|
||||
// between
|
||||
(* b *)
|
||||
logic x;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
(* a *)
|
||||
// between
|
||||
(* b *)
|
||||
logic x;
|
||||
endmodule
|
||||
====
|
||||
# a comment after a statement's attribute stays after it
|
||||
module m;
|
||||
initial begin
|
||||
(* keep *)
|
||||
// after
|
||||
x = 1;
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
(* keep *)
|
||||
// after
|
||||
x = 1;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a comment after an attribute inside a generate block stays after it
|
||||
module m;
|
||||
if (1) begin : g
|
||||
(* keep *)
|
||||
// after
|
||||
logic x;
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
if (1) begin : g
|
||||
(* keep *)
|
||||
// after
|
||||
logic x;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# a blank line between an attribute and the comment after it survives
|
||||
(* keep *)
|
||||
|
||||
// after a blank
|
||||
module m;
|
||||
endmodule
|
||||
----
|
||||
(* keep *)
|
||||
|
||||
// after a blank
|
||||
module m;
|
||||
endmodule
|
||||
====
|
||||
# a comment before a lone instance's name stays before it
|
||||
module m;
|
||||
sub #(.W(1))
|
||||
// the instance
|
||||
u (.a(b));
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
sub #(.W(1)) // the instance
|
||||
u (.a(b));
|
||||
endmodule
|
||||
====
|
||||
# a block comment before a lone instance's name keeps it on one line
|
||||
module m;
|
||||
sub /* the one */ u (.a(b));
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
sub /* the one */ u (.a(b));
|
||||
endmodule
|
||||
@@ -431,3 +431,84 @@ fn a_line_comment_swallowing_a_list_comma_is_still_rejected() {
|
||||
let output = "module m (\n input logic a // why ,\n input logic b\n);\nendmodule\n";
|
||||
expect_divergence(input, output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_moved_past_a_module_headers_param_bracket_is_still_rejected() {
|
||||
// The comment used to fall through to the first parameter port, which puts
|
||||
// it *inside* the `#(...)` the source wrote it before.
|
||||
let input = "module m\n// why these defaults\n#(parameter int P = 1) (input a);\nendmodule\n";
|
||||
let output =
|
||||
"module m #(\n // why these defaults\n parameter int P = 1\n) (input a);\nendmodule\n";
|
||||
expect_divergence(input, output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_moved_past_a_module_headers_port_bracket_is_still_rejected() {
|
||||
// The port-list twin, which is what the corpus's `prim_lc_dec.sv` writes
|
||||
// between its header `import` and the `(`.
|
||||
let input = "module m\n import p::*;\n// the ports\n(input a);\nendmodule\n";
|
||||
let output = "module m\n import p::*;\n(\n // the ports\n input a\n);\nendmodule\n";
|
||||
expect_divergence(input, output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_moved_past_an_instantiations_param_bracket_is_still_rejected() {
|
||||
// Same shape one level down: between the module name and the `#(` of an
|
||||
// instantiation's parameter override list.
|
||||
let input = "module m;\n sub\n // override the width\n #(.WIDTH(8)) u (.a(b));\nendmodule\n";
|
||||
let output = "module m;\n sub #(\n // override the width\n .WIDTH(8)\n ) u (.a(b));\nendmodule\n";
|
||||
expect_divergence(input, output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_moved_past_an_instances_connection_bracket_is_still_rejected() {
|
||||
let input = "module m;\n sub u\n // hook it up\n (.a(b));\nendmodule\n";
|
||||
let output = "module m;\n sub u (\n // hook it up\n .a(b)\n );\nendmodule\n";
|
||||
expect_divergence(input, output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_swapped_with_an_attribute_is_still_rejected() {
|
||||
// `Meta` keeps attributes and leading comments in two lists; printing all
|
||||
// comments and then all attributes swaps a pair the source interleaved.
|
||||
// Both directions, because both spellings occur in the corpus.
|
||||
let input =
|
||||
"(* DONT_TOUCH = \"yes\" *)\n// keep the tool honest\nmodule m (input a);\nendmodule\n";
|
||||
let output =
|
||||
"// keep the tool honest\n(* DONT_TOUCH = \"yes\" *)\nmodule m (input a);\nendmodule\n";
|
||||
expect_divergence(input, output);
|
||||
expect_divergence(output, input);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_attribute_hoisted_past_a_comment_that_preceded_it_is_still_rejected() {
|
||||
// Three-way interleave: only the middle attribute moves, which a
|
||||
// "sort the comments, then append the attributes" printer would do.
|
||||
let input = "module m;\n (* a *)\n // between\n (* b *)\n logic x;\nendmodule\n";
|
||||
let output = "module m;\n (* a *)\n (* b *)\n // between\n logic x;\nendmodule\n";
|
||||
expect_divergence(input, output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_bracket_comment_is_still_rejected() {
|
||||
// The failure mode the new `Vec<Comment>` fields must never regress into:
|
||||
// harvesting the comment and then never printing it (hard invariant #3).
|
||||
let input = "module m\n// why these defaults\n#(parameter int P = 1) (input a);\nendmodule\n";
|
||||
let output = "module m #(parameter int P = 1) (input a);\nendmodule\n";
|
||||
expect_divergence(input, output);
|
||||
|
||||
let input = "module m;\n sub u\n // hook it up\n (.a(b));\nendmodule\n";
|
||||
let output = "module m;\n sub u (.a(b));\nendmodule\n";
|
||||
expect_divergence(input, output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_instance_name_comment_is_still_rejected() {
|
||||
// The single-instance branch of `instantiation` printed the instance
|
||||
// without its `Meta`, so a comment between the `#(...)` and the instance
|
||||
// name was parsed and never emitted — hard invariant #3, caught only
|
||||
// because the net refused the file.
|
||||
let input = "module m;\n sub #(.W(1))\n // the instance\n u (.a(b));\nendmodule\n";
|
||||
let output = "module m;\n sub #(.W(1)) u (.a(b));\nendmodule\n";
|
||||
expect_divergence(input, output);
|
||||
}
|
||||
@@ -175,11 +175,17 @@ pub struct Module {
|
||||
/// write several (`module m import a::*; import b::t; (...)`), and merging
|
||||
/// them into one statement would replace a `;` with a `,`.
|
||||
pub imports: Vec<HeaderImport>,
|
||||
/// Comments written between the header's name (or its last `import`) and
|
||||
/// the `#` of the parameter port list. Empty when the header wrote none.
|
||||
pub param_comments: Vec<Comment>,
|
||||
/// `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>,
|
||||
/// Comments written between whatever precedes the port list and its `(`.
|
||||
/// Empty when the header wrote no parenthesized port list.
|
||||
pub port_comments: Vec<Comment>,
|
||||
pub ports: PortList,
|
||||
/// Comments written after the last port and before the `)`.
|
||||
pub port_dangling: Vec<Comment>,
|
||||
@@ -434,6 +440,9 @@ pub struct Instantiation {
|
||||
/// with its `::` glued, so there the slice matches `module` only modulo
|
||||
/// the whitespace the source may have written around the `::`.
|
||||
pub module_span: TextRange,
|
||||
/// Comments written between the module name and the `#` of the parameter
|
||||
/// override list. Empty when the source wrote no `#(...)`.
|
||||
pub param_comments: Vec<Comment>,
|
||||
/// 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.
|
||||
@@ -448,6 +457,9 @@ pub struct Instance {
|
||||
/// Byte range of `name`.
|
||||
pub name_span: TextRange,
|
||||
pub dims: Vec<Dim>,
|
||||
/// Comments written between the instance name (or its dimensions) and the
|
||||
/// `(` opening its connection list.
|
||||
pub conn_comments: Vec<Comment>,
|
||||
pub conns: Connections,
|
||||
/// Code extent of the instance, its connection list included.
|
||||
pub span: TextRange,
|
||||
|
||||
@@ -586,6 +586,20 @@ impl<'a> Parser<'a> {
|
||||
meta.before_sep.append(&mut around);
|
||||
}
|
||||
|
||||
/// Comments written just before an opening bracket the caller is about to
|
||||
/// consume (`module m` ⏎ `// why` ⏎ `#(`).
|
||||
///
|
||||
/// A no-op unless the cursor is on that bracket, for the same reason
|
||||
/// [`Parser::take_before_sep`] is: a construct that wrote no such bracket
|
||||
/// must leave the comments for whoever comes next, and stealing them here
|
||||
/// would move them backwards across a token.
|
||||
fn take_before_open(&mut self, open: &str) -> Vec<Comment> {
|
||||
if !self.cur().is_sym(open) {
|
||||
return Vec::new();
|
||||
}
|
||||
self.take_dangling()
|
||||
}
|
||||
|
||||
/// Comments sitting right before a closing keyword (`end`, `endmodule`,
|
||||
/// ...) — they belong inside the enclosing construct.
|
||||
fn take_dangling(&mut self) -> Vec<Comment> {
|
||||
@@ -976,6 +990,7 @@ impl<'a> Parser<'a> {
|
||||
meta.trailing = self.take_trailing();
|
||||
imports.push(HeaderImport { meta, paths });
|
||||
}
|
||||
let param_comments = self.take_before_open("#");
|
||||
let mut param_ports = None;
|
||||
let mut param_dangling = Vec::new();
|
||||
if self.cur().is_sym("#") {
|
||||
@@ -1002,6 +1017,7 @@ impl<'a> Parser<'a> {
|
||||
self.expect_sym(")")?;
|
||||
param_ports = Some(list);
|
||||
}
|
||||
let port_comments = self.take_before_open("(");
|
||||
let (ports, port_dangling) = self.parse_port_list()?;
|
||||
self.expect_sym(";")?;
|
||||
let mut items = Vec::new();
|
||||
@@ -1016,8 +1032,10 @@ impl<'a> Parser<'a> {
|
||||
name,
|
||||
name_span,
|
||||
imports,
|
||||
param_comments,
|
||||
param_ports,
|
||||
param_dangling,
|
||||
port_comments,
|
||||
ports,
|
||||
port_dangling,
|
||||
items,
|
||||
@@ -1465,6 +1483,7 @@ impl<'a> Parser<'a> {
|
||||
module.push_str(&self.expect_ident()?);
|
||||
}
|
||||
let module_span = self.span_from(module_start);
|
||||
let param_comments = self.take_before_open("#");
|
||||
let mut params = None;
|
||||
if self.cur().is_sym("#") {
|
||||
self.bump();
|
||||
@@ -1499,6 +1518,7 @@ impl<'a> Parser<'a> {
|
||||
let mut meta = self.take_meta();
|
||||
let Name { text: name, span: name_span } = self.expect_name()?;
|
||||
let dims = self.parse_dims()?;
|
||||
let conn_comments = self.take_before_open("(");
|
||||
self.expect_sym("(")?;
|
||||
let conns = self.parse_connections()?;
|
||||
self.expect_sym(")")?;
|
||||
@@ -1508,13 +1528,13 @@ impl<'a> Parser<'a> {
|
||||
if more {
|
||||
meta.trailing = self.take_trailing();
|
||||
}
|
||||
instances.push(Instance { meta, name, name_span, dims, conns, span });
|
||||
instances.push(Instance { meta, name, name_span, dims, conn_comments, conns, span });
|
||||
if !more {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.expect_sym(";")?;
|
||||
Ok(Instantiation { module, module_span, params, instances })
|
||||
Ok(Instantiation { module, module_span, param_comments, params, instances })
|
||||
}
|
||||
|
||||
fn parse_connections(&mut self) -> PResult<Connections> {
|
||||
@@ -3291,6 +3311,59 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_before_a_headers_brackets_land_on_the_module() {
|
||||
let src = "module m\n// params\n#(parameter int P = 1)\n// ports\n(input a);\nendmodule\n";
|
||||
let file = parse_ok(src);
|
||||
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
|
||||
assert_eq!(m.param_comments.len(), 1);
|
||||
assert_eq!(m.param_comments[0].text, "// params");
|
||||
assert_eq!(m.port_comments.len(), 1);
|
||||
assert_eq!(m.port_comments[0].text, "// ports");
|
||||
let params = m.param_ports.as_ref().expect("a parameter port list");
|
||||
assert!(params[0].meta.leading.is_empty(), "not the first parameter's leading comment");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_without_brackets_keeps_its_comment_for_the_next_construct() {
|
||||
// `take_before_open` is a no-op unless the bracket is actually there,
|
||||
// so a module that writes neither `#(` nor `(` must not steal the
|
||||
// comment that belongs to its first item.
|
||||
let src = "module m;\n// the data bus\nwire x;\nendmodule\n";
|
||||
let file = parse_ok(src);
|
||||
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
|
||||
assert!(m.param_comments.is_empty());
|
||||
assert!(m.port_comments.is_empty());
|
||||
assert_eq!(m.items[0].meta.leading[0].text, "// the data bus");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_before_an_instantiations_brackets_land_on_it() {
|
||||
let src = "module m;\nsub\n// params\n#(.W(8)) u\n// conns\n(.a(b));\nendmodule\n";
|
||||
let file = parse_ok(src);
|
||||
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") };
|
||||
let ItemKind::Instantiation(inst) = &m.items[0].kind else {
|
||||
panic!("expected an instantiation")
|
||||
};
|
||||
assert_eq!(inst.param_comments.len(), 1);
|
||||
assert_eq!(inst.param_comments[0].text, "// params");
|
||||
assert_eq!(inst.instances[0].conn_comments.len(), 1);
|
||||
assert_eq!(inst.instances[0].conn_comments[0].text, "// conns");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_attribute_and_the_comments_around_it_keep_their_source_order() {
|
||||
// The formatter merges the two lists by span, so both must carry
|
||||
// offsets that put the attribute between the comments.
|
||||
let src = "// before\n(* keep *)\n// after\nmodule m;\nendmodule\n";
|
||||
let file = parse_ok(src);
|
||||
let meta = &file.items[0].meta;
|
||||
assert_eq!(meta.attrs.len(), 1);
|
||||
assert_eq!(meta.leading.len(), 2);
|
||||
assert!(meta.leading[0].span.start < meta.attrs[0].span.start);
|
||||
assert!(meta.attrs[0].span.start < meta.leading[1].span.start);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Error recovery
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,507 @@
|
||||
# comments-round-2
|
||||
|
||||
## Goal
|
||||
|
||||
Close the last two comment-attachment gaps that ordinary RTL still trips over.
|
||||
`comments-round` fixed comments *inside* lists and parked "a comment before a
|
||||
construct's opening bracket" as a shape nobody writes; the corpus disagreed. A
|
||||
sweep that inserts one `// marker` line at lines len/3 and len/2 of every
|
||||
formattable corpus file refused **14 files**, in exactly two shapes: a comment
|
||||
between a module/instantiation head and the `#(` or `(` that follows it
|
||||
(10 files), and a comment written next to an `(* attribute *)`, which came out
|
||||
on the wrong side of it (4 files). Both are refusals, not corruption — the
|
||||
safety net was right both times — but a file `vfmt` cannot format is a file
|
||||
`vfmt` cannot format. Measuring the fix turned up a third, quieter bug in the
|
||||
same family: `instantiation`'s single-instance branch never read the instance's
|
||||
`Meta`, so a comment before a lone instance's name was parsed and then dropped
|
||||
(hard invariant #3, visible only because the net refused the file). **Result:
|
||||
14 refusals → 0 on the acceptance sweep, 335 → 240 on an exhaustive one with 0
|
||||
new refusals, `verify.rs` byte-identical to `HEAD` and the corpus TSV md5
|
||||
unchanged.**
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A comment stays lexically between the two tokens it was written between.**
|
||||
That is the whole spec, and it is what `verify_equivalence` checks. Every fix
|
||||
here gives the comment a place to live in the AST at the position the source
|
||||
put it; not one of them relaxes a check.
|
||||
- **An opening bracket is a token like any other.** `module m` ⏎ `// why` ⏎
|
||||
`#(...)` and `module m #(` ⏎ `// why` ⏎ `...)` are different streams. The
|
||||
first is what `prim_mubi*_dec.sv` writes once a marker lands there, and the
|
||||
parser now records which one it saw instead of letting the comment fall
|
||||
through to the first element of the list.
|
||||
- **Attributes and leading comments interleave, so their relative order is
|
||||
data, not a formatting choice.** `Meta` keeps them in two lists (`attrs` and
|
||||
`leading`) because they are different kinds of thing, but both carry byte
|
||||
spans, and the source order is recoverable from those spans. Printing all
|
||||
comments and then all attributes silently reorders a `(* DONT_TOUCH *)`
|
||||
against the comment explaining it.
|
||||
- **"Harvest only when the bracket is actually there."** `take_before_open` is
|
||||
a no-op unless the cursor is on the bracket named, exactly as
|
||||
`take_before_sep` is a no-op unless the cursor is on the separator. A module
|
||||
that writes no `#(` must leave the comment for whoever comes next — which is
|
||||
why the whole 512-test suite stayed byte-for-byte green.
|
||||
- **A line comment runs to end of line**, so the bracket that follows one goes
|
||||
on the next line. `sub u // why` ⏎ `(.a(b));` is ugly and faithful;
|
||||
`sub u // why (.a(b));` would delete the connection list into the comment.
|
||||
- **A header that has broken to column 0 keeps the bracket at column 0.** The
|
||||
module printer already does this after an `import` block ("the usual single
|
||||
space before `#(`/`(` is dropped"); a line comment in the same position takes
|
||||
the same path, so `module m // why` ⏎ `#(...)` is the existing spelling, not
|
||||
a new one.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Changed in `vlog_parser::ast` (consumed by `vlog_formatter::format`):**
|
||||
|
||||
| item | before | after |
|
||||
|---|---|---|
|
||||
| `Module` | — | new `param_comments: Vec<Comment>` — comments between the header's name (or its last `import`) and the `#` of the parameter port list. Empty when the header wrote no `#(`. |
|
||||
| `Module` | — | new `port_comments: Vec<Comment>` — comments between whatever precedes the port list and its `(`. Empty when the header wrote no parenthesized port list. |
|
||||
| `Instantiation` | — | new `param_comments: Vec<Comment>` — comments between the module name and the `#` of the override list. |
|
||||
| `Instance` | — | new `conn_comments: Vec<Comment>` — comments between the instance name (or its dimensions) and the `(` of its connection list. |
|
||||
|
||||
All four are plain `Vec<Comment>` beside existing `Vec`s; no variant grew, so
|
||||
`clippy::large_enum_variant` stayed silent.
|
||||
|
||||
New parser helper: `Parser::take_before_open(open) -> Vec<Comment>` — the
|
||||
opening-bracket twin of `take_before_sep`, a no-op unless the cursor is on that
|
||||
bracket.
|
||||
|
||||
New formatter helpers: `Fmt::bracket_comments` (prints one of the four buckets
|
||||
— or a lone instance's leading comments, which sit in the same head position —
|
||||
and reports whether the caller must start the next token on a fresh line),
|
||||
`Fmt::push_leading` (one leading entry plus the break before it) and
|
||||
`Fmt::push_comment` (the fence-aware half of the old `leading_comments` loop).
|
||||
`Fmt::leading` now merges `meta.leading` and `meta.attrs` by span instead of
|
||||
concatenating them.
|
||||
|
||||
**`Fmt::instantiation`'s single-instance branch now reads `Instance.meta`.** It
|
||||
printed `self.instance(only)` bare, so the instance's leading comments were
|
||||
parsed and never emitted; the multi-instance branch beside it has always called
|
||||
`self.leading`. Only the leading comments are printed here — `before_sep` and
|
||||
`trailing` stay empty for a lone instance, since nothing separates it — so the
|
||||
two branches cannot double-print.
|
||||
|
||||
**`Fmt::item_docs` restructured, not re-specified.** It used to emit leading
|
||||
comments, check the fence, then emit attributes; it now checks the fence first
|
||||
and takes the merged `leading()` on the normal path. The fenced path is
|
||||
unchanged (an item's attributes are inside its span, so a fence emits them as
|
||||
source bytes and the formatter must not print them again).
|
||||
|
||||
**Consumed from `verify.rs`: nothing new. No normalization was added,
|
||||
broadened or weakened** — `git diff --quiet -- crates/vlog_formatter/src/verify.rs`
|
||||
exits 0, so CLAUDE.md hard invariant #4 does not bind this round. Seven new
|
||||
**rejection** tests were added to `tests/verification.rs` anyway, one per shape
|
||||
fixed, each asserting that the "corrupted" output a widened normalization would
|
||||
have forgiven is still refused. The attribute swap asserts both directions, and
|
||||
one test pins the *dropped*-comment failure mode the four new `Vec<Comment>`
|
||||
fields could regress into (hard invariant #3).
|
||||
|
||||
**Format fences (`docs/features/format-fences/README.md`): unchanged, and
|
||||
verified so.** `fence::scan_scope` walks item-level leading comments only, so a
|
||||
`// vfmt: off` written in one of the four new bracket positions opens no region
|
||||
— exactly as it opened none when the same comment used to land in the first
|
||||
parameter port's `meta.leading`. The difference is that such a file is now
|
||||
formatted (fence inert, output verified) instead of refused. `fence.rs`,
|
||||
`tests/fences.rs` and `fences.cases` are untouched and green.
|
||||
|
||||
**Recursion/chain budgets (`docs/features/recursion-limit/README.md`):**
|
||||
unaffected. Four `Vec<Comment>` fields on existing nodes; nothing recurses,
|
||||
nothing nests, root-to-leaf depth is unchanged.
|
||||
|
||||
**`line_starts_inside_string` is still the one in-string-break definition** —
|
||||
untouched; nothing here parses comment or string text.
|
||||
|
||||
**Not touched, by scope:** `crates/vfmt`, `crates/vfmt_core`,
|
||||
`crates/vfmt_server`, `crates/vlog_linter`, `crates/vlog_semantic`, `editors/`,
|
||||
`tools/`, `corpus/`, `verify.rs`. `vfmt_server`'s tests consume `format_source`
|
||||
and stayed green. `cargo fmt --all` rewrote exactly one file, this round's own
|
||||
`tests/verification.rs` (confirmed against `cargo fmt --all --check` beforehand,
|
||||
which listed only that file).
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] **Bucket 1 — comment before an opening bracket.** Four positions, four
|
||||
fields: a module header's `#(` and its port-list `(`, an instantiation's
|
||||
`#(` and an instance's connection `(`. 10 of the 14 corpus refusals.
|
||||
- [x] **Bucket 2 — comment adjacent to an `(* attribute *)`.** `Fmt::leading`
|
||||
merges comments and attributes by span. Covers items *and* statements
|
||||
(both go through `Meta.attrs`), so the generate-block and
|
||||
procedural-block twins came free. 4 of the 14.
|
||||
- [x] **Found while measuring — a comment before a lone instance's name was
|
||||
parsed and never printed.** `instantiation`'s single-instance branch
|
||||
called `self.instance(only)` without ever reading `only.meta`; the
|
||||
multi-instance branch beside it does. `sub #(.W(1))` ⏎ `// the instance`
|
||||
⏎ `u (...)` therefore lost the comment — hard invariant #3, refused by
|
||||
the net every time, and 6 more corpus positions. Fixed by routing that
|
||||
`Meta`'s leading comments through the same `bracket_comments` helper.
|
||||
- [x] 16 new `.cases` entries in `comments.cases` (77 → 93; 299 → 315 overall).
|
||||
- [x] 8 new rejection tests in `tests/verification.rs` (39 → 47).
|
||||
- [x] 4 new parser unit tests, including the "no bracket, no harvest" one that
|
||||
pins why the existing suite did not churn.
|
||||
- [x] Sweep acceptance: **14 → 0** on the lead's protocol, reproduced against a
|
||||
`HEAD` worktree binary first.
|
||||
- [x] `cargo test --workspace` 524 passed (512 baseline + 12), clippy silent,
|
||||
fmt clean, `verify.rs` byte-identical to `HEAD`.
|
||||
- [x] Corpus TSV md5 unchanged: `aa982463f68c1a3568c02a0fc5e0c455`, 0
|
||||
verification errors, 0 crashes, script exit 0.
|
||||
- [x] `TODO.md` §2: the comment item's note updated with what this round
|
||||
closed and what is still parked.
|
||||
- [ ] **Still parked, inherited from `comments-round`** — bracket *interiors*
|
||||
(`x[a /* c */ : b]`, `logic [7 /* c */ : 0]`), a comment before a
|
||||
*procedural* statement's `;`, a comment before `else`, and the bare name
|
||||
lists (`genvar i /* c */, j;`). All refusals, never corruption. The
|
||||
exhaustive sweep shows the `else` one is by far the biggest of them.
|
||||
- [ ] **Not done — the remaining head positions**, the rest of bucket 1's
|
||||
family: a comment before an opening `{` / `'{` (a concatenation, an
|
||||
assignment pattern, a struct body), before an `if`'s `(`, and between a
|
||||
function's return type and its name. Same shape as bucket 1 and each is
|
||||
its own slot, but none is reachable by the lead's sweep and the
|
||||
exhaustive one says they are rare; this round stopped at the positions
|
||||
the corpus actually refuses on. Counts in Measurements.
|
||||
|
||||
## Measurements
|
||||
|
||||
**The lead's sweep, reproduced and re-run.** One `// marker` line inserted so
|
||||
that it becomes line len/3 (and, separately, line len/2) of every corpus file
|
||||
that formats cleanly unmodified; formatted through
|
||||
`vfmt --stdin-filename <path> -`. A trial is discarded when the insertion breaks
|
||||
the *parse* — a comment dropped into a backslash-continued macro body genuinely
|
||||
changes what the file says, and that is the harness's doing, not the
|
||||
formatter's. Script in the session scratchpad (`sweep.py`); not checked in, as
|
||||
none of the earlier rounds' harnesses were.
|
||||
|
||||
| | before (`HEAD` worktree, c8b936a) | after |
|
||||
|---|---|---|
|
||||
| formattable files | 501 | 501 |
|
||||
| usable trials | 989 | 989 |
|
||||
| discarded (insertion broke the parse) | 11 | 11 |
|
||||
| **verification refusals** | **14** | **0** |
|
||||
|
||||
The 14 are the lead's 14, file for file and line for line — 10 `prim_*_dec.sv` /
|
||||
`prim_lc_dec.sv` (bucket 1) and 4 `prim_xilinx` / `read.sv` (bucket 2). The
|
||||
trial count differs from the brief's 934 because the file set and the
|
||||
parse-error accounting are this harness's own; the failure list is identical,
|
||||
which is the part that matters.
|
||||
|
||||
**Exhaustive line sweep.** The same insertion before *every* line of every
|
||||
formattable corpus file, run on both binaries — because "0 refusals at two
|
||||
sample points per file" is a weaker claim than it sounds, and because it is the
|
||||
only way to say honestly whether anything got *worse*. Script `dense.py`, same
|
||||
scratchpad.
|
||||
|
||||
| | before (`HEAD`) | after |
|
||||
|---|---|---|
|
||||
| usable trials | 62 407 | 62 407 |
|
||||
| discarded (insertion broke the parse) | 967 | 967 |
|
||||
| **verification refusals** | **335** (0.54%) | **240** (0.38%) |
|
||||
|
||||
Diffed by `file:line`, not by count: **95 positions fixed, 0 positions newly
|
||||
refusing.** The 95 are exactly the three shapes this round names — 46 before a
|
||||
`#(`, 22 an attribute/comment swap, 21 before an instantiation's or header's
|
||||
`(`, 6 before a lone instance's name.
|
||||
|
||||
The 240 survivors, bucketed by the token the output has where the input has the
|
||||
comment. **None is a new bucket**; every one is a head or interior position of
|
||||
the already-parked families:
|
||||
|
||||
| survivors | shape | disposition |
|
||||
|---|---|---|
|
||||
| 89 | before an `else` keyword | parked by `comments-round`: the else-branch `Meta` is read as `_meta` and never printed. A layout decision, not plumbing. |
|
||||
| 74 | before an opening `{` (58) or `'{` (16) | bucket 1's family, other members: a concatenation, an assignment pattern, a struct body. |
|
||||
| 49 | before an identifier | 36 of them one generated package (`prim_secded_pkg.sv`) splitting a function's return type from its name; the rest are expression positions. |
|
||||
| 20 | before a `)` (13) or a `(` (7) | remaining head positions (`if (`, a call's `(`) and list-closing brackets in expressions. |
|
||||
| 8 | before `=`, `begin`, a number, `$signed`, `!` | expression and statement interiors — the `comments-round` parked list. |
|
||||
|
||||
Every survivor refuses on `HEAD` too, at the same position. Refusals, never
|
||||
corruption: the net caught all 240.
|
||||
|
||||
## Corpus results
|
||||
|
||||
`./tools/corpus_check.sh corpus`, release build:
|
||||
|
||||
```
|
||||
ok-unchanged 8 1.0% (unchanged)
|
||||
would-reformat 460 56.1% (unchanged)
|
||||
parse-error 352 42.9% (unchanged)
|
||||
verification-error 0 0.0%
|
||||
other-error 0 0.0%
|
||||
crash 0 0.0%
|
||||
total 820 100.0%
|
||||
```
|
||||
|
||||
Script exit status 0. TSV md5 **`aa982463f68c1a3568c02a0fc5e0c455`** —
|
||||
byte-identical to the `comments-round` baseline, so no corpus file moved
|
||||
category and no by-path delta exists to report. That is the expected result and
|
||||
it was checked, not assumed: no corpus file writes any of these three shapes
|
||||
*uninserted*, which is exactly why they needed an insertion sweep to find at
|
||||
all.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-19 — dev agent
|
||||
|
||||
- Read `CLAUDE.md`, the `comments-round` and `corpus-bugs` READMEs, and
|
||||
`TODO.md` §2 before touching code. Baseline: `cargo test --workspace` 512
|
||||
passed, clippy silent, fmt clean, corpus TSV md5
|
||||
`aa982463f68c1a3568c02a0fc5e0c455`.
|
||||
- **Reproduced the harness before reproducing the bugs.** The brief's failure
|
||||
list gave file *and line*, so the first job was finding the insertion index
|
||||
that reproduces it: inserting so the marker *becomes* line len/3 (0-based
|
||||
index len/3 − 1), not at index len/3. With that, a `HEAD` worktree binary
|
||||
reproduces all 14 failures exactly. Every later number has a real control.
|
||||
- **Reduced both buckets to five-line cases before writing any code**, and
|
||||
found in the process that the brief's bucket 1 is only half about
|
||||
instantiations: 10 of the 10 corpus files are *module headers*
|
||||
(`module prim_mubi4_dec` ⏎ `import prim_mubi_pkg::*;` ⏎ `// marker` ⏎ `#(`),
|
||||
not instantiations. The instantiation twin exists and refuses identically, so
|
||||
both are fixed; the module header is the one the corpus actually writes.
|
||||
- **Root cause, bucket 1.** `bump()` moves a consumed token's leading comments
|
||||
into `pending_leading`, so nothing is dropped — the comment simply reappears
|
||||
at the next `take_meta`, which is the first *element of the list*. The
|
||||
comment therefore printed inside the `#(...)` the author wrote it before.
|
||||
The information was in the token stream and nowhere in the AST, the same
|
||||
diagnosis the previous two rounds reached for separators.
|
||||
- **Chose four narrow fields over one general one.** A single
|
||||
`Meta::before_open` beside `before_sep` was tempting, but the four positions
|
||||
belong to three different nodes (`Module`, `Instantiation`, `Instance`) and
|
||||
two of them are not `Meta`-carrying at all. Four `Vec<Comment>` fields with
|
||||
four one-line doc comments read better than one field whose doc has to
|
||||
explain four meanings.
|
||||
- **`take_before_open` is a no-op unless the bracket is there**, copied
|
||||
deliberately from `take_before_sep`. That single decision is why a change
|
||||
reaching four parse sites left all 299 pre-existing `.cases`, all snapshots
|
||||
and all 512 tests byte-for-byte green: a module with no `#(` never enters
|
||||
the new path.
|
||||
Pinned by `a_header_without_brackets_keeps_its_comment_for_the_next_construct`.
|
||||
- **Root cause, bucket 2, was a printing bug, not a parsing one.** The parser
|
||||
already stores attributes and the comments after them in source order within
|
||||
each list; `Fmt::leading` just concatenated the two lists. Merging by
|
||||
`span.start` is a five-line change, and it happens to be a no-op for the
|
||||
common `// comment` ⏎ `(* attr *)` spelling, which is why only four corpus
|
||||
files ever hit it.
|
||||
- **Restructuring `item_docs` was the risky half of bucket 2.** It emitted
|
||||
leading comments, *then* checked the fence, *then* emitted attributes — so
|
||||
the merged `leading()` could not simply be dropped in without emitting a
|
||||
fenced item's attributes twice. Hoisted the fence check to the top and left
|
||||
the fenced path on the comments-only helper. Probed it four ways (fence
|
||||
covering an attributed item, fence opening between an attribute and its
|
||||
comment, a comment before the fence, a region spanning several items): every
|
||||
fenced region still byte-exact, `tests/fences.rs` 6/6, `fences.cases`
|
||||
untouched.
|
||||
- **Checked the fence question the new bucket-1 fields raise**, since they hold
|
||||
comments the fence scanner never sees. It never saw them before either —
|
||||
`scan_scope` walks item-level `meta.leading` only, and the comment used to
|
||||
live in a *parameter port's* meta. So a `// vfmt: off` in bracket position is
|
||||
inert now and was inert before; the change is that the file formats instead
|
||||
of refusing. Written up in Handshakes rather than left as a surprise.
|
||||
- **Every fixed shape is 3-pass stable**, checked outside `cargo test` on all
|
||||
23 reduced cases plus the four fence probes: `format(format(x)) == format(x)`
|
||||
with no refusals.
|
||||
- **Ran the exhaustive line sweep as well as the lead's two sample points**,
|
||||
on *both* binaries, because "0 at two positions per file" is a weaker claim
|
||||
than it sounds and because only a full run can say whether something got
|
||||
worse. 62 407 trials each: 335 → 240, 95 positions fixed, **0 newly
|
||||
refusing**.
|
||||
- **The exhaustive sweep is what found the third bug.** Reading its survivors
|
||||
rather than counting them turned up `rrarbiter.sv` and friends refusing at a
|
||||
comment between an instantiation's `#(...)` and its instance name — and the
|
||||
cause was that `instantiation`'s single-instance branch never reads
|
||||
`only.meta` at all, while the multi-instance branch three lines below it
|
||||
does. A comment parsed and never printed is hard invariant #3; it only ever
|
||||
showed up as a refusal. Fixed through the same `bracket_comments` helper, and
|
||||
pinned by its own rejection test. Six more corpus positions, zero test churn.
|
||||
- **Did not touch** `verify.rs` (`git diff --quiet` exits 0), `crates/vfmt*`,
|
||||
`crates/vlog_linter`, `crates/vlog_semantic`, `editors/`, `tools/` or
|
||||
`corpus/`. Did not run `git commit`/`git push`.
|
||||
|
||||
**Results:** `cargo test --workspace` **524 passed, 0 failed** (512 baseline +
|
||||
8 rejection tests + 4 parser unit tests; the 16 new `.cases` entries run inside
|
||||
the existing `case_tables` test, which now covers 315 cases). `cargo clippy
|
||||
--workspace --all-targets` silent. `cargo fmt --all --check` clean. Corpus TSV
|
||||
md5 unchanged, `tools/corpus_check.sh` exit 0.
|
||||
|
||||
Files touched: `crates/vlog_parser/src/{ast,parser}.rs`,
|
||||
`crates/vlog_formatter/src/format.rs`,
|
||||
`crates/vlog_formatter/tests/cases/comments.cases`,
|
||||
`crates/vlog_formatter/tests/verification.rs`, `TODO.md` (§2, one note), this
|
||||
README.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-19 — QA agent
|
||||
|
||||
**Verdict: pass on all five claims. No blocking findings.**
|
||||
|
||||
**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --workspace
|
||||
--all-targets` silent. `cargo test --workspace`: **524 passed, 0 failed**
|
||||
(counted by hand: 27+48+31+82+3+8+1+4+6+2+47+71+30+57+24+19+17+6+1+19+20+1
|
||||
doc-test = 524). `git diff --quiet -- crates/vlog_formatter/src/verify.rs`
|
||||
exits 0; same for `fence.rs`/`tests/fences.rs`/`fences.cases`; `fences.rs`
|
||||
6/6. `comments.cases` 77 → 93 (`grep -c '^# '`), workspace `.cases` total
|
||||
315. Corpus: `./tools/corpus_check.sh corpus` release build, exit 0, TSV md5
|
||||
**`aa982463f68c1a3568c02a0fc5e0c455`** — byte-identical to the claimed
|
||||
baseline.
|
||||
|
||||
**Claim 1 (bucket 1 / `take_before_open`).** Read `parser.rs`:
|
||||
`take_before_open` is exactly `if !self.cur().is_sym(open) { return
|
||||
Vec::new(); } self.take_dangling()` — a true no-op unless the cursor sits on
|
||||
the named bracket, the same shape as `take_before_sep`. Confirmed by the
|
||||
untouched pre-existing suite staying green (524 total, no regressions) and
|
||||
by the new parser unit test
|
||||
`a_header_without_brackets_keeps_its_comment_for_the_next_construct`. Pass.
|
||||
|
||||
**Claim 2 (bucket 2 / span-merge, fence hoist).** Read `format.rs::leading`:
|
||||
merges `meta.leading` and `meta.attrs` with a peekable iterator comparing
|
||||
`span.start`, in source order. `item_docs` checks `self.is_fenced(item.span)`
|
||||
first and only then branches to `leading_comments` (comments only, fenced
|
||||
path) vs `leading` (merged, normal path) — matches the claim exactly. Probed
|
||||
directly (`attack_g_fence_attrs.sv`, `attack_e_attr_comment_interleave.sv`
|
||||
below): fenced region byte-exact, no double emission; 4-way
|
||||
comment/attribute interleave preserved in source order. Pass.
|
||||
|
||||
**Claim 3 (single-instance `Instance.meta`).** Read the diff: the
|
||||
single-instance branch now calls `self.bracket_comments(&only.meta.leading,
|
||||
...)` before `self.instance(only)`; the multi-instance branch calls the full
|
||||
`self.leading(&instance.meta)`. Checked whether this asymmetry (leading only,
|
||||
not `attrs`) could drop an attribute on a lone instance: `Instance.meta` is
|
||||
built by plain `take_meta()`, which never populates `.attrs` (only
|
||||
`parse_item_inner`/`parse_stmt_inner` run the attribute-harvest loop) — so
|
||||
`Instance.meta.attrs` is structurally always empty, confirmed by trying to
|
||||
write one (`(* keep_hierarchy *)` before an instance name is a **parse
|
||||
error**, pre-existing, not a regression). The asymmetry is therefore not a
|
||||
gap. Pass.
|
||||
|
||||
**Claim 4 (sweep numbers).** Reproduced independently, not just re-read.
|
||||
- *Lead's 14-item list*: reconstructed each `file:line` insertion from
|
||||
`comment_fails.txt`, ran on the current release binary — **14/14** format
|
||||
cleanly, are 3-pass idempotent (checked pass1==pass2==pass3 by re-feeding
|
||||
output), and keep `// marker` at a sane position (eyeballed
|
||||
`prim_mubi4_dec.sv` and `prim_and2.sv`: marker lands between the import and
|
||||
`#(`, and between the attribute and `module`, exactly source order).
|
||||
- *Exhaustive spot-check*: built a `HEAD` (832bf4a) worktree binary, picked 30
|
||||
corpus files (8 import-header family, 6 `prim_xilinx` attribute family, 16
|
||||
random 20–200-line `would-reformat` files), inserted `// marker` before
|
||||
every line of every file on both binaries (7273 usable trials, 2 discarded
|
||||
for breaking parse). Result: **HEAD refusals 19, current refusals 9, 10
|
||||
fixed, 0 newly refusing.** Spot-checked 3 of the still-parked survivors:
|
||||
`ibex_alu.sv:655` etc. are `'{...}` assignment-pattern lines and
|
||||
`ibex_controller.sv`/`pulp_sync.sv` are `else`/`=` lines — exactly the
|
||||
parked families the README names, refusing on both binaries. Pass (numbers
|
||||
are of a different sample than the lead's full run, as instructed, but the
|
||||
direction and zero-regression property both hold).
|
||||
|
||||
**Claim 5 (verify.rs / corpus untouched).** Covered under Gates above; also
|
||||
re-verified after both sabotage rounds (see below) that `verify.rs` returned
|
||||
byte-identical (md5 of the file matched pre-sabotage) and the full
|
||||
verification suite went back to 47/47.
|
||||
|
||||
**Attack pass on the new comment slots** (8 probe files, `crates/.../attack_
|
||||
{a..h}_*.sv` pattern, saved in scratch; each run 3 passes through the current
|
||||
binary): comment before both `#(` and `(` in one header; three stacked
|
||||
comments in one bracket position; comment before `#(` on an instantiation
|
||||
(not just a header); comment between `#(...)` and an instance name for a
|
||||
single instance, an array instance `[3:0]`, and a multi-instance list;
|
||||
4-way attribute/comment interleave; attribute+comment on a statement inside
|
||||
`always`; a fence carrying an oddly-spaced attribute and a comment (verified
|
||||
byte-exact region reproduction, no double emission); comment before `#(` on
|
||||
an instantiation inside a `generate` block. **All 8 passed**: no crashes, all
|
||||
3-pass stable, every comment landed in the same source order at a sane
|
||||
position, no drops.
|
||||
|
||||
**Sabotage (hard invariant #4 check).** `verify.rs` carries no new
|
||||
normalization this round, so there's nothing "widened" to attack directly;
|
||||
instead confirmed the 8 new rejection tests have real teeth by weakening the
|
||||
*guard itself* two different ways, one at a time, each reverted before the
|
||||
next:
|
||||
1. Added a normalization sorting adjacent `Comment`/`Attribute` runs by text
|
||||
(simulating "attribute/comment order stops mattering"). Result:
|
||||
exactly the two attribute-order tests
|
||||
(`a_comment_swapped_with_an_attribute_is_still_rejected`,
|
||||
`an_attribute_hoisted_past_a_comment_that_preceded_it_is_still_rejected`)
|
||||
went red; 45/47 others stayed green — narrowly scoped, as expected.
|
||||
2. Commented out the leading/trailing comment-harvest lines in `lex_stream`
|
||||
(simulating "comments stop being compared at all"). Result:
|
||||
`a_dropped_bracket_comment_is_still_rejected` and
|
||||
`a_dropped_instance_name_comment_is_still_rejected` both went red (plus
|
||||
a pre-existing round-1 test, `a_dropped_enum_dangling_comment_is_still_
|
||||
rejected`, consistently — not an anomaly).
|
||||
Both times: reverted via `git checkout -- crates/vlog_formatter/src/
|
||||
verify.rs`, confirmed `git diff --quiet` exits 0 and the file's md5 matches
|
||||
the pre-sabotage value, then reran the full verification suite (47/47) and
|
||||
`cargo test --workspace` (524/524) clean.
|
||||
|
||||
**Regression breadth.** Full `.cases` + fixtures suite green (in the 524).
|
||||
10 random previously-passing `would-reformat` corpus files (fresh random
|
||||
sample, different from the QA's dense-sweep sample), run through `--stdin`
|
||||
on both the current and `HEAD` binaries: **0/10 differ** — byte-identical
|
||||
output and exit code on every one.
|
||||
|
||||
**CLAUDE.md compliance.** Files touched match the stated scope exactly
|
||||
(`git diff --stat`: `TODO.md`, `crates/vlog_formatter/src/format.rs`,
|
||||
`crates/vlog_formatter/tests/cases/comments.cases`,
|
||||
`crates/vlog_formatter/tests/verification.rs`,
|
||||
`crates/vlog_parser/src/{ast,parser}.rs`, plus this README). `crates/
|
||||
vfmt_server/` and `crates/vlog_linter/` show as untracked in `git status`
|
||||
but predate this feature (present in the session's initial git-status
|
||||
snapshot) — not touched by this diff. README has all seven required
|
||||
sections; Review is empty, left alone. `TODO.md` §2 note read honest: it
|
||||
states the sweep numbers, names the two shapes closed, and points at this
|
||||
README rather than re-explaining bucket 1's remaining head positions inline
|
||||
— acceptable, since the README itself lists them under "Not done."
|
||||
|
||||
**No blocking findings.** No dropped or reordered comment that
|
||||
`verify_equivalence` missed, no newly-refusing position, in any of the
|
||||
above. One non-blocking observation for the record, not a defect: the 8
|
||||
rejection tests in `verification.rs` call `expect_divergence(input, output)`
|
||||
directly on hand-written literal pairs — they exercise `verify.rs`'s
|
||||
strictness on these corruption shapes, not the `parser.rs`/`format.rs` fix
|
||||
itself (which has no failure path to hit from a test that never runs it).
|
||||
That's consistent with how the pre-existing rejection tests in this file are
|
||||
already written, so it isn't a regression, just worth naming: the fix's own
|
||||
regression coverage lives in the parser unit tests and the `.cases` entries,
|
||||
not in `verification.rs`.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-19 — lead. Verdict: accepted and committed. The owner's
|
||||
comment-drop report is fully resolved: 14/14 reported positions fixed,
|
||||
zero regressions across 62k exhaustive trials, and a third latent
|
||||
invariant-#3 bug found and fixed along the way.**
|
||||
|
||||
Points reviewed and accepted:
|
||||
|
||||
1. **Root-causing bucket 1 to module headers, not instantiations**
|
||||
(the brief's guess) is why the fix is right rather than lucky:
|
||||
`bump()` pushing consumed tokens' leading comments into
|
||||
`pending_leading` meant the comment teleported into the bracket it
|
||||
preceded. `take_before_open` as the opening-bracket twin of
|
||||
`take_before_sep` — no-op unless the cursor is on the bracket —
|
||||
inherits the proven byte-identity argument, and QA read it to
|
||||
confirm the shape.
|
||||
2. **Bucket 2's span-merge** (attrs and comments emitted in source
|
||||
order, not list order) covers items and statements in one change,
|
||||
and the fence-check hoist keeps fenced items emitting attrs only as
|
||||
source bytes — the interaction QA attacked directly.
|
||||
3. **The third bug** — a lone instance's meta parsed and never printed
|
||||
— was found by reading sweep survivors rather than stopping at the
|
||||
brief's two buckets. QA's follow-up (Instance.meta.attrs is
|
||||
structurally always empty, so no attr twin of the bug exists) closes
|
||||
the question properly.
|
||||
4. **The survivor accounting** (240 positions, all in families
|
||||
comments-round already parked, all refusing on HEAD too) keeps the
|
||||
honest ledger: nothing new refuses, and what still refuses is
|
||||
documented, not hidden.
|
||||
|
||||
QA's non-blocking note — the rejection tests pin verify.rs strictness
|
||||
on literal pairs rather than exercising the fix path — is accurate and
|
||||
matches the file's pre-existing style; the fix path itself is pinned by
|
||||
the 16 new .cases entries, so the two layers together cover both
|
||||
directions. Worth keeping in mind if verification.rs ever grows a
|
||||
format-then-verify harness.
|
||||
|
||||
Comment-insertion refusal history, for the record: ~6% (fences QA,
|
||||
pre-comments-round) → 0.4% (comments-round) → 0 on the acceptance
|
||||
protocol (this round), with survivors only at exhaustive per-line
|
||||
granularity in parked families.
|
||||
Reference in new issue
Block a user