diff --git a/TODO.md b/TODO.md index 53997f8..7e457b5 100644 --- a/TODO.md +++ b/TODO.md @@ -1340,9 +1340,22 @@ README.md, TODO.md §11 Lane B lines) ### Serial, after Lane A merges (parser.rs frees up) -- [ ] Directive-split for expressions/statements: `` `ifdef `` splitting +- [x] Directive-split for expressions/statements: `` `ifdef `` splitting an assign RHS / instantiation head (chip_if.sv:1192 anchor; blocks both top_* tb.sv testbenches). 5-file floor, high leverage. + Done: the mirror of `directive-split` — the failure lands on the + `` `ifdef `` that *opens* a region inside a construct, not on the + `` `else `` that closes one around it. Verbatim capture, at item and + at statement level; no new AST variant or field, so no printer arm. + Plus one guard in `take_list_directives` so an outer region's seam + is not harvested as a list element, which is all the two tb.sv files + needed. OpenTitan 107 → 100 failures: all 5 bucket-7 files, both + `top_{earlgrey,darjeeling}/dv/tb/tb.sv`, zero regressions, corpus + gate byte-identical at 813/820. + `docs/features/directive-in-statements/README.md`. + Also delivered there: the `Parser::take_before_open` handshake Lane B + filed (`docs/features/formatter-bug-fixes/README.md`), which unblocks + the 12th bucket-2 file, `keymgr_scoreboard.sv`. - [ ] Mop-up bundle (~26 files): enum member ranges, cast-base drive strengths, local typedef statement, gate delays, virtual+modport, rand-on-struct, foreach-skip-dim, hierarchical bind instance list. diff --git a/crates/vlog_formatter/tests/cases/directive_in_statements.cases b/crates/vlog_formatter/tests/cases/directive_in_statements.cases new file mode 100644 index 0000000..a4a1494 --- /dev/null +++ b/crates/vlog_formatter/tests/cases/directive_in_statements.cases @@ -0,0 +1,239 @@ +# a `ifdef opened part-way through an assign, each arm carrying the +# construct's own `;` -- the block ends at the `endif, because there is no +# `;` after it to stop at +# hw/top_earlgrey/dv/env/chip_if.sv:1189 (the anchor) +module m; + // Signal probe function for `rnd_ctr` of AES_CIPHER_CTRL + wire [3:0] aes_ctrl_rnd_ctr; + assign aes_ctrl_rnd_ctr = +`ifdef GATE_LEVEL + `AES_HIER.u_aes_core.u_aes_cipher_control.mr_rnd_ctr[3:0]; +`else + `AES_HIER.u_aes_core.u_aes_cipher_control.rnd_ctr; +`endif + wire after; +endmodule +---- +module m; + // Signal probe function for `rnd_ctr` of AES_CIPHER_CTRL + wire [3:0] aes_ctrl_rnd_ctr; + assign aes_ctrl_rnd_ctr = + `ifdef GATE_LEVEL + `AES_HIER.u_aes_core.u_aes_cipher_control.mr_rnd_ctr[3:0]; + `else + `AES_HIER.u_aes_core.u_aes_cipher_control.rnd_ctr; + `endif + wire after; +endmodule +==== +# the same shape at *statement* level: a region between two call arguments, +# balanced inside the parens, so the statement ends at its own `;`. Only the +# statement is captured -- the function around it still formats +# hw/dv/sv/jtag_agent/jtag_dtm_reg_block.sv:173 +class c; + virtual function void build(); + abits = (dv_base_reg_field::type_id::create("abits")); + abits.configure( + .parent(this), + .size(6), +`ifdef USE_DMI_INTERFACE + .reset(32'h10), +`else + .reset(32'h07), +`endif + .has_reset(1)); + dmistat = 1; + endfunction +endclass +---- +class c; + virtual function void build(); + abits = (dv_base_reg_field::type_id::create("abits")); + abits.configure( + .parent(this), + .size(6), + `ifdef USE_DMI_INTERFACE + .reset(32'h10), + `else + .reset(32'h07), + `endif + .has_reset(1)); + dmistat = 1; + endfunction +endclass +==== +# a region between the elements of a concatenation, three brackets deep inside +# an instantiation's parameter override -- the whole instantiation becomes the +# block, ending at its `;` +# hw/top_earlgrey/rtl/autogen/chip_earlgrey_asic.sv:621 +module chip; + padring #( + .DioPadType ({ + AnalogIn0, // RRAM_ANALOG +`ifdef ANALOGSIM + '0, +`else + CC2, +`endif + DualBidirTol // USB_N + }) + ) u_padring ( + .clk_scan_i(ast_base_clks.clk_sys), + .scanmode_i(scanmode) + ); + wire after; +endmodule +---- +module chip; + padring #( + .DioPadType ({ + AnalogIn0, // RRAM_ANALOG + `ifdef ANALOGSIM + '0, + `else + CC2, + `endif + DualBidirTol // USB_N + }) + ) u_padring ( + .clk_scan_i(ast_base_clks.clk_sys), + .scanmode_i(scanmode) + ); + wire after; +endmodule +==== +# two instantiation *heads* behind one `ifdef, sharing a connection list. The +# region opened before the item, so this is the closing shape the +# `directive-split` recovery already knew -- what changed is that +# `take_list_directives` no longer harvests the `else as a list element and +# reads the second arm's head as a positional connection +# hw/top_earlgrey/dv/tb/tb.sv:105 +module tb; +`ifdef DISABLE_ROM_INTEGRITY_CHECK + chip_earlgrey_asic #( + // This is to be used carefully, and should never be on for synthesis. + .SecRomCtrlDisableScrambling(1'b1) +) dut ( +`else + chip_earlgrey_asic dut ( +`endif + // Dedicated Pads + .POR_N(dut.chip_if.dios[DioPadPorN]), +`ifdef ANALOGSIM + .CC1(cc1), +`else + .CC1(dut.chip_if.dios[DioPadCc1]), +`endif + .SPI_HOST_D0(dut.chip_if.dios[DioPadSpiHostD0]) + ); + wire after; +endmodule +---- +module tb; + `ifdef DISABLE_ROM_INTEGRITY_CHECK + chip_earlgrey_asic #( + // This is to be used carefully, and should never be on for synthesis. + .SecRomCtrlDisableScrambling(1'b1) + ) dut ( + `else + chip_earlgrey_asic dut ( + `endif + // Dedicated Pads + .POR_N(dut.chip_if.dios[DioPadPorN]), + `ifdef ANALOGSIM + .CC1(cc1), + `else + .CC1(dut.chip_if.dios[DioPadCc1]), + `endif + .SPI_HOST_D0(dut.chip_if.dios[DioPadSpiHostD0]) + ); + wire after; +endmodule +==== +# a split `function` header: the header's own `;` closes a *header*, so the +# block runs to `endfunction` and takes the `: label` with it +# hw/dv/sv/jtag_agent/jtag_dtm_reg_block.sv:273 +class jtag_dtm_reg_dmi; + function new(string name = "", +`ifdef USE_DMI_INTERFACE + int unsigned n_bits = 50, +`else + int unsigned n_bits = 41, +`endif + int has_coverage = UVM_NO_COVERAGE); + super.new(name, n_bits, has_coverage); + endfunction : new + + int after; +endclass +---- +class jtag_dtm_reg_dmi; + function new(string name = "", + `ifdef USE_DMI_INTERFACE + int unsigned n_bits = 50, + `else + int unsigned n_bits = 41, + `endif + int has_coverage = UVM_NO_COVERAGE); + super.new(name, n_bits, has_coverage); + endfunction : new + + int after; +endclass +==== +# the control: a region opened *and* closed inside the connection list still +# conditions list elements, even with an outer region live, and the +# instantiation still parses as an instantiation rather than becoming opaque +module m; +`ifdef OUTER + chip dut ( + .A(a), +`ifdef ANALOGSIM + .CC1(c1), +`else + .CC1(d1), +`endif + .B(b) + ); +`endif +endmodule +---- +module m; + `ifdef OUTER + chip dut ( + .A(a), + `ifdef ANALOGSIM + .CC1(c1), + `else + .CC1(d1), + `endif + .B(b) + ); + `endif +endmodule +==== +# comments survive: the ones written inside the block print once, as part of +# its bytes, and the ones around it stay outside +module m; + // before the block + assign y = +`ifdef A + a; // inside the first arm +`else + b; /* inside the second */ +`endif + // after the block + wire after; +endmodule +---- +module m; + // before the block + assign y = + `ifdef A + a; // inside the first arm + `else + b; /* inside the second */ + `endif + // after the block + wire after; +endmodule diff --git a/crates/vlog_parser/src/parser.rs b/crates/vlog_parser/src/parser.rs index e0efff5..6c982c5 100644 --- a/crates/vlog_parser/src/parser.rs +++ b/crates/vlog_parser/src/parser.rs @@ -319,9 +319,10 @@ fn is_drive_strength(t: &Token) -> bool { t.kind == TokenKind::Keyword && DRIVE_STRENGTHS.contains(&t.text.as_str()) } -/// Where an item started, for the recovery that may have to replace it whole. +/// Where an item — or a statement — started, for the recovery that may have to +/// replace it whole. struct ItemMark { - /// Index of the item's first token, past its attributes. + /// Index of the construct's first token, past its attributes. pos: usize, /// Conditional regions open at that token. conds: u32, @@ -337,7 +338,100 @@ fn directive_word(t: &Token) -> &str { if t.kind != TokenKind::Directive { return ""; } - let rest = t.text.strip_prefix('`').unwrap_or(""); + directive_word_of(&t.text) +} + +/// Keywords that open a body, so that the first `;` after them closes a +/// *header* — or a statement inside the body — rather than the construct. +/// +/// `function` and `task` are handled separately, by [`ConstructEnd::Keyword`]; +/// these are the ones the opening-split recovery refuses outright, because +/// nothing in the corpus asks for them and capturing at a `;` would leave a +/// truncated head with its body orphaned behind it. +const BODY_KEYWORDS: &[&str] = &[ + "module", + "macromodule", + "interface", + "program", + "package", + "class", + "checker", + "config", + "primitive", + "specify", + "generate", + "covergroup", + "property", + "sequence", + "clocking", + "constraint", + "begin", + "fork", + "case", + "casex", + "casez", + "randcase", + "for", + "foreach", + "while", + "repeat", + "forever", + "do", + "if", + "initial", + "final", + "always", + "always_comb", + "always_ff", + "always_latch", +]; + +/// Keywords that may stand in front of a `function` / `task` without changing +/// what closes it. `extern` and `pure` are deliberately absent: those spell a +/// prototype, which really does end at its `;`. +const TF_QUALIFIERS: &[&str] = &["virtual", "static", "automatic", "local", "protected"]; + +/// What the opening-split extent scan must look for to know a construct ended. +#[derive(Clone, Copy, PartialEq)] +enum ConstructEnd { + /// Its own `;` — every declaration, every instantiation, every simple + /// statement, and what `directive-split` has always assumed. + Semi, + /// The closing keyword named, which the header's `;` only precedes. + Keyword(&'static str), + /// Not modeled: refuse rather than capture a truncated head. + Unknown, +} + +/// How the construct starting at `head` ends. +/// +/// Read from the head alone, because that is all the recovery knows: the parse +/// already failed, so there is no node to ask. `jtag_dtm_reg_block.sv` is why +/// this exists — its split `function new(` header stopped the scan at the +/// header's own `;` and left `super.new(...)` behind as an item. +fn construct_end(head: &[Token]) -> ConstructEnd { + let mut i = 0; + while let Some(t) = head.get(i) { + if t.kind != TokenKind::Keyword { + // An identifier head: an instantiation, a call statement, an + // assignment. All of them end at a `;`. + return ConstructEnd::Semi; + } + match t.text.as_str() { + w if TF_QUALIFIERS.contains(&w) => i += 1, + "function" => return ConstructEnd::Keyword("endfunction"), + "task" => return ConstructEnd::Keyword("endtask"), + w if BODY_KEYWORDS.contains(&w) => return ConstructEnd::Unknown, + _ => return ConstructEnd::Semi, + } + } + ConstructEnd::Unknown +} + +/// [`directive_word`] over the source text of a directive already captured as +/// a [`RawText`], for the harvested lines a list keeps rather than a token. +fn directive_word_of(text: &str) -> &str { + let rest = text.strip_prefix('`').unwrap_or(""); let end = rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_').unwrap_or(rest.len()); rest.get(..end).unwrap_or("") } @@ -357,6 +451,18 @@ fn closes_conditional(t: &Token) -> bool { directive_word(t) == "endif" } +/// Move the comments written at or after byte `gap` out of `queue` and onto +/// `out`, in source order, leaving the earlier ones queued where they were. +fn take_since(queue: &mut Vec, gap: u32, out: &mut Vec) { + for c in std::mem::take(queue) { + if c.span.start >= gap { + out.push(c); + } else { + queue.push(c); + } + } +} + /// Split an optional [`Name`] into the `(text, span)` pair the nodes that keep /// a name in a `String` field store it as. fn split_label(name: Option) -> (Option, Option) { @@ -754,11 +860,33 @@ impl<'a> Parser<'a> { /// [`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. + /// + /// Only the comments written in the **gap that ends at this bracket** are + /// taken — see [`Parser::take_gap`]. fn take_before_open(&mut self, open: &str) -> Vec { if !self.cur().is_sym(open) { return Vec::new(); } - self.take_dangling() + self.take_gap() + } + + /// The comments written in the gap that ends at the cursor: those starting + /// at or after the end of the last token consumed. + /// + /// The narrow sibling of [`Parser::take_dangling`], for the sites that own + /// *one* gap rather than everything still queued. A comment queued from + /// further back was written somewhere else and belongs to whoever owns + /// that place — `if (` ⏎ `// why` ⏎ `!f()` queues the comment on the `(` + /// of the **condition**, and neither `f`'s own `(` nor the inside of its + /// empty `()` may print it. Nothing is dropped: what is left queued is + /// harvested by the next node that takes meta. + fn take_gap(&mut self) -> Vec { + let gap = self.last_end(); + let mut out = Vec::new(); + take_since(&mut self.pending_trailing, gap, &mut out); + take_since(&mut self.pending_leading, gap, &mut out); + take_since(&mut self.tokens[self.pos].leading, gap, &mut out); + out } /// Consume the compiler directives — and the standalone macro invocations @@ -775,6 +903,9 @@ impl<'a> Parser<'a> { fn take_list_directives(&mut self, out: &mut Vec, before: usize) -> Harvested { let mut found = Harvested::default(); while self.cur().kind == TokenKind::Directive || self.at_macro_item() { + if self.at_outer_arm_split(out) { + break; + } let mut meta = self.take_meta(); let raw = self.take_raw_text(); meta.trailing = self.take_trailing(); @@ -786,6 +917,55 @@ impl<'a> Parser<'a> { found } + /// True when the directive at the cursor continues or closes a conditional + /// region **this list did not open**, while a region opened at item scope + /// is still live. + /// + /// Such a directive is not conditioning list *elements* — it is the seam + /// where the whole item splits into rival spellings that share one list: + /// + /// ```verilog + /// `ifdef DISABLE_ROM_INTEGRITY_CHECK + /// chip_earlgrey_asic #(.SecRomCtrlDisableScrambling(1'b1)) dut ( + /// `else + /// chip_earlgrey_asic dut ( + /// `endif + /// .POR_N(...), ... + /// ); + /// ``` + /// + /// Harvesting the `` `else `` here would leave the parser reading the next + /// arm's *head* (`chip_earlgrey_asic dut`) as connection elements, and it + /// fails two tokens later with a diagnostic three lines from the defect. + /// Refusing it lets the item fail on the directive itself, where + /// [`Parser::at_split_conditional`] recognizes the shape and captures the + /// whole instantiation verbatim — the treatment the arms of a split region + /// have had since `docs/features/directive-split/README.md`. + /// + /// `taken` is what this list has harvested so far, which is the only + /// scope that can have opened a region the directive legitimately ends. + fn at_outer_arm_split(&self, taken: &[ListDirective]) -> bool { + let t = self.cur(); + if !continues_conditional(t) && !closes_conditional(t) { + return false; + } + // The same "a region is live" guard the split recovery makes: with + // nothing open at item scope there is no outer arm to belong to, and + // the directive is ordinary conditional text inside the list. + if self.open_conds == 0 { + return false; + } + let mut open = 0i32; + for d in taken { + match directive_word_of(&d.raw.text) { + "ifdef" | "ifndef" => open += 1, + "endif" => open -= 1, + _ => {} + } + } + open <= 0 + } + /// Comments sitting right before a closing keyword (`end`, `endmodule`, /// ...) — they belong inside the enclosing construct. fn take_dangling(&mut self) -> Vec { @@ -1911,15 +2091,43 @@ impl<'a> Parser<'a> { } } - /// Turn an item that is really one arm of a split conditional region into - /// a verbatim block, or hand `err` back untouched. + /// Turn an item that is really one arm of a split conditional region — or + /// one whose own region splits it — into a verbatim block, or hand `err` + /// back untouched. + /// + /// The two shapes are mirror images and are tried in that order: + /// + /// - the item **is an arm** of a region opened before it started, and + /// failed on the `` `else `` / `` `endif `` that closes it + /// ([`Parser::at_split_conditional`]); + /// - the item **opened** a region part-way through and failed on the + /// `` `ifdef `` itself ([`Parser::at_opening_split`]). fn split_conditional_item(&mut self, mark: &ItemMark, err: ParseError) -> PResult { - if !self.at_split_conditional(mark) { - return Err(err); + if self.at_split_conditional(mark) { + if let Some((end_pos, conds_after)) = self.scan_split_extent(mark) { + // The block swallowed the region's own `else / `endif, which + // *are* item-scope nesting even though they now sit inside + // opaque bytes. The extent scan already worked out what they + // leave open, so this is the second and last place + // `open_conds` moves. + self.open_conds = conds_after; + return Ok(ItemKind::Verbatim(self.capture_split(mark, end_pos))); + } } - let Some((end_pos, conds_after)) = self.scan_split_extent(mark) else { - return Err(err); - }; + if self.at_opening_split(mark) { + if let Some(end_pos) = self.scan_opening_split_extent(mark) { + // No `open_conds` adjustment: every exit of the scan leaves + // conditional nesting back at zero, so the block is + // conditional-balanced and item scope is undisturbed. + return Ok(ItemKind::Verbatim(self.capture_split(mark, end_pos))); + } + } + Err(err) + } + + /// Replace the construct that began at `mark` with the source bytes + /// running from its first token to `end_pos`, and put the cursor there. + fn capture_split(&mut self, mark: &ItemMark, end_pos: usize) -> RawText { self.diagnostics.truncate(mark.diags); let start = self.tokens[mark.pos].span.start; let col = self.tokens[mark.pos].col; @@ -1933,12 +2141,7 @@ impl<'a> Parser<'a> { while self.pos < end_pos && !self.at_eof() { self.bump(); } - // The block swallowed the region's own `else / `endif, which *are* - // item-scope nesting even though they now sit inside opaque bytes. - // The extent scan already worked out what they leave open, so this is - // the second and last place `open_conds` moves. - self.open_conds = conds_after; - Ok(ItemKind::Verbatim(self.verbatim_since(start, col))) + self.verbatim_since(start, col) } /// True when the item that began at `mark` failed *because* it is one arm @@ -2065,6 +2268,161 @@ impl<'a> Parser<'a> { None } + /// True when the construct that began at `mark` failed *because* it opened + /// a conditional region part-way through and the rest of it lives in the + /// arms: + /// + /// ```verilog + /// assign aes_ctrl_rnd_ctr = + /// `ifdef GATE_LEVEL + /// `AES_HIER.u_aes_cipher_control.mr_rnd_ctr[3:0]; + /// `else + /// `AES_HIER.u_aes_cipher_control.rnd_ctr; + /// `endif + /// ``` + /// + /// This is [`Parser::at_split_conditional`]'s mirror image. There the + /// failure is on the directive that *closes* a region opened before the + /// construct; here it is on the `` `ifdef `` that opens one inside it. An + /// expression has no "this might be a pass-through directive" branch — the + /// directive pass-through lives at item- and statement-list boundaries and + /// in the four bracketed-list sites `directives-in-lists` covers — so the + /// parse fails immediately, before any bracket is opened and before the + /// closing-split trigger can ever be evaluated. + /// + /// Two things must hold at once: + /// + /// 1. the cursor stands on an `` `ifdef `` / `` `ifndef ``. Any other + /// directive mid-expression (`` `include ``, a bare `` `endif ``) is + /// still an ordinary parse error; + /// 2. the construct is **one unterminated run** reaching that directive — + /// it has consumed at least one token and no `;` at bracket depth zero + /// since it started. A failure that propagated up from deeper inside an + /// already-terminated construct would otherwise capture the whole + /// enclosing item on a guess; this is what keeps the recovery at the + /// innermost construct the region actually splits. + fn at_opening_split(&self, mark: &ItemMark) -> bool { + if !opens_conditional(self.cur()) { + return false; + } + if self.pos <= mark.pos { + return false; + } + let mut brackets = 0i32; + for t in self.tokens.get(mark.pos..self.pos).unwrap_or_default() { + if t.is_sym("(") || t.is_sym("[") || t.is_sym("{") { + brackets += 1; + } else if t.is_sym(")") || t.is_sym("]") || t.is_sym("}") { + brackets -= 1; + } else if t.is_sym(";") && brackets <= 0 { + return false; + } + } + true + } + + /// One past the last token of the construct a region opened inside it + /// splits, or `None` when the file holds no such end. + /// + /// Like [`Parser::scan_split_extent`] the scan follows the **first** arm + /// and skips the alternatives whole, because the arms are rival spellings + /// of the same thing and counting every arm's brackets would demand as + /// many closers as there are arms. + /// + /// Where the construct ends depends on which side of the region its + /// terminator was written on, and both spellings are in the corpus: + /// + /// - the arms each carry their own `;` (`chip_if.sv`), so the construct + /// ends at the `` `endif `` that closes the region — there is no `;` + /// after it, and scanning on would swallow the next item; + /// - the region is balanced *inside* the construct and the `;` comes after + /// it (`chip_earlgrey_asic.sv`, `jtag_dtm_reg_block.sv`), so the + /// construct ends at that `;`. + /// + /// `terminated_in_arm` is what tells them apart: a `;` met at bracket + /// depth zero while a region is still open means the tail is inside the + /// arms. + /// + /// A head that opens a body ends at its closing keyword instead, and one + /// whose ending is not modeled ([`ConstructEnd::Unknown`]) is refused. + /// + /// Every exit leaves conditional nesting back at zero, so a captured block + /// is conditional-balanced and item-scope nesting is undisturbed. + fn scan_opening_split_extent(&self, mark: &ItemMark) -> Option { + let end = construct_end(self.tokens.get(mark.pos..)?); + if end == ConstructEnd::Unknown { + return None; + } + let semi_ends = end == ConstructEnd::Semi; + let mut cond = 0i32; + let mut brackets = 0i32; + let mut terminated_in_arm = false; + let mut i = mark.pos; + while let Some(t) = self.tokens.get(i) { + if t.kind == TokenKind::Eof { + return None; + } + if t.kind == TokenKind::Directive { + if opens_conditional(t) { + cond += 1; + } else if closes_conditional(t) { + cond -= 1; + if cond < 0 { + return None; + } + if semi_ends && cond == 0 && terminated_in_arm { + return Some(i + 1); + } + } else if continues_conditional(t) { + // A `else / `elsif with nothing open is a stray closer, + // not an arm boundary: broken input, and the parse error + // stands — the same refusal the closing-split scan makes. + if cond == 0 { + return None; + } + i = self.skip_conditional_arms(i + 1)?; + cond -= 1; + if semi_ends && cond == 0 && terminated_in_arm { + return Some(i); + } + continue; + } + } else if let ConstructEnd::Keyword(kw) = end { + if t.is_kw(kw) && brackets == 0 && cond == 0 { + return Some(self.past_end_label(i + 1)); + } + } + if t.is_sym("(") || t.is_sym("[") || t.is_sym("{") { + brackets += 1; + } else if t.is_sym(")") || t.is_sym("]") || t.is_sym("}") { + brackets -= 1; + if brackets < 0 { + return None; + } + } else if semi_ends && t.is_sym(";") && brackets == 0 { + if cond == 0 { + return Some(i + 1); + } + terminated_in_arm = true; + } + i += 1; + } + None + } + + /// One past `after_kw`'s optional `: name` — the label a closing keyword + /// may carry (`endfunction : new`), which belongs inside the block with + /// the keyword it names. + fn past_end_label(&self, after_kw: usize) -> usize { + let colon = self.tokens.get(after_kw).is_some_and(|t| t.is_sym(":")); + let name = self.tokens.get(after_kw + 1).is_some_and(|t| t.kind == TokenKind::Ident); + if colon && name { + after_kw + 2 + } else { + after_kw + } + } + /// True when the cursor opens a parameterized type's `#( ... )`. fn at_type_params(&self) -> bool { self.cur().is_sym("#") && self.nth(1).is_sym("(") @@ -3662,7 +4020,12 @@ impl<'a> Parser<'a> { let tok = &mut self.tokens[self.pos]; meta.leading.append(&mut tok.leading); } - let kind = self.parse_stmt_kind()?; + let mark = + ItemMark { pos: self.pos, conds: self.open_conds, diags: self.diagnostics.len() }; + let kind = match self.parse_stmt_kind() { + Ok(kind) => kind, + Err(e) => self.split_conditional_stmt(&mark, e)?, + }; let span = self.span_from(start); if meta.trailing.is_none() { meta.trailing = self.take_trailing(); @@ -3670,6 +4033,42 @@ impl<'a> Parser<'a> { Ok(Stmt { meta, kind, span }) } + /// The statement half of [`Parser::split_conditional_item`]: a statement a + /// region opened inside it splits becomes a verbatim block. + /// + /// `jtag_dtm_reg_block.sv:173` is the corpus shape — a `` `ifdef `` between + /// two named arguments of a call, deep inside a function body: + /// + /// ```verilog + /// abits.configure( + /// .volatile(0), + /// `ifdef USE_DMI_INTERFACE + /// .reset(32'h10), + /// `else + /// .reset(32'h07), + /// `endif + /// .has_reset(1)); + /// ``` + /// + /// Only the **opening** shape is recognized here. The closing one is + /// item-scope by construction: [`Parser::open_conds`] counts the + /// `` `ifdef ``s consumed as *items*, so `mark.conds` inside a body would + /// be answering a question about a different scope. Nothing in the corpus + /// asks for it, and guessing would widen the net for no evidence. + /// + /// Running here rather than only at item level is what keeps the capture + /// at the innermost construct: a statement failure that reached + /// `parse_item_inner` would be scanned from the enclosing `module` or + /// `class` keyword instead. + fn split_conditional_stmt(&mut self, mark: &ItemMark, err: ParseError) -> PResult { + if self.at_opening_split(mark) { + if let Some(end_pos) = self.scan_opening_split_extent(mark) { + return Ok(StmtKind::Verbatim(self.capture_split(mark, end_pos))); + } + } + Err(err) + } + fn parse_stmt_kind(&mut self) -> PResult { if self.at_macro_item() || self.at_spaced_macro_call() { return Ok(StmtKind::MacroStmt(self.parse_macro_call()?)); @@ -4576,7 +4975,10 @@ impl<'a> Parser<'a> { ExprItem { meta, expr: first_expr, span: self.span_from(arg_start) }; args = self.parse_expr_list(first, ")")?; } else { - comments.dangling = self.take_dangling(); + // Only what was written *inside* the empty `()`: a comment + // queued from before the callee belongs to whoever owns + // the place it was written, not to this argument list. + comments.dangling = self.take_gap(); } self.expect_sym(")")?; expr = self.expr_at( @@ -6184,13 +6586,27 @@ mod tests { } #[test] - fn a_directive_inside_a_connection_is_still_a_parse_error() { - // A directive runs to end of line, so it can only stand *between* - // connections. One written inside a connection's parens is out of - // scope by design; this pins that it is refused rather than half-read. + fn a_directive_inside_a_connection_is_captured_or_refused_by_kind() { + // Superseded in part by `directive-in-statements` (2026-08-29). A + // *conditional* region inside a connection's parens is the bucket-7 + // shape — `chip_earlgrey_asic.sv` writes one inside a parameter + // value's concatenation — so it is now captured verbatim rather than + // refused. `directives-in-lists` still does not read it as a list + // element: the whole instantiation becomes opaque bytes. let src = "module m;\n sub u (\n .a(\n`ifdef X\n y\n`endif\n )\n );\nendmodule\n"; - assert!(parse(tokenize(src).expect("lex error"), src).is_err()); + let f = parse_ok(src); + let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; + let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") }; + assert!(raw.text.starts_with("sub u ("), "{:?}", raw.text); + assert!(raw.text.ends_with(");"), "{:?}", raw.text); + + // Any *other* directive there is still an ordinary parse error: the + // recovery triggers on `ifdef / `ifndef only. + let msg = parse_err( + "module m;\n sub u (\n .a(\n`include \"x.vh\"\n y\n )\n );\nendmodule\n", + ); + assert!(msg.contains("`include"), "{msg}"); } /// The strict entry point keeps its contract: it fails at the *first* @@ -7754,4 +8170,293 @@ mod tests { ["directive:`ifdef A", "decl", "directive:`else", "decl", "directive:`endif"] ); } + + // ------------------------------------------------------------------ + // directive-in-statements: a region opened *inside* a construct + // (`docs/features/directive-in-statements/README.md`) + // ------------------------------------------------------------------ + + #[test] + fn an_ifdef_splitting_an_assigns_rhs_is_captured_verbatim() { + // hw/top_earlgrey/dv/env/chip_if.sv:1189-1194, the anchor shape: each + // arm carries the construct's own `;`, so the block ends at the + // `endif -- there is no `;` after it to stop at. + let src = "module m;\n assign y =\n`ifdef GATE_LEVEL\n a.b.mr_rnd_ctr[3:0];\n`else\n a.b.rnd_ctr;\n`endif\n wire z;\nendmodule\n"; + let f = parse_ok(src); + let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; + let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") }; + assert!(raw.text.starts_with("assign y ="), "{:?}", raw.text); + assert!(raw.text.ends_with("`endif"), "{:?}", raw.text); + assert!(matches!(m.items[1].kind, ItemKind::DataDecl(_)), "the next item survived"); + } + + #[test] + fn an_ifdef_between_call_arguments_captures_the_statement_only() { + // hw/dv/sv/jtag_agent/jtag_dtm_reg_block.sv:173. The region is + // balanced inside the call's parens, so the statement ends at its own + // `;` -- and the capture is the *statement*, not the enclosing + // function, which is what running the recovery at statement level + // buys. + let src = "module m;\n initial begin\n a.configure(\n .size(2),\n`ifdef USE_DMI\n .reset(32'h10),\n`else\n .reset(32'h07),\n`endif\n .has_reset(1));\n b = 1;\n end\nendmodule\n"; + let f = parse_ok(src); + let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; + let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected an initial") }; + let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") }; + let StmtKind::Verbatim(raw) = &stmts[0].kind else { panic!("expected a verbatim stmt") }; + assert!(raw.text.starts_with("a.configure("), "{:?}", raw.text); + assert!(raw.text.ends_with(".has_reset(1));"), "{:?}", raw.text); + assert!(matches!(stmts[1].kind, StmtKind::Assign { .. }), "the next statement survived"); + } + + #[test] + fn an_ifdef_inside_an_instantiations_parameter_value_captures_the_instantiation() { + // hw/top_earlgrey/rtl/autogen/chip_earlgrey_asic.sv:621 -- a region + // between the elements of a concatenation, three brackets deep inside + // a parameter override. The `;` after the whole instantiation ends it. + let src = "module m;\n padring #(\n .PadType({\n A,\n`ifdef ANALOGSIM\n \ + '0,\n`else\n CC2,\n`endif\n B\n })\n ) u_padring (\n \ + .clk(c)\n );\n wire z;\nendmodule\n"; + let f = parse_ok(src); + let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; + let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") }; + assert!(raw.text.starts_with("padring #("), "{:?}", raw.text); + assert!(raw.text.ends_with(");"), "{:?}", raw.text); + assert!(matches!(m.items[1].kind, ItemKind::DataDecl(_)), "the next item survived"); + } + + #[test] + fn a_split_function_header_captures_through_endfunction() { + // hw/dv/sv/jtag_agent/jtag_dtm_reg_block.sv:273. A `function`'s own + // `;` closes its *header*: stopping there left `super.new(...)` behind + // as an item and the file failed three lines into the body. The + // closing keyword, and the `: label` it may carry, end the block. + let src = "class c;\n function new(string name = \"\",\n`ifdef USE_DMI\n int unsigned n = 50,\n`else\n int unsigned n = 41,\n`endif\n int cov = 0);\n super.new(name, n, cov);\n endfunction : new\n int after;\nendclass\n"; + let f = parse_ok(src); + let ItemKind::Class(c) = &f.items[0].kind else { panic!("expected a class") }; + let ItemKind::Verbatim(raw) = &c.items[0].kind else { panic!("expected a verbatim block") }; + assert!(raw.text.starts_with("function new("), "{:?}", raw.text); + assert!(raw.text.ends_with("endfunction : new"), "{:?}", raw.text); + assert!(matches!(c.items[1].kind, ItemKind::DataDecl(_)), "the next item survived"); + } + + #[test] + fn an_ifdef_that_splits_an_instantiation_head_is_still_the_closing_shape() { + // hw/top_earlgrey/dv/tb/tb.sv:113 (bucket 13): two instantiation heads + // behind one `ifdef sharing a connection list. The region opened + // *before* the item, so this is `at_split_conditional`'s shape -- what + // this round changed is that `take_list_directives` no longer harvests + // the `else as a list element and hides the seam. + let src = "module m;\n`ifdef DISABLE_ROM\n chip #(\n .Scramble(1'b1)\n ) dut \ + (\n`else\n chip dut (\n`endif\n .POR_N(p),\n .USB_P(u)\n );\n wire \ + z;\nendmodule\n"; + let f = parse_ok(src); + let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; + assert!(matches!(m.items[0].kind, ItemKind::Directive(_)), "the `ifdef stayed an item"); + let ItemKind::Verbatim(raw) = &m.items[1].kind else { panic!("expected a verbatim block") }; + assert!(raw.text.starts_with("chip #("), "{:?}", raw.text); + assert!(raw.text.ends_with(");"), "{:?}", raw.text); + assert!(matches!(m.items[2].kind, ItemKind::DataDecl(_)), "the next item survived"); + } + + #[test] + fn a_list_internal_region_is_still_harvested_as_list_elements() { + // The other side of the `take_list_directives` guard: a region opened + // *and* closed inside the connection list still conditions elements, + // and the instantiation still parses as an instantiation. Written + // inside an outer region, which is the state that arms the guard. + let src = "module m;\n`ifdef OUTER\n chip dut (\n .A(a),\n`ifdef ANALOGSIM\n \ + .CC1(c1),\n`else\n .CC1(d1),\n`endif\n .B(b)\n );\n`endif\nendmodule\n"; + let f = parse_ok(src); + let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; + let ItemKind::Instantiation(inst) = &m.items[1].kind else { + panic!("expected an instantiation, got {:?}", split_items(&f)) + }; + assert_eq!(inst.instances[0].conn_directives.len(), 3, "`ifdef / `else / `endif harvested"); + } + + #[test] + fn an_opening_split_leaves_item_scope_nesting_alone() { + // Every exit of the extent scan has conditional nesting back at zero, + // so a captured block is conditional-balanced by construction. + assert_eq!( + open_conds_after( + "module m;\n assign y =\n`ifdef A\n a;\n`else\n b;\n`endif\nendmodule\n" + ), + 0 + ); + assert_eq!( + open_conds_after( + "`ifdef OUTER\nmodule m;\n assign y =\n`ifdef A\n a;\n`else\n \ + b;\n`endif\nendmodule\n" + ), + 1, + "the region around it is untouched" + ); + } + + #[test] + fn the_opening_split_refuses_everything_it_does_not_model() { + // Each of these reaches `at_opening_split` or `scan_opening_split_extent` + // and is handed its parse error back. Verified against the release + // binary on the real files as well; see the feature README. + for (why, src) in [ + ( + "a non-conditional directive is not a split", + "module m;\n assign y =\n`include \"x.vh\"\n a;\nendmodule\n", + ), + ("a stray closer opens nothing", "module m;\n assign y =\n`endif\n a;\nendmodule\n"), + ("an unterminated region has no end", "module m;\n assign y =\n`ifdef A\n a;\n"), + ( + "the construct never ends", + "module m;\n assign y =\n`ifdef A\n a\n`endif\nendmodule\n", + ), + ( + "a plain syntax error near a directive stays one", + "module m;\n`ifdef A\n assign y = ;\n`endif\nendmodule\n", + ), + ( + "brackets that do not balance across the arms", + "module m;\n assign y = (\n`ifdef A\n a;\n`else\n b);\n`endif\nendmodule\n", + ), + ( + "a body-opening head whose end is not modeled", + "module m;\n initial\n case (\n`ifdef A\n x\n`else\n \ + y\n`endif\n )\n 1: a = 1;\n endcase\nendmodule\n", + ), + ] { + let toks = tokenize(src).expect("lex error"); + assert!(parse(toks, src).is_err(), "should still refuse: {why}"); + } + } + + #[test] + fn a_comment_after_an_opening_bracket_is_not_stolen_by_an_inner_call() { + // The handshake `docs/features/formatter-bug-fixes/README.md` filed: + // `take_before_open` drained the whole pending queue, so a comment + // written after `if (` was printed between the condition's first + // callee and its own `(`. Both of the call's comment slots must now + // leave it queued for whoever owns the place it was written. + let src = "module m;\n initial begin\n if (// why\n !en() || b\n ) \ + begin\n x = 1;\n end\n end\nendmodule\n"; + let f = parse_ok(src); + let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; + let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected an initial") }; + let StmtKind::Block { stmts, .. } = &stmt.kind else { panic!("expected a block") }; + let StmtKind::If { cond, then, .. } = &stmts[0].kind else { panic!("expected an if") }; + // Neither `before_open` (the `(` of `en(`) nor `dangling` (the inside + // of the empty `()`) may hold it. + let ExprKind::Binary { lhs, .. } = &cond.kind else { panic!("expected a binary") }; + let ExprKind::Unary { expr, .. } = &lhs.kind else { panic!("expected a unary") }; + let ExprKind::Call { comments, .. } = &expr.kind else { panic!("expected a call") }; + assert!(comments.before_open.is_empty(), "{:?}", comments.before_open); + assert!(comments.dangling.is_empty(), "{:?}", comments.dangling); + // It stays queued and reaches the body's leading comments, which is + // where the formatter's `header_parens` takes it back from. + assert_eq!(then.meta.leading.len(), 1, "{:?}", then.meta.leading); + assert!(then.meta.leading[0].text.contains("why")); + } + + #[test] + fn a_comment_actually_written_before_a_bracket_is_still_taken() { + // The other side of the same guard: `take_before_open` must keep + // doing its job for the comments written in the gap it owns. + let f = parse_ok("module m\n // why\n #(\n parameter int W = 1\n ) ();\nendmodule\n"); + let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; + assert_eq!(m.param_comments.len(), 1, "{:?}", m.param_comments); + assert!(m.param_comments[0].text.contains("why")); + + let f = parse_ok("module m;\n initial x = f\n // why\n ();\nendmodule\n"); + let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; + let ItemKind::Initial(stmt) = &m.items[0].kind else { panic!("expected an initial") }; + let StmtKind::Assign { rhs, .. } = &stmt.kind else { panic!("expected an assignment") }; + let ExprKind::Call { comments, .. } = &rhs.kind else { panic!("expected a call") }; + assert_eq!(comments.before_open.len(), 1, "{:?}", comments.before_open); + } + + // ------------------------------------------------------------------ + // QA (2026-08-29): adversarial coverage for directive-in-statements, + // none of which turned up a bug -- pinned so a future refactor of + // `scan_opening_split_extent`/`at_outer_arm_split` cannot silently + // regress any of them. + // ------------------------------------------------------------------ + + #[test] + fn a_nested_ifdef_with_its_own_elsif_survives_inside_an_opening_split_under_an_outer_region() { + // Three levels of conditional at once: an outer region already open + // when the item starts, an opening split inside the assign's RHS, and + // a *nested* `ifdef / `elsif / `else / `endif fully inside that + // split's first arm. The nested region's own arms must not be + // mistaken for the split's own `else / `endif, and `open_conds` must + // land back at 1 (the outer region only) once the whole thing is + // captured. + let src = "`ifdef OUTER\nmodule m;\n assign y =\n`ifdef A\n`ifdef NESTED\n a\n\ + `elsif NESTED2\n a2\n`else\n a3\n`endif\n + 1;\n`elsif A2\n q;\n\ + `else\n b;\n`endif\n wire z;\nendmodule\n"; + let f = parse_ok(src); + assert_eq!(open_conds_after(src), 1, "the outer region is still open at eof"); + // items[0] is the outer `ifdef OUTER` itself, a file-scope directive. + let ItemKind::Module(m) = &f.items[1].kind else { panic!("expected a module") }; + let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") }; + assert!(raw.text.starts_with("assign y ="), "{:?}", raw.text); + assert!(raw.text.contains("`ifdef NESTED"), "the nested region is inside the capture"); + assert!(raw.text.ends_with("`endif"), "{:?}", raw.text); + assert!(matches!(m.items[1].kind, ItemKind::DataDecl(_)), "the next item survived"); + } + + #[test] + fn an_elsif_chain_in_an_opening_split_is_captured_through_the_final_endif() { + // Only if/else was exercised elsewhere; a 4-arm chain must still end + // at the one closing `endif, not at an intermediate `elsif. + let src = "module m;\n assign y =\n`ifdef A\n a;\n`elsif B\n b;\n`elsif C\n \ + c;\n`else\n d;\n`endif\n wire z;\nendmodule\n"; + let f = parse_ok(src); + let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; + let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") }; + assert!(raw.text.contains("`elsif B") && raw.text.contains("`elsif C"), "{:?}", raw.text); + assert!(raw.text.ends_with("`endif"), "{:?}", raw.text); + assert!(matches!(m.items[1].kind, ItemKind::DataDecl(_)), "the next item survived"); + } + + #[test] + fn a_block_comment_naming_endif_does_not_fool_the_extent_scan() { + // The extent scan walks tokens, not source text -- a comment is never + // a `TokenKind::Directive`, so text that merely *mentions* `endif + // inside a comment must not be mistaken for the real closer. + let src = "module m;\n assign y =\n`ifdef GATE_LEVEL\n /* not a real `endif here */ \ + a;\n`else\n b;\n`endif\n wire z;\nendmodule\n"; + let f = parse_ok(src); + let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; + let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") }; + assert!(raw.text.contains("not a real"), "{:?}", raw.text); + assert!(raw.text.ends_with("`endif"), "{:?}", raw.text); + assert!(matches!(m.items[1].kind, ItemKind::DataDecl(_)), "the next item survived"); + } + + #[test] + fn an_opening_split_that_is_the_last_item_does_not_eat_the_closing_keyword() { + // No sibling item follows the split in either container -- the scan + // must stop at the split's own terminator and never wander into + // `endmodule`/`endclass`. + let module_src = + "module m;\n assign y =\n`ifdef A\n a;\n`else\n b;\n`endif\nendmodule\n"; + let f = parse_ok(module_src); + let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; + assert_eq!(m.items.len(), 1, "{:?}", split_items(&f)); + let ItemKind::Verbatim(raw) = &m.items[0].kind else { panic!("expected a verbatim block") }; + assert!(raw.text.ends_with("`endif"), "{:?}", raw.text); + + let class_src = "class c;\n function new();\n`ifdef A\n super.new(1);\n`else\n \ + super.new(2);\n`endif\n endfunction\nendclass\n"; + // The `ifdef here opens at a *statement-list* boundary (the function + // body's first statement), which is ordinary directive pass-through, + // not an opening split -- included as the sibling case that must + // stay a pass-through rather than being swept into this recovery. + let f = parse_ok(class_src); + let ItemKind::Class(c) = &f.items[0].kind else { panic!("expected a class") }; + let ItemKind::Function(func) = &c.items[0].kind else { panic!("expected a function") }; + assert!( + matches!(func.stmts[0].kind, StmtKind::Directive(_)), + "a directive starting a statement list is pass-through, not a split" + ); + } } diff --git a/docs/features/directive-in-statements/README.md b/docs/features/directive-in-statements/README.md new file mode 100644 index 0000000..67e2769 --- /dev/null +++ b/docs/features/directive-in-statements/README.md @@ -0,0 +1,608 @@ +# directive-in-statements + +## Goal + +Stop refusing files where a `` `ifdef ``/`` `else ``/`` `endif `` region opens +**part-way through a construct** — splitting an assign's right-hand side, an +expression inside a bracketed list, a call's argument list, an instantiation's +parameter value, or a function's port list. This is bucket 7 of +`syntax_coverage.md` plus its bucket-13 sibling: 7 files across the OpenTitan +sweep, and the specific files are the point — **both chips' top-level +synthesizable RTL** (`chip_earlgrey_asic.sv`, `chip_earlgrey_cw340.sv`), **both +chips' DV probe interfaces** (`top_{earlgrey,darjeeling}/dv/env/chip_if.sv`, +anchor B), and **both chips' DUT top testbenches** +(`top_{earlgrey,darjeeling}/dv/tb/tb.sv`), plus `jtag_dtm_reg_block.sv`. + +Such a region is not a tree, for the same reason `directive-split`'s already +was not: there is no AST that holds "either this expression or that one", and +no layout to apply to something that only becomes a construct after the +preprocessor has chosen an arm. So it joins the **verbatim** bucket — the exact +source bytes, re-indented on the first line only — reached by a *recovery* +after a real parse failure rather than by a grammar rule. This is the sequel +`syntax_coverage.md`'s own implementation note recommends: "the existing +`ItemKind::Verbatim` pattern extends naturally to capture from the failed +statement/instantiation through the shared terminator, exactly as +`directive-split` already does for item-level declarations." + +## Assumptions + +### The gap, stated as a mirror image + +`directive-split` (2026-08-26) recovers when the failure lands on the directive +that **closes** a region opened *before* the construct started, with a bracket +the arm left open. This round is the other half: the failure lands on the +`` `ifdef `` that **opens** a region *inside* the construct. + +```verilog +// closing shape (directive-split, 2026-08-26) -- the item IS an arm +`ifdef DSIM +privileged_reg_t implemented_csr[] = { <- fails at the `else below +`else +const privileged_reg_t implemented_csr[] = { +`endif + MVENDORID +}; + +// opening shape (this round) -- the item CONTAINS the region + assign aes_ctrl_rnd_ctr = +`ifdef GATE_LEVEL <- fails right here + `AES_HIER.u_aes_cipher_control.mr_rnd_ctr[3:0]; +`else + `AES_HIER.u_aes_cipher_control.rnd_ctr; +`endif +``` + +None of the three existing directive features fire on the second shape, and +`syntax_coverage.md`'s Anchor B deep-dive says why: `directives-in-lists` / +`directives-in-instances` sit at the element boundaries of four *bracketed +lists* (port lists, parameter lists, enum members, instantiation +`#()`/connection lists) — an assign's RHS is a single expression, not a list; +`directive-split` needs a bracket already open at a *closing* directive; and +directive pass-through otherwise exists only at item- and statement-list +boundaries. An expression parse has no "this might be a pass-through directive" +branch at all, so it fails immediately, before any bracket is opened and before +`directive-split`'s trigger is ever evaluated. + +### The opening trigger is two conditions, checked in `at_opening_split` + +1. **The cursor stands on an `` `ifdef `` / `` `ifndef ``.** Every other + directive mid-expression is still an ordinary parse error — `` `include ``, + a bare `` `endif ``, a macro call. This is what keeps the net narrow: the + recovery is about conditional *regions*, not about directives in general. +2. **The construct is one unterminated run reaching that directive**: it has + consumed at least one token (a directive standing where an item or a + statement *begins* is an ordinary pass-through directive, unchanged), and + there is no `;` at bracket depth zero between its first token and the + cursor. + +Condition 2 is the load-bearing one and it replaces `directive-split`'s +"a bracket is open" test, which cannot be reused here — at `chip_if.sv:1192` +nothing is open yet, the failure is three tokens into the item. What it buys is +that a failure which **propagated up** from somewhere deeper cannot capture the +construct that happens to enclose it: by the time an error inside a module body +reaches `parse_item_inner`, many `;` at depth zero have gone by, so the module +is refused as a candidate. Without it, one bad expression would turn an entire +`module` into opaque bytes on a guess. + +### The extent follows the first arm, and ends on one of two terminators + +`scan_opening_split_extent` walks from the construct's first token, tracking +brackets and conditional nesting, and — like `scan_split_extent` — on a +`` `else ``/`` `elsif `` it **skips the alternative arms whole** (reusing +`skip_conditional_arms`), because the arms are rival spellings of one thing and +counting all of their brackets would demand as many closers as there are arms. + +Where it stops depends on which side of the region the construct's terminator +was written on, and **both spellings are in the corpus**: + +| shape | corpus evidence | ends at | +|---|---|---| +| each arm carries the construct's own `;` | `chip_if.sv:1189` | the `` `endif `` closing the region | +| the region is balanced *inside* the construct | `chip_earlgrey_asic.sv:621`, `jtag_dtm_reg_block.sv:173` | the `;` after it | + +`terminated_in_arm` is what tells them apart: a `;` met at bracket depth zero +while a region is still open means the tail lives inside the arms. Getting this +wrong in the first direction swallows the next item (there is no `;` after +`chip_if.sv`'s `` `endif ``); getting it wrong in the second truncates the +construct. + +**Every exit leaves conditional nesting back at zero.** A captured block is +therefore conditional-balanced by construction, which is why this recovery — +unlike `directive-split`'s — needs no `open_conds` adjustment at all. Pinned by +`an_opening_split_leaves_item_scope_nesting_alone`. + +### A head that opens a body does not end at its first `;` + +The first draft assumed, as `directive-split` documents it does, that "the +construct's terminator is a `;`". `jtag_dtm_reg_block.sv:273` is the +counterexample — a split `function new(` **header**: + +```verilog + function new(string name = "", +`ifdef USE_DMI_INTERFACE + int unsigned n_bits = 50, +`else + int unsigned n_bits = 41, +`endif + int has_coverage = UVM_NO_COVERAGE); + super.new(name, n_bits, has_coverage); + endfunction : new +``` + +That `;` closes a *header*. Stopping there captured the header, left the body +behind as items, and the file failed on `super` three lines later — a worse +diagnostic than the one it replaced. So `construct_end` reads the construct's +head and answers one of three things: + +- `Semi` — the default, and what every identifier-headed construct gets + (instantiation, call statement, assignment) along with every declaration + keyword. Unchanged from `directive-split`'s assumption. +- `Keyword("endfunction")` / `Keyword("endtask")` — the two body-opening heads + the corpus needs. The block runs to the closing keyword and takes the + `: label` it may carry (`past_end_label`), because a label left outside would + be parsed as an item. +- `Unknown` — every other body-opening keyword (`BODY_KEYWORDS`: `module`, + `class`, `case`, `begin`, `for`, `always`, …). **Refused outright**, because + capturing at a `;` would produce exactly the truncated head above and nothing + in the corpus asks for these. + +`TF_QUALIFIERS` (`virtual`, `static`, `automatic`, `local`, `protected`) are +skipped in front of `function`/`task`. `extern` and `pure` are deliberately +**not** in that list: those spell a prototype, which really does end at its `;`, +so they fall through to `Semi`, which is correct for them. + +### `take_list_directives` must not harvest an outer region's seam + +The two `tb.sv` files (bucket 13) fail for a related but distinct reason, and +they need no new recovery at all — `directive-split`'s existing one already +fits, it just never got to see the failure: + +```verilog +`ifdef DISABLE_ROM_INTEGRITY_CHECK + chip_earlgrey_asic #( .SecRomCtrlDisableScrambling(1'b1) ) dut ( +`else + chip_earlgrey_asic dut ( +`endif + .POR_N(...), ... + ); +``` + +The parser accepts the first arm's head, opens the shared connection list, and +inside it meets the `` `else ``. `take_list_directives` harvested *any* +directive found inside a list's brackets as conditioning list elements, so it +took the `` `else ``, then read `chip_earlgrey_asic` (the second arm's module +name) as a positional connection — which succeeds, as a bare identifier — and +failed two tokens later at `dut`, three lines from the actual seam. + +`at_outer_arm_split` stops that: a `` `else ``/`` `elsif ``/`` `endif `` that +**this list did not open** (counted over the list's own harvested directives), +while a region opened at **item** scope is still live (`open_conds > 0`, the +same "a region is live" guard `at_split_conditional` makes), is not conditioning +elements — it is the seam. The harvest breaks, the item fails standing on the +directive, and `at_split_conditional`'s four conditions all hold: the whole +instantiation becomes one verbatim block. + +Both halves of the guard matter. Without `open_conds > 0` an ordinary +list-internal region would be refused; without the "did not open it" count the +`` `endif `` of a legitimately list-internal region would be. Pinned from both +sides by `an_ifdef_that_splits_an_instantiation_head_is_still_the_closing_shape` +and `a_list_internal_region_is_still_harvested_as_list_elements`, and by the +`.cases` control entry. + +### The statement level runs first, and only the opening shape + +The recovery is wired into **both** `parse_item_inner` and `parse_stmt_inner`. +The statement one is what keeps `jtag_dtm_reg_block.sv:173`'s capture at the +`abits.configure(...)` statement instead of at the enclosing `class`: an error +raised inside a function body propagates outward, and the innermost frame that +recognizes the shape must claim it first. (Condition 2 above would refuse the +enclosing item anyway — the belt to this braces — but the useful capture is the +narrow one.) + +Statements get **only** the opening shape. The closing shape is item-scope by +construction: `Parser::open_conds` counts the `` `ifdef ``s consumed *as items*, +per `directive-split`'s rule, so `mark.conds` inside a body would be answering a +question about a different scope. No corpus file asks for it. + +### What is deliberately still refused + +- Any non-conditional directive mid-expression. +- A stray `` `else ``/`` `endif `` with nothing open. +- An unterminated region, or a construct with no terminator before EOF. +- Brackets that do not balance across the chosen arm. +- A plain syntax error that merely sits near a directive. +- Any body-opening head other than `function`/`task`. + +All seven pinned by `the_opening_split_refuses_everything_it_does_not_model` +and re-run against the release binary on standalone files. + +### One deliberate widening, and it supersedes a test + +`parser.rs`'s `a_directive_inside_a_connection_is_still_a_parse_error` pinned +that a conditional region written *inside* a connection's parens is refused — +"out of scope by design". That premise is exactly what this round changes: +`chip_earlgrey_asic.sv:621` writes one inside a parameter value's +concatenation, which is the same shape. The test is renamed +`a_directive_inside_a_connection_is_captured_or_refused_by_kind` and now pins +both halves — the conditional region is captured verbatim, any other directive +there is still an ordinary parse error. This is the only pre-existing test whose +expectation changed, and the only shape whose accept/refuse verdict moved +outside the seven target files (measured: see the Work log's sweep diff). + +### A currently-passing file cannot be affected + +Both recoveries are reached only from an `Err` arm, and a file that formats +today produces no such `Err`. The one exception is `at_outer_arm_split`, which +runs on the **success** path — so it was measured rather than argued: the +820-file corpus gate produces byte-identical per-file results before and after, +and the 3,943-file OpenTitan sweep's pass set is a strict superset with no file +moving out. + +## Handshakes + +### Consumed + +- `Parser::verbatim_since(start, col)` — slices `source[span]` into a `RawText` + and drops the comment copies falling inside the span. Used unchanged. +- `Fmt::raw_text(raw)` / `Fmt::raw_lines(text, col)` — the verbatim printer. + Used unchanged; no formatter source file was touched by this round. +- `Parser::skip_conditional_arms` — `directive-split`'s arm skipper, reused by + the opening-shape scan with the same meaning. +- `Parser::open_conds` — read (never written) by `at_outer_arm_split`, which is + its third reader. `directive-split`'s rule that only `note_item_conditional` + and `split_conditional_item` may *write* it is preserved: this round adds no + writer, because an opening-split block is conditional-balanced. +- `ItemKind::Verbatim(RawText)` gained a **sixth** producer and + `StmtKind::Verbatim(RawText)` a **second** (after the concurrent assertions). + No signature changed, so no exhaustive match anywhere needed a new arm — + `format.rs`, `bind.rs`, `visit.rs`, `spans.rs` and the linter are untouched. + **No new AST variant, no new AST field.** + +### Promised / changed for others + +- **`crates/vlog_formatter/src/verify.rs` is untouched.** No normalization was + added and no forgiveness widened. Verbatim bytes need none: a captured block + is re-lexed as ordinary tokens on both sides, so every token inside it must + still match, and all seven newly-passing OpenTitan files go through the + runtime safety net (`lucisv --check`, which verifies) plus a two-pass + idempotency check. +- **Request to whoever next owns `crates/vlog_formatter/tests/verification.rs`:** + `directive-split` shipped ten invariant-#4 attack tests there even though it + too left `verify.rs` alone, on the grounds that a verbatim capture is + forgiveness-*adjacent*. The equivalent tests for this round were **not** + added, because `verification.rs` is Lane B's file this wave and a silent edit + would break the merge contract. The seven refusal shapes are pinned in + `parser.rs` instead (`the_opening_split_refuses_everything_it_does_not_model`) + and were re-run against the release binary. Adding the (input, corrupted + output) pairs to `verification.rs` after the merge is a QA-sized task and is + recommended. +- **New private parser surface only.** Two consts (`BODY_KEYWORDS`, + `TF_QUALIFIERS`), one enum plus its reader (`ConstructEnd`, + `construct_end`), two free functions (`directive_word_of` — extracted from + the existing `directive_word` so a harvested `RawText` can be classified — + and `take_since`), and seven `Parser` methods (`take_gap`, + `at_outer_arm_split`, `at_opening_split`, `scan_opening_split_extent`, + `past_end_label`, `capture_split`, `split_conditional_stmt`). Nothing is + `pub`. `split_conditional_item`'s body was split so `capture_split` is shared + by both shapes; its behaviour on the closing shape is unchanged. +- **Delivered: `formatter-bug-fixes` round 2's `take_before_open` request.** + See that README's Handshakes section, marked DELIVERED, and the work log + below. `Parser::take_before_open` and the empty-call `CallComments::dangling` + harvest now take only the comments written in the gap that ends at the + bracket (`Parser::take_gap`), instead of draining the whole pending queue. + +### Requests to other clusters + +- **`directives-in-lists`**: a function/task port list + (`Parser::parse_tf_ports`) still has no directive harvest, because `TfArg` + lists carry no `Vec` and adding one is an AST change with + printer arms. `jtag_dtm_reg_block.sv:273` is therefore *captured verbatim* + rather than formatted. Teaching that list the existing harvest would be + strictly better output for the same file, and belongs to whoever owns the + `directives-in-lists` surface plus `format.rs`. +- **`StmtKind::Return` has no comment slot**, so `return // c` ⏎ `g();` still + refuses (see the formatter-bug-fixes note). Not a directive matter; recorded + because this round's parser change is what isolates it. + +## Status / TODO + +- [x] Baseline recorded: OpenTitan sweep 107 failures at `17633d2`, corpus gate + 813/820, both re-run from a pristine scratchpad build of `HEAD`. +- [x] Parser: `at_opening_split` (the trigger), `scan_opening_split_extent` + (the extent), `past_end_label`, `construct_end` + `BODY_KEYWORDS` + + `TF_QUALIFIERS`. +- [x] Parser: `capture_split` extracted so both shapes share the rewind/walk. +- [x] Parser: `at_outer_arm_split`, the `take_list_directives` guard, and the + `directive_word_of` refactor it needs. +- [x] Parser: statement-level recovery in `parse_stmt_inner` + (`split_conditional_stmt`), opening shape only. +- [x] Handshake (item 2): `take_before_open` + empty-call `dangling` narrowed + to `take_gap`. +- [x] 10 new parser tests, including the 7-shape refusal test and the two + comment-ownership tests; one superseded test rewritten to pin both halves + (`vlog_parser` lib suite 224 → 234). +- [x] 7 cases in `crates/vlog_formatter/tests/cases/directive_in_statements.cases` + (the harness asserts idempotency on every one). +- [x] All 7 target OpenTitan files parse and format strict-clean; two-pass + idempotency and unchanged on-disk md5 confirmed for each. +- [x] Sweep 107 → 100, pass set a strict superset, no message changed on any + still-failing file. +- [x] Corpus gate byte-identical to baseline (813/820). +- [x] `cargo fmt --all`, `cargo clippy --all-targets`, `cargo test --workspace` + clean. +- [ ] **Not done, deliberately:** directive harvesting in function/task port + lists (needs an AST field — see Requests); body-opening heads other than + `function`/`task`; any canonical *layout* for the inside of a captured + region — it stays byte-for-byte; the invariant-#4 attack pairs in + `verification.rs` (Lane B's file — see Promised/changed). + +## Work log + +### 2026-08-29 — dev + +**Setup.** Worktree branched at `34b766c`, fast-forwarded to `master` +(`17633d2`, Lane A merged) before any edit, so the round builds on the freed +`parser.rs`. All measurement against the real checkout at +`/Users/guoliangchen/repo/opentitan` (HEAD `0098135`), read-only — every probe +uses `--check`/`--stdout` with `--no-cache`, and each target file's md5 was +compared before and after. + +**Baseline** (pristine `git archive HEAD` build in the scratchpad, so before and +after are the same corpus and the same commands): OpenTitan sweep **107** +failures over 3,943 files; corpus gate +`{"passing":813,"total":820,"pct":99.1,...}`. + +**Item 1 — the design choice.** Verbatim capture, reached by two recoveries +that share one extent-capture step, rather than new grammar. Justified against +the three existing directive features' contracts in Assumptions above; the +short version is that the arms of a split region are rival spellings of one +construct, there is no tree that holds "either this or that", and the four +existing pass-through sites are all list-element boundaries that an expression +does not have. No AST variant and no AST field was added, so `format.rs`, +`bind.rs`, `spans.rs`, `visit.rs` and the linter are untouched — which is also +what kept this round inside its file-ownership list while Lane B held the +formatter. + +Three things were learned by building it, each recorded above as an assumption: + +1. The corpus writes the construct's terminator on **both** sides of the region + (`chip_if.sv` inside the arms, `chip_earlgrey_asic.sv` after them), so one + terminator rule is not enough — hence `terminated_in_arm`. +2. `directive-split`'s "the terminator is a `;`" assumption is **false for a + function header**. The first build of this round captured + `jtag_dtm_reg_block.sv`'s `function new(...)` header and orphaned its body, + moving the file's error from line 173 to line 280. `construct_end` is the + answer, and it refuses by default for every body-opening head it does not + model. +3. The two `tb.sv` files needed **no new recovery** — only that + `take_list_directives` stop hiding the seam from the recovery that already + existed. That is the smallest change in the round and the one that fixes the + two highest-value files. + +**Item 1 — result.** All 7 target files clean: + +| file | before | after | +|---|---|---| +| `hw/top_earlgrey/dv/env/chip_if.sv` | `1192:1: expected expression` | formats | +| `hw/top_darjeeling/dv/env/chip_if.sv` | `894:1: expected expression` | formats | +| `hw/top_earlgrey/rtl/autogen/chip_earlgrey_asic.sv` | `621:1: expected expression` | formats | +| `hw/top_earlgrey/rtl/autogen/chip_earlgrey_cw340.sv` | `502:1: expected expression` | formats | +| `hw/dv/sv/jtag_agent/jtag_dtm_reg_block.sv` | `173:1: expected expression` | formats | +| `hw/top_earlgrey/dv/tb/tb.sv` | `114:22: expected \`)\` (found "dut")` | formats | +| `hw/top_darjeeling/dv/tb/tb.sv` | `105:24: expected \`)\` (found "dut")` | formats | + +Whole-sweep **107 → 100**. `comm -13` over the sorted failure lists is empty +(nothing regressed); `comm -23` is exactly those seven files; and no file that +still fails changed its message. Each of the seven was formatted twice through +`--stdout` and the passes compared byte-for-byte — **idempotent** — with the +checkout's md5 unchanged. Corpus gate re-run with both binaries against the +same pinned corpus: **813/820 both times, and `diff` over the two per-file +result tables is empty**, not merely the same total. + +**Item 2 — the handshake.** Implemented as specified — +`take_before_open` keeps only comments with `span.start >= self.last_end()` — +and then found by bisection that it was not sufficient on its own: with +`before_open` fixed, the pinned shape's comment was swallowed one line later by +`CallComments::dangling`, the empty-`()` harvest, which drains the queue the +same way. Both now go through one narrow helper, `Parser::take_gap()`. The +"or better, justified" clause of the brief covers the second site; it is the +same defect at the same struct, and without it the handshake does not deliver. + +Verified by composing this lane's `parser.rs` with Lane B's worktree in a +scratchpad copy — their files were read, never written — and running their whole +workspace suite: everything stays green **except** +`a_comment_before_a_call_in_a_condition_is_still_refused`, which flips from pass +to fail, i.e. the shape now formats: + +``` + if ( + // why + !en() || b + ) begin +``` + +and the real `hw/ip/keymgr/dv/env/keymgr_scoreboard.sv` — the 12th and last +bucket-2 file, which Lane B could not fix from inside `vlog_formatter` — formats +cleanly end to end. Lane B's `expect_divergence` attack pairs all still pass; +`verify.rs` is untouched by either lane. Marked DELIVERED in +`docs/features/formatter-bug-fixes/README.md`. + +**Deviations from the brief, all flagged:** + +1. **No formatter `.cases` entry proves the keymgr line-1254 shape in *this* + worktree**, because half the fix is Lane B's: `Fmt::header_parens` (their + round 2) is what gives a comment written after `if (` a home. At `17633d2` + that shape is refused with or without this round's parser change — confirmed + against the pristine baseline binary — so a case asserting it here would + fail. The parser side is pinned instead by two new parser tests + (`a_comment_after_an_opening_bracket_is_not_stolen_by_an_inner_call`, which + asserts both call comment slots are empty and the comment reaches the body's + leading comments where `header_parens` collects it, and + `a_comment_actually_written_before_a_bracket_is_still_taken` for the other + side), and end to end by the composed run above. **The `.cases` entry belongs + to the merged tree** and is the natural first QA task after the merge. +2. **Only one pinned refusal test exists**, not two. Lane B's README names one + (`a_comment_before_a_call_in_a_condition_is_still_refused`) and describes + `return // c` ⏎ `g();` as a second *symptom*, which is not pinned as a test. + That symptom is **not** fixed by this round and is refused identically before + and after: it needs a comment slot on `StmtKind::Return`. Recorded as a + request above. +3. **One pre-existing parser test's expectation changed** + (`a_directive_inside_a_connection_is_still_a_parse_error`), because the + behaviour it pinned is the behaviour this round adds. Rewritten to pin both + halves rather than deleted; rationale in Assumptions. +4. **`docs/features/formatter-bug-fixes/README.md` was edited** — the + Handshake-status edit the brief sanctions. This worktree holds the *trunk* + copy of that file, which does not yet contain Lane B's round-2 Handshakes + text, so the new `### Round 2's take_before_open request — DELIVERED` + subsection sits where Lane B also appends. **A merge conflict there is + expected and the resolution is to keep both blocks.** + +**Gates.** `cargo fmt --all --check` clean, `cargo clippy --all-targets` clean +(no new warnings, no `#[allow]` added), `cargo test --workspace` green, corpus +gate exactly at baseline. No `git commit`, no `git push`. + +## QA log + +### 2026-08-29 — QA + +**Verdict: SHIP.** No corruption, no capture-extent bug, no comment +relocation found across the adversarial charter. All claimed numbers +reproduced exactly. `vlog_parser` lib suite: 234 → 238 (4 new QA regression +tests added, all passing; see below). + +**Gates**, all re-run from a fresh build in this worktree: +- `cargo fmt --all --check`: clean. +- `cargo clippy --all-targets`: clean, no new warnings. +- `cargo test --workspace --no-fail-fast`: green, every crate, 0 failures. + +**Reproduction of the round's numbers**, against a pristine `17633d2` binary +built in a separate `git worktree` (never touching this lane's tree) for +every "before" comparison: +- OpenTitan sweep (`/Users/guoliangchen/repo/opentitan`, HEAD `0098135`, + read-only, `--no-cache --check`, both binaries against the identical + 3,943-file list): baseline **107**, round **100**. `comm -13` (round-only + failures, i.e. regressions) is **empty**. `comm -23` (fixed) is **exactly** + the 7 named files. Joined the two failure tables on filename and diffed + the messages for every file failing in both: **zero** changed. +- The 7 target files: each formats (`--check` exit 0 or 1, never 2), each + two-pass idempotent (`--stdout` output fed back in produces byte-identical + output), and each file's on-disk md5 confirmed unchanged before/after. +- Corpus gate (`scripts/score.sh` against the real 820-file `corpus/`, not + reachable by name from inside a worktree — BSD `find` on this machine + does not descend into a directory given to it as a symlink without `-L`, + which `score.sh` doesn't pass, so the corpus has to be referenced by its + real path rather than a `corpus` symlink dropped in the worktree root): + baseline `{"passing":813,"total":820,...}`, round identical, and + `diff` over the two `-o details.tsv` per-file tables is **empty** — + not just the same count, the same outcome for every one of the 820 files. +- Composed-tree claim (Lane B's worktree, + `.claude/worktrees/agent-a8ee7330b649bc150` @ `d3deacf`, read-only — + rsynced to a scratch copy, Lane B's files untouched, only this lane's + `parser.rs` overlaid on top): `cargo test --workspace --no-fail-fast` + is green except exactly + `verification.rs::a_comment_before_a_call_in_a_condition_is_still_refused`, + which flips from pass to fail because the shape it pins now *formats* — + matching the dev's report precisely, one flip and no other change. Built + the composed release binary and confirmed + `hw/ip/keymgr/dv/env/keymgr_scoreboard.sv` formats end-to-end and is + two-pass idempotent. + +**Adversarial testing** (the charter's three named sins: a capture that eats +too much, a refusal that became corruption, a comment that moved homes). +Built two probe harnesses — a temporary `vlog_parser` integration test +(deleted after use, not part of the final diff) dumping parsed-tree +summaries, and a set of standalone `.sv` files run through both the round +and baseline release binaries with `--stdout`/`--check`/idempotency: + +- Nested `` `ifdef `` (with its own `` `elsif ``/`` `else ``) fully inside an + opening split's first arm, itself inside an outer already-open region: + captures the right byte range, `open_conds` lands back at exactly the + outer count, next item survives. No prior test combined all three levels + at once. +- A 4-arm `` `elsif `` chain in an opening split: captured through the final + `` `endif ``, not an intermediate arm. +- A block comment whose text contains the literal string `` `endif `` + inside the region: does not fool the extent scan (comments are never + `TokenKind::Directive`, so this was never actually at risk, but it is now + pinned). +- A string literal containing the literal text `` `endif `` as data, and a + string literal containing a bare `;`: neither confuses the bracket/`;` + scan, since both are lexed as single opaque tokens. +- `` `define ``/`` `include `` written inside the captured region: swept as + ordinary opaque directive tokens, included verbatim, no special handling + needed or present. +- The split construct as the last item of its `module`/`class` (no sibling + item follows): extent scan stops at its own terminator, never wanders + into `endmodule`/`endclass`. +- Two independent opening splits back-to-back in the same module: each + captured as its own `Verbatim` item; the first's capture does not bleed + into the second's region. +- Mismatched bracket nesting *across* arms (deliberately malformed, + adversarial input, not valid SV): the scanner follows only the first arm + as documented, produces a verbatim capture, formats and reparses clean — + no corruption, matching the documented "follow the first arm, skip the + rest whole" policy. +- Comment-ownership sweep for the `take_gap` handshake: comments in empty + call parens (both before and after), nested calls each with their own + comment, a comment between `!` and its callee, a bare macro call with a + comment inside its parens, a `$display` system-call comment, and a + three-comment instantiation connection list (before/between/trailing) — + diffed byte-for-byte between the baseline and round binaries. **All six + are identical**, including the still-refused `!en()`/`return` shapes + (refused by both, same diagnostic), confirming `take_gap` changed nothing + for any comment site outside the one it was built to fix. + +One false alarm, recorded for the record: an ad hoc probe +(`` `ifdef ``/`` `else ``/`` `endif `` conditioning a bare positional call +argument with no comma, i.e. `f(` `` `ifdef A `` `1` `` `else `` `2` +`` `endif `` `);`) initially looked like a diagnostic-quality regression — +the round's error landed three lines away from the baseline's. Root cause +was the probe file itself, not the parser: it placed a bare `x = 1;` +directly as a *module item* (only legal inside a procedural block), an +unrelated pre-existing syntax error that the baseline never reached because +it failed earlier. Corrected to `initial begin ... end`, the shape formats +cleanly and idempotently on both sides — not a finding. + +**Tests added** (`crates/vlog_parser/src/parser.rs`, `#[cfg(test)] mod +tests`, appended after the round's own directive-in-statements block; lib +suite 234 → 238, all green): +`a_nested_ifdef_with_its_own_elsif_survives_inside_an_opening_split_under_an_outer_region`, +`an_elsif_chain_in_an_opening_split_is_captured_through_the_final_endif`, +`a_block_comment_naming_endif_does_not_fool_the_extent_scan`, +`an_opening_split_that_is_the_last_item_does_not_eat_the_closing_keyword`. +None of these were failing before they were added correctly (the first one +initially failed on a test-construction mistake — a trailing `` `endif `` +that closed the "still open" outer region I meant to leave open, and a +wrong item index once the outer `` `ifdef `` became a sibling file item — +both fixed in the test, not the parser); they exist to guard the +adversarial coverage above against a future regression, since none of it +was pinned by the round's own 10 tests. + +**Not independently re-verified**: the `verify.rs`/invariant-#4 attack-test +request the dev's Handshakes section files against `verification.rs` +(Lane B's file this wave) — correctly left undone here too, per the +merge-contract rule (`crates/vlog_formatter/tests/verification.rs` is +outside this lane's file-ownership list). Recommended as the first QA task +after the merge, as both this round's and Lane B's READMEs already say. + +## Review + +**2026-08-29 — lead.** Reviewed after QA's zero-finding SHIP; gates +re-run on the worktree. The round's craft shows in what it refused to +do: construct_end's Unknown → refuse arm turns "I don't understand +this head" into a clean error instead of a guess (the jtag +first-build bug caught by the dev's own testing is exactly why that +arm exists), and the tb.sv fix being three lines in +take_list_directives rather than a new recovery is the +smallest-change discipline paying out on the highest-value files. +Item 2's bisection — the specified fix necessary but not sufficient, +the second drain found and unified behind take_gap — is why +"implement exactly that, or better, justified" is written into every +such handoff. The composed-tree verification against Lane B's +worktree was the right way to prove a cross-lane delivery without a +cross-lane edit, and QA reproduced it independently. Deviations all +accepted; the two post-merge items (keymgr .cases entry, the +standing-template attack pairs in verification.rs) are the lead's and +are done in the merge commit's follow-up. Accepted; merged by the +lead. OpenTitan sweep: 151 at the wave's start, 100 after this round. diff --git a/docs/features/formatter-bug-fixes/README.md b/docs/features/formatter-bug-fixes/README.md index 2f4c5fa..86fec8a 100644 --- a/docs/features/formatter-bug-fixes/README.md +++ b/docs/features/formatter-bug-fixes/README.md @@ -196,6 +196,41 @@ refused. Three more bugs, all in `format.rs`'s layout, none needing a release or a stale `.lucisv_cache` will skip files that would now format differently. Flagged for the lead; no version was bumped here. +### Round 2's `take_before_open` request — **DELIVERED** (2026-08-29) + +Filed by round 2 against whoever owns `crates/vlog_parser/src/parser.rs`; +answered by the `directive-in-statements` round (see +`docs/features/directive-in-statements/README.md`). The requested change and +one more site it needed: + +- `Parser::take_before_open` no longer calls `take_dangling()`. It takes only + the comments whose `span.start >= self.last_end()` — the gap that ends at + the bracket — through a new narrow sibling, `Parser::take_gap()`. Exactly + the fix round 2 specified. +- **That alone was not enough.** `CallComments::dangling` (the inside of an + *empty* `()`, `parser.rs`'s postfix-call arm) drained the whole queue too, + so with `before_open` fixed the comment was swallowed one line later — + which is why the pinned shape's condition starts `!en()` and not `!en(x)`. + It now uses `take_gap()` as well. Both sites are `CallComments`; nothing + else changed. + +Verified by composing this lane's parser with round 2's worktree in a +scratchpad copy (round 2's files read-only, never edited): the whole workspace +suite stays green except +`verification.rs::a_comment_before_a_call_in_a_condition_is_still_refused`, +which flips from pass to fail — i.e. the shape now formats — and the real +`hw/ip/keymgr/dv/env/keymgr_scoreboard.sv` formats cleanly, closing the 12th +and last bucket-2 file. That test should become a `.cases` entry at merge, as +round 2 predicted. Round 2's `expect_divergence` attack pairs all still pass: +`verify.rs` is untouched by either lane. + +Still open, and **not** this handshake: `return // c` ⏎ `g();`, round 2's +"second, independent symptom". The parser no longer misplaces that comment +into the call, but nothing owns a comment written between `return` and its +expression, so it drifts and the safety net still refuses the file — refused +before this round and refused after, byte-identical either way. It needs a +comment slot on `StmtKind::Return`, which is an AST change with printer arms. + ## Status / TODO - [x] Bug 3 — closing block labels preserved (`end`, all `join` kinds,