diff --git a/crates/vlog_formatter/tests/cases/directive_split.cases b/crates/vlog_formatter/tests/cases/directive_split.cases new file mode 100644 index 0000000..6a4be42 --- /dev/null +++ b/crates/vlog_formatter/tests/cases/directive_split.cases @@ -0,0 +1,320 @@ +# alternative declaration heads sharing one body: the whole construct is one +# verbatim block, so it comes back byte for byte +# corpus/ibex/vendor/google_riscv-dv/target/rv32imc/riscv_core_setting.sv:98 +`ifdef DSIM +privileged_reg_t implemented_csr[] = { +`else +const privileged_reg_t implemented_csr[] = { +`endif + MVENDORID, // Vendor ID + MARCHID // Architecture ID +}; + +parameter int AFTER = 1; +---- +`ifdef DSIM +privileged_reg_t implemented_csr[] = { +`else +const privileged_reg_t implemented_csr[] = { +`endif + MVENDORID, // Vendor ID + MARCHID // Architecture ID +}; + +parameter int AFTER = 1; +==== +# alternative struct bodies sharing one closing brace, inside a package +# corpus/ibex/vendor/google_riscv-dv/src/riscv_instr_pkg.sv:1236 +package p; +`ifdef _VCP + typedef struct packed { + bit l; +`else + typedef struct{ + rand bit l; +`endif + } pmp_cfg_reg_t; + + parameter int AFTER = 1; +endpackage +---- +package p; + `ifdef _VCP + typedef struct packed { + bit l; + `else + typedef struct{ + rand bit l; + `endif + } pmp_cfg_reg_t; + + parameter int AFTER = 1; +endpackage +==== +# the block's *relative* layout is what survives: only the first line is +# re-indented to the item's level, the rest is dedented by the block's start +# column and indented back -- the fixed-point trick `constraint` uses +module m; +`ifdef A + logic [3:0] x[] = { +`else + const logic [3:0] x[] = { +`endif + 4'h1, + 4'h2 + }; + assign y = 1; +endmodule +---- +module m; + `ifdef A + logic [3:0] x[] = { + `else + const logic [3:0] x[] = { + `endif + 4'h1, + 4'h2 + }; + assign y = 1; +endmodule +==== +# `ifndef and an `elsif chain: three rival spellings of one head, one body. +# Only the first arm's `{` is counted, so the scan does not go looking for +# two more closing braces. +`ifndef A +int x[] = { +`elsif B +const int x[] = { +`else +static int x[] = { +`endif + 1 +}; +---- +`ifndef A +int x[] = { +`elsif B +const int x[] = { +`else +static int x[] = { +`endif + 1 +}; +==== +# a *balanced* region inside the shared tail is ordinary conditional text and +# does not end the block early -- the item after it is still its own item +`ifdef A +int x[] = { +`else +const int x[] = { +`endif + 1, +`ifdef B + 2, +`endif + 3 +}; + +parameter int AFTER=1; +---- +`ifdef A +int x[] = { +`else +const int x[] = { +`endif + 1, +`ifdef B + 2, +`endif + 3 +}; + +parameter int AFTER = 1; +==== +# comments: the one before the region leads the `ifdef, the ones written on +# the directives and inside the arms are part of the verbatim bytes, and the +# one after the terminating `;` stays outside the block and trails it +// head +`ifdef A // which +int x[] = { // open +`else // other +const int x[] = { +`endif + // why + 1 +}; // done +int y; +---- +// head +`ifdef A // which +int x[] = { // open +`else // other +const int x[] = { +`endif + // why + 1 +}; // done +int y; +==== +# NEGATIVE: a region whose arms are each a whole item is not a split -- both +# arms are parsed and laid out normally, as they always were +`ifdef A +wire x; +`else +wire y ; +`endif +---- +`ifdef A +wire x; +`else +wire y; +`endif +==== +# NEGATIVE: a bracket that opens *and closes* inside one arm leaves nothing +# open, so the region is ordinary text around ordinary items +`ifdef A +int x[] = {1, 2}; +`else +int x[] = {3, 4}; +`endif +---- +`ifdef A +int x [] = {1, 2}; +`else +int x [] = {3, 4}; +`endif +==== +# a genuine split nested INSIDE a legitimately-open outer region: the guard +# added for QA's stray-`endif finding is "a region is live", not "exactly one +# region is live", so this still recovers +`ifdef OUTER +`ifdef DSIM +privileged_reg_t csr[] = { +`else +const privileged_reg_t csr[] = { +`endif + MVENDORID +}; +`endif +parameter int AFTER = 1; +---- +`ifdef OUTER +`ifdef DSIM +privileged_reg_t csr[] = { +`else +const privileged_reg_t csr[] = { +`endif + MVENDORID +}; +`endif +parameter int AFTER = 1; +==== +# the same, shape B, inside a package inside an outer region +package p; +`ifdef OUTER +`ifdef _VCP + typedef struct packed { + bit l; +`else + typedef struct{ + rand bit l; +`endif + } pmp_cfg_reg_t; +`endif + parameter int AFTER = 1; +endpackage +---- +package p; + `ifdef OUTER + `ifdef _VCP + typedef struct packed { + bit l; + `else + typedef struct{ + rand bit l; + `endif + } pmp_cfg_reg_t; + `endif + parameter int AFTER = 1; +endpackage +==== +# NEGATIVE: a stray `endif closes nothing, so the declaration next to it is +# not a split -- and, since neither is a parse error on its own, both stay +# ordinary items (lucisv does not validate directive nesting, and did not +# before this work either) +wire a; +`endif +int x[] = {1}; +---- +wire a; +`endif +int x [] = {1}; +==== +# over-suppression guard: directives written inside an opaque `constraint` +# body no longer touch item-scope nesting, but the region around the body +# still counts, so a genuine split after it still recovers +class c; + constraint co { +`ifdef X + x < 10; +`endif + } +endclass + +`ifdef DSIM +int y[] = { +`else +const int y[] = { +`endif + 1 +}; +parameter int AFTER = 1; +---- +class c; + constraint co { + `ifdef X + x < 10; + `endif + } +endclass + +`ifdef DSIM +int y[] = { +`else +const int y[] = { +`endif + 1 +}; +parameter int AFTER = 1; +==== +# under-suppression guard: an earlier verbatim item (a constraint) inside the +# very region the split sits in -- the outer `ifdef must still be counted +`ifdef OUTER +class c; + constraint co {x < 10;} +endclass + +`ifdef DSIM +int y[] = { +`else +const int y[] = { +`endif + 1 +}; +`endif +parameter int AFTER = 1; +---- +`ifdef OUTER +class c; + constraint co {x < 10;} +endclass + +`ifdef DSIM +int y[] = { +`else +const int y[] = { +`endif + 1 +}; +`endif +parameter int AFTER = 1; diff --git a/crates/vlog_formatter/tests/verification.rs b/crates/vlog_formatter/tests/verification.rs index 3d27647..ec346a0 100644 --- a/crates/vlog_formatter/tests/verification.rs +++ b/crates/vlog_formatter/tests/verification.rs @@ -1129,3 +1129,131 @@ fn a_property_declarations_local_variable_may_not_be_dropped() { let output = "module m;\n property p;\n a |-> b;\n endproperty\nendmodule\n"; expect_divergence(input, output); } + +// ---------------------------------------------------------------------- +// Split conditional regions (`docs/features/directive-split/README.md`) +// +// The recovery adds no forgiveness to the safety net -- verbatim bytes need +// none -- but the capture is forgiveness-*adjacent* in exactly the way the +// assertions above are: the block is re-lexed as ordinary tokens on both +// sides, so every token inside it must still match. These are the crafted +// (input, corrupted output) pairs CLAUDE.md's invariant #4 asks for, plus the +// legitimate transformation that keeps the rejections from being vacuous. +// ---------------------------------------------------------------------- + +/// The one shape all of these attack: alternative declaration heads sharing a +/// body (`riscv_core_setting.sv:98`). +fn split_region() -> String { + "`ifdef DSIM\nprivileged_reg_t csr[] = {\n`else\nconst privileged_reg_t csr[] = {\n\ + `endif\n // vendor\n MVENDORID\n};\n" + .to_string() +} + +#[test] +fn a_split_conditional_region_may_be_reindented() { + let input = format!("module m;\n{}endmodule\n", split_region()); + let output = format_source(&input, &Config::default()).expect("must format"); + verify_equivalence(&input, &output).expect("only indentation changed"); + // ... and the second pass is a fixed point, which is what makes a + // verbatim block safe to re-indent at all. + let twice = format_source(&output, &Config::default()).expect("must format again"); + verify_convergence(&output, &twice).expect("idempotent"); +} + +#[test] +fn a_dropped_arm_of_a_split_region_is_rejected() { + let input = split_region(); + let output = "`ifdef DSIM\nprivileged_reg_t csr[] = {\n`endif\n // vendor\n MVENDORID\n};\n"; + expect_divergence(&input, output); +} + +#[test] +fn a_dropped_endif_of_a_split_region_is_rejected() { + let input = split_region(); + let output = "`ifdef DSIM\nprivileged_reg_t csr[] = {\n`else\nconst privileged_reg_t csr[] = {\n // vendor\n MVENDORID\n};\n"; + expect_divergence(&input, output); +} + +#[test] +fn a_dropped_comment_inside_a_split_region_is_rejected() { + let input = split_region(); + let output = "`ifdef DSIM\nprivileged_reg_t csr[] = {\n`else\nconst privileged_reg_t csr[] = {\n`endif\n MVENDORID\n};\n"; + expect_divergence(&input, output); +} + +#[test] +fn a_split_regions_arms_may_not_be_swapped() { + // Both arms are still there and the bytes still balance -- only which + // one the `else selects has changed, which is a semantic rewrite. + let input = split_region(); + let output = "`ifdef DSIM\nconst privileged_reg_t csr[] = {\n`else\nprivileged_reg_t csr[] = {\n`endif\n // vendor\n MVENDORID\n};\n"; + expect_divergence(&input, output); +} + +#[test] +fn a_changed_ifdef_condition_is_rejected() { + let input = split_region(); + let output = "`ifdef VCS\nprivileged_reg_t csr[] = {\n`else\nconst privileged_reg_t csr[] = {\n`endif\n // vendor\n MVENDORID\n};\n"; + expect_divergence(&input, output); +} + +#[test] +fn a_dropped_element_of_a_split_regions_shared_body_is_rejected() { + let input = "`ifdef DSIM\nint x[] = {\n`else\nconst int x[] = {\n`endif\n 1,\n 2\n};\n"; + let output = "`ifdef DSIM\nint x[] = {\n`else\nconst int x[] = {\n`endif\n 1\n};\n"; + expect_divergence(input, output); +} + +#[test] +fn a_split_region_keeps_a_multiline_string_byte_for_byte() { + let input = "`ifdef DSIM\nstring x[] = {\n`else\nconst string x[] = {\n`endif\n \"line one\n line two indented\"\n};\n"; + let output = format_source(input, &Config::default()).expect("must format"); + assert!( + output.contains("\"line one\n line two indented\""), + "the string's bytes changed:\n{output}" + ); + verify_equivalence(input, &output).expect("nothing but indentation moved"); +} + +/// QA repro (2026-08-26): a `` `endif `` with no region open is broken input, +/// not a split. Recovering it would have `format_source` accept and rewrite +/// invalid Verilog that a real toolchain rejects at preprocessing. +#[test] +fn a_stray_endif_next_to_an_open_bracket_is_refused_not_reformatted() { + for input in [ + "int x[] = {\n`endif\n1\n};\n", + "module m;\n int x[] = {\n`endif\n 1\n};\nendmodule\n", + "module m;\n`ifdef FOO\n wire a;\n`endif\n`endif\n int x[] = {\n`else\n const int x[] = {\n`endif\n 1\n};\nendmodule\n", + ] { + match format_source(input, &Config::default()) { + Err(FormatError::Source(e)) => { + assert!(e.to_string().contains('`'), "the directive is named: {e}"); + } + Ok(out) => panic!("invalid input was accepted and rewritten as:\n{out}"), + Err(e) => panic!("expected a parse refusal, got {e}"), + } + } +} + +/// QA repro (2026-08-26, round 4): an unbalanced `` `ifdef `` written inside a +/// construct lucisv keeps as opaque bytes must not leak into the file's +/// item-scope conditional nesting, where it would launder an unrelated stray +/// `` `endif `` into a split and get invalid input reformatted with exit 0. +#[test] +fn an_opaque_body_cannot_launder_a_stray_endif_into_a_split() { + for input in [ + // constraint, covergroup, property: all three walk their bodies token + // by token to find their closer. + "class c;\n constraint co {\n`ifdef FAKE\n x < 10;\n }\nendclass\nint y[] = {\n`endif\n1\n};\n", + "covergroup cg;\n`ifdef FAKE\n cp: coverpoint x;\nendgroup\nint y[] = {\n`endif\n1\n};\n", + "module m;\n property p;\n`ifdef FAKE\n a |-> b;\n endproperty\n int y[] = {\n`endif\n1\n};\nendmodule\n", + // Control: the inner directive balanced. The tail is still stray. + "class c;\n constraint co {\n`ifdef FAKE\n x < 10;\n`endif\n }\nendclass\nint y[] = {\n`endif\n1\n};\n", + ] { + match format_source(input, &Config::default()) { + Err(FormatError::Source(_)) => {} + Ok(out) => panic!("invalid input was accepted and rewritten as:\n{out}"), + Err(e) => panic!("expected a parse refusal, got {e}"), + } + } +} diff --git a/crates/vlog_parser/src/parser.rs b/crates/vlog_parser/src/parser.rs index 3c156a3..cc2c474 100644 --- a/crates/vlog_parser/src/parser.rs +++ b/crates/vlog_parser/src/parser.rs @@ -215,6 +215,17 @@ pub struct Parser<'a> { depth: u32, /// Chain links open on the current path; see [`MAX_CHAIN_LENGTH`]. links: u32, + /// Conditional-compilation regions open **at item scope** at the cursor: + /// one per `` `ifdef `` / `` `ifndef `` that stood as an item and has not + /// been closed by an `` `endif `` standing as an item. + /// + /// Kept as running state because the split-conditional recovery must know + /// whether a closing directive closes anything at all — a stray + /// `` `endif `` is broken input, not a split. Maintained by exactly two + /// places, [`Parser::note_item_conditional`] and + /// [`Parser::split_conditional_item`]; see the former's doc for why it is + /// *not* maintained in [`Parser::bump`]. + open_conds: u32, /// Recover from errors instead of returning them; see [`parse_tolerant`]. tolerant: bool, /// The text the tokens were lexed from, in both modes: recovery copies a @@ -273,6 +284,44 @@ 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. +struct ItemMark { + /// Index of the item's first token, past its attributes. + pos: usize, + /// Conditional regions open at that token. + conds: u32, + /// Diagnostics recorded before the item ran; a replaced parse's notes are + /// dropped back to this length (tolerant mode only — strict has none). + diags: usize, +} + +/// The word a compiler-directive token spells, without its backtick and +/// without its argument: `` `ifndef FOO `` is `"ifndef"`. The empty string for +/// anything that is not a directive token. +fn directive_word(t: &Token) -> &str { + if t.kind != TokenKind::Directive { + return ""; + } + let rest = t.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("") +} + +/// `` `ifdef `` / `` `ifndef ``: opens a conditional-compilation region. +fn opens_conditional(t: &Token) -> bool { + matches!(directive_word(t), "ifdef" | "ifndef") +} + +/// `` `else `` / `` `elsif ``: starts the next arm of the region already open. +fn continues_conditional(t: &Token) -> bool { + matches!(directive_word(t), "else" | "elsif") +} + +/// `` `endif ``: closes the region already open. +fn closes_conditional(t: &Token) -> bool { + directive_word(t) == "endif" +} + /// 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) { @@ -291,6 +340,7 @@ impl<'a> Parser<'a> { pending_trailing: Vec::new(), depth: 0, links: 0, + open_conds: 0, tolerant, source, diagnostics: Vec::new(), @@ -1118,7 +1168,12 @@ impl<'a> Parser<'a> { let tok = &mut self.tokens[self.pos]; meta.leading.append(&mut tok.leading); } - let kind = self.parse_item_kind()?; + let mark = + ItemMark { pos: self.pos, conds: self.open_conds, diags: self.diagnostics.len() }; + let kind = match self.parse_item_kind() { + Ok(kind) => kind, + Err(e) => self.split_conditional_item(&mark, e)?, + }; let span = self.span_from(start); if meta.trailing.is_none() { meta.trailing = self.take_trailing(); @@ -1132,7 +1187,10 @@ impl<'a> Parser<'a> { } let t = self.cur(); match t.kind { - TokenKind::Directive => Ok(ItemKind::Directive(self.take_raw_text())), + TokenKind::Directive => { + self.note_item_conditional(); + Ok(ItemKind::Directive(self.take_raw_text())) + } TokenKind::Keyword => self.parse_keyword_item(), TokenKind::Ident if self.at_bind_directive() => self.parse_bind().map(ItemKind::Bind), // `NoNMI: assume property (...)` and `restrict property (...)`: @@ -1765,6 +1823,206 @@ impl<'a> Parser<'a> { Ok(self.verbatim_since(start, col)) } + // ------------------------------------------------------------------ + // Conditional-directive split recovery + // + // An `ifdef region whose arms are each an *incomplete fragment* of one + // construct — two spellings of a declaration head sharing one body, two + // struct bodies sharing one closing brace — is not a tree. There is no + // AST for it and no layout to apply, so it joins `constraint`, + // `covergroup` and the concurrent assertions in the verbatim bucket: the + // exact source bytes, re-indented on the first line only. + // + // The recovery is deliberately hard to reach. It fires only after a real + // parse failure, and only when that failure is the grammar refusing a + // `else / `elsif / `endif that closes a region which is genuinely open + // and which the failed item did not open, with a bracket the arm left + // open. Everything else — a plain syntax error that merely sits near a + // directive, a garbage token run with directives in it, an unterminated + // region, a stray closer with nothing open — still refuses. + // See `docs/features/directive-split/README.md`. + // ------------------------------------------------------------------ + + /// Count the conditional-compilation directive standing at the cursor, + /// which the caller is about to consume as an `ItemKind::Directive`. + /// + /// This is the **only** place [`Parser::open_conds`] grows, and the whole + /// reason it is here rather than in [`Parser::bump`] is that `bump` cannot + /// tell item scope from anything else. The constructs lucisv keeps as + /// opaque bytes — `constraint`, `covergroup`, `property` / `sequence`, + /// concurrent assertions, and the split regions this module produces — + /// walk their bodies token by token *through* `bump` to find their closer, + /// so counting there let a `` `ifdef `` written inside a constraint body + /// leak into the file's item-scope nesting (QA round 4). Counting here + /// instead makes "not item scope, does not count" the **default**: a new + /// verbatim construct inherits the right behaviour by doing nothing, and + /// there is no flag anyone can forget to set. + /// + /// Saturating on the way down, so a stray closer near the top of a file + /// cannot make a later, genuine region look unopened. + fn note_item_conditional(&mut self) { + let t = self.cur(); + if opens_conditional(t) { + self.open_conds += 1; + } else if closes_conditional(t) { + self.open_conds = self.open_conds.saturating_sub(1); + } + } + + /// Turn an item that is really one arm of a split conditional region into + /// a verbatim block, or hand `err` back untouched. + fn split_conditional_item(&mut self, mark: &ItemMark, err: ParseError) -> PResult { + if !self.at_split_conditional(mark) { + return Err(err); + } + let Some((end_pos, conds_after)) = self.scan_split_extent(mark) else { + return Err(err); + }; + self.diagnostics.truncate(mark.diags); + let start = self.tokens[mark.pos].span.start; + let col = self.tokens[mark.pos].col; + // Walk the span from the top rather than jumping the cursor: `bump` + // is what moves a token's trailing comment into the pending bucket, + // and the comment written after the construct's last token must end + // up there for the next node to harvest. The copies that fall *inside* + // the span — including the duplicates of the ones the failed parse + // already moved — are dropped by `verbatim_since`. + self.pos = mark.pos; + 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))) + } + + /// True when the item that began at `mark` failed *because* it is one arm + /// of a conditional region it did not open. + /// + /// Four things must hold at once: + /// + /// 1. the cursor — where the failure was raised — stands on a + /// `` `else `` / `` `elsif `` / `` `endif ``; + /// 2. a conditional region was already open when the item started, so + /// that directive has something to close. A stray closer opens nothing + /// and ends nothing: it is broken input, and the parse error stands; + /// 3. the item's own conditional nesting is back to zero there, so the + /// live region is one opened *before* the item rather than by it; + /// 4. the arm left a bracket open, i.e. it is structurally a fragment. + /// A missing `;` leaves nothing open and is indistinguishable from a + /// typo, so it is refused. + fn at_split_conditional(&self, mark: &ItemMark) -> bool { + let at = self.cur(); + if !continues_conditional(at) && !closes_conditional(at) { + return false; + } + if mark.conds == 0 { + return false; + } + let mut cond = 0i32; + let mut brackets = 0i32; + for t in self.tokens.get(mark.pos..self.pos).unwrap_or_default() { + if t.kind == TokenKind::Directive { + if opens_conditional(t) { + cond += 1; + } else if closes_conditional(t) { + cond -= 1; + } + } else 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; + } + } + cond == 0 && brackets > 0 + } + + /// One past the last token of the construct the split region belongs to, + /// paired with the item-scope conditional nesting left open after it — or + /// `None` when the file holds no such end. + /// + /// The scan follows the *first* arm and skips the alternatives whole: the + /// arms are rival spellings of the same thing, so counting all of their + /// brackets would demand as many closers as there are arms. It ends where + /// all three of (a) the regions the scan itself opened are closed, (b) the + /// region that was already open has been closed — conditional nesting is + /// back to the level it stood at where that region began — and (c) the + /// brackets the chosen scan opened are closed: at the first `;` that sees + /// all three. + /// + /// A `` `else `` / `` `elsif `` / `` `endif `` met at scan level zero with + /// no region live is a stray closer, not a split, and gives up — the same + /// refusal the trigger makes, repeated here because the scan walks past + /// the point the trigger looked at. + fn scan_split_extent(&self, mark: &ItemMark) -> Option<(usize, u32)> { + // Regions this scan opened, and regions that were already open when + // it started. A directive at scan level zero belongs to the latter. + let mut cond = 0i32; + let mut live = mark.conds; + let mut closed_outer = false; + let mut brackets = 0i32; + 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) { + if cond > 0 { + cond -= 1; + } else { + live = live.checked_sub(1)?; + closed_outer = true; + } + } else if continues_conditional(t) && cond == 0 { + live = live.checked_sub(1)?; + closed_outer = true; + i = self.skip_conditional_arms(i + 1)?; + continue; + } + } else 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 t.is_sym(";") && brackets == 0 && cond == 0 && closed_outer { + return Some((i + 1, live)); + } + i += 1; + } + None + } + + /// Skip from `from` — just past a `` `else `` / `` `elsif `` — through the + /// `` `endif `` that closes the region that directive belongs to, nested + /// regions included. `None` if the file ends first. + fn skip_conditional_arms(&self, from: usize) -> Option { + let mut nested = 0i32; + let mut i = from; + while let Some(t) = self.tokens.get(i) { + if t.kind == TokenKind::Eof { + return None; + } + if opens_conditional(t) { + nested += 1; + } else if closes_conditional(t) { + if nested == 0 { + return Some(i + 1); + } + nested -= 1; + } + i += 1; + } + None + } + /// True when the cursor opens a parameterized type's `#( ... )`. fn at_type_params(&self) -> bool { self.cur().is_sym("#") && self.nth(1).is_sym("(") @@ -6833,4 +7091,331 @@ mod tests { // The else-branch itself did not also take the comment. assert!(els.as_ref().expect("an else").meta.leading.is_empty()); } + + // ------------------------------------------------------------------ + // Split conditional regions (`docs/features/directive-split/README.md`) + // ------------------------------------------------------------------ + + /// The verbatim item a split conditional region collapsed into, with the + /// items that came before and after it, so every test can also assert + /// that nothing around the region was swallowed. + fn split_items(file: &SourceFile) -> Vec { + file.items + .iter() + .map(|i| match &i.kind { + ItemKind::Verbatim(raw) => format!("verbatim:{}", raw.text), + ItemKind::Directive(raw) => format!("directive:{}", raw.text), + ItemKind::DataDecl(_) => "decl".to_string(), + ItemKind::ParamDecl(_) => "param".to_string(), + ItemKind::Typedef(_) => "typedef".to_string(), + _ => "other".to_string(), + }) + .collect() + } + + #[test] + fn alternative_declaration_heads_sharing_one_body_are_captured_verbatim() { + // corpus/ibex/vendor/google_riscv-dv/target/rv32imc/riscv_core_setting.sv:98 + let src = "`ifdef DSIM\nprivileged_reg_t csr[] = {\n`else\nconst privileged_reg_t csr[] \ + = {\n`endif\n MVENDORID\n};\n\nparameter int AFTER = 1;\n"; + let f = parse_ok(src); + let kinds = split_items(&f); + assert_eq!(kinds.len(), 3, "{kinds:?}"); + assert_eq!(kinds[0], "directive:`ifdef DSIM"); + assert_eq!(kinds[2], "param", "the item after the region was not swallowed"); + let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") }; + assert_eq!(raw.text, src[raw.span.as_range()]); + assert!(raw.text.starts_with("privileged_reg_t"), "{:?}", raw.text); + assert!(raw.text.ends_with("};"), "{:?}", raw.text); + assert!(raw.text.contains("`else") && raw.text.contains("`endif"), "{:?}", raw.text); + } + + #[test] + fn alternative_struct_bodies_sharing_one_closing_are_captured_verbatim() { + // corpus/ibex/vendor/google_riscv-dv/src/riscv_instr_pkg.sv:1236 + let src = "package p;\n`ifdef _VCP\n typedef struct packed {\n bit l;\n`else\n \ + typedef struct{\n rand bit l;\n`endif\n } pmp_cfg_reg_t;\n\n parameter \ + int AFTER = 1;\nendpackage\n"; + let f = parse_ok(src); + let ItemKind::Package { items, .. } = &f.items[0].kind else { panic!("expected package") }; + assert_eq!(items.len(), 3, "{:?}", items.len()); + let ItemKind::Verbatim(raw) = &items[1].kind else { panic!("expected a verbatim block") }; + assert_eq!(raw.text, src[raw.span.as_range()]); + assert!(raw.text.starts_with("typedef struct packed {"), "{:?}", raw.text); + assert!(raw.text.ends_with("} pmp_cfg_reg_t;"), "{:?}", raw.text); + assert!(matches!(items[2].kind, ItemKind::ParamDecl(_)), "the next item survived"); + } + + #[test] + fn an_ifndef_and_an_elsif_chain_are_the_same_shape() { + let src = "`ifndef A\nint x[] = {\n`elsif B\nconst int x[] = {\n`else\nstatic int x[] = \ + {\n`endif\n 1\n};\n"; + let f = parse_ok(src); + let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") }; + // Every arm is inside the one block, and only the first arm's `{` was + // counted -- otherwise the scan would still be looking for two more. + assert!(raw.text.contains("`elsif B") && raw.text.contains("`else"), "{:?}", raw.text); + assert!(raw.text.ends_with("};"), "{:?}", raw.text); + } + + #[test] + fn a_balanced_region_inside_the_shared_tail_does_not_end_the_scan() { + let src = "`ifdef A\nint x[] = {\n`else\nconst int x[] = {\n`endif\n 1,\n`ifdef B\n \ + 2,\n`endif\n 3\n};\n\nparameter int AFTER = 1;\n"; + let f = parse_ok(src); + let kinds = split_items(&f); + assert_eq!(kinds.len(), 3, "{kinds:?}"); + let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") }; + assert!(raw.text.contains("`ifdef B"), "the nested region is inside: {:?}", raw.text); + assert_eq!(kinds[2], "param", "the item after the region was not swallowed"); + } + + #[test] + fn comments_inside_a_split_region_are_kept_and_the_one_after_it_is_not() { + let src = "// head\n`ifdef A // which\nint x[] = { // open\n`else // other\nconst int \ + x[] = {\n`endif\n // why\n 1\n}; // done\nint y;\n"; + let f = parse_ok(src); + assert_eq!(texts(&f.items[0].meta.leading), ["// head"]); + assert_eq!( + f.items[0].meta.trailing.as_ref().expect("`ifdef's own comment").text, + "// which" + ); + let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") }; + for c in ["// open", "// other", "// why"] { + assert!(raw.text.contains(c), "{c} was dropped from {:?}", raw.text); + } + assert!(!raw.text.contains("// done"), "the trailing comment was swallowed"); + assert_eq!( + f.items[1].meta.trailing.as_ref().expect("the comment survived").text, + "// done" + ); + } + + // -- the trigger refuses everything that is not a split --------------- + + #[test] + fn a_plain_syntax_error_inside_a_complete_arm_is_still_an_error() { + // Both arms are whole declarations; the `= ;` is an ordinary typo + // that merely happens to sit inside a conditional region. + let msg = parse_err("`ifdef A\nwire x = ;\n`else\nwire x = 1;\n`endif\n"); + assert!(msg.contains("expected expression"), "{msg}"); + // ... and the same typo with a bracket open before it, so the only + // thing missing is the `else`/`endif` at the cursor. + let msg = parse_err("`ifdef A\nint x[] = {1, };\nwire y = ;\n`else\n`endif\n"); + assert!(msg.contains("expected expression"), "{msg}"); + } + + #[test] + fn a_garbage_token_run_between_directives_is_still_an_error() { + let msg = parse_err("`ifdef A\n) ] }\n`else\n(\n`endif\n;\n"); + assert!(msg.contains("expected item"), "{msg}"); + let msg = parse_err("module m;\n`ifdef A\n = = =\n`else\n ;\n`endif\nendmodule\n"); + assert!(!msg.is_empty(), "{msg}"); + } + + #[test] + fn an_unterminated_region_with_broken_code_is_still_an_error() { + // No `endif at all: the scan finds no end for the region and the + // original error stands. + let msg = parse_err("`ifdef A\nint x[] = {\n`else\nconst int x[] = {\n 1\n};\n"); + assert!(msg.contains("`else"), "{msg}"); + // An `endif but no terminating `;` before the end of the file. + let msg = parse_err("`ifdef A\nint x[] = {\n`else\nconst int x[] = {\n`endif\n 1\n"); + assert!(msg.contains("`else"), "{msg}"); + } + + #[test] + fn a_missing_semicolon_is_not_a_split() { + // The arm left no bracket open, so it is a fragment of nothing: the + // shape is indistinguishable from a forgotten `;` and is refused. + let msg = parse_err("`ifdef A\nwire x\n`else\nwire y\n`endif\n;\n"); + assert!(msg.contains("`else"), "{msg}"); + } + + #[test] + fn a_stray_endif_is_never_a_split() { + // QA repro (2026-08-26): nothing opened a region, so the `endif + // closes nothing and the arm before it is a fragment of nothing. + // Recovering here would reformat invalid Verilog and exit 0. + let msg = parse_err("int x[] = {\n`endif\n1\n};\n"); + assert!(msg.contains("expected expression") && msg.contains("`endif"), "{msg}"); + let msg = parse_err("module m;\n int x[] = {\n`endif\n 1\n};\nendmodule\n"); + assert!(msg.contains("`endif"), "{msg}"); + } + + #[test] + fn a_closed_region_does_not_leave_a_later_endif_something_to_close() { + // QA repro (2026-08-26): a legitimately closed region, then an + // accidental duplicate closer, then a bracket-opening declaration. + // The duplicate re-opens nothing, so the `else below is still stray. + let msg = parse_err( + "module m;\n`ifdef FOO\n wire a;\n`endif\n`endif\n int x[] = {\n`else\n const int \ + x[] = {\n`endif\n 1\n};\nendmodule\n", + ); + assert!(msg.contains("`else"), "{msg}"); + } + + #[test] + fn a_stray_endif_with_no_item_to_break_is_left_exactly_as_it_was() { + // lucisv has never validated directive nesting -- a lone `endif at + // item position is an ordinary `ItemKind::Directive`, before this + // work and after it. What matters is that no bracket-opening item + // near it gets swallowed into a verbatim block. + let f = parse_ok("wire a;\n`endif\nwire b;\n`endif\nint x[] = {1};\n"); + let kinds = split_items(&f); + assert_eq!( + kinds, + ["decl", "directive:`endif", "decl", "directive:`endif", "decl"], + "nothing was collapsed into a verbatim block" + ); + } + + #[test] + fn a_split_nested_inside_an_open_region_is_still_recovered() { + // The guard is "a region is live", not "exactly one region is live": + // both corpus shapes still recover when they sit inside an outer + // `ifdef that stays open across them. + let a = parse_ok( + "`ifdef OUTER\n`ifdef DSIM\nprivileged_reg_t csr[] = {\n`else\nconst \ + privileged_reg_t csr[] = {\n`endif\n MVENDORID\n};\n`endif\nparameter int AFTER = \ + 1;\n", + ); + let ItemKind::Verbatim(raw) = &a.items[2].kind else { panic!("expected a verbatim block") }; + assert!(raw.text.ends_with("};"), "{:?}", raw.text); + // The outer region's own `endif is still its own directive item, and + // the item past it was not swallowed. + let kinds = split_items(&a); + assert_eq!(kinds[3], "directive:`endif", "{kinds:?}"); + assert_eq!(kinds[4], "param", "{kinds:?}"); + + let b = parse_ok( + "package p;\n`ifdef OUTER\n`ifdef _VCP\n typedef struct packed {\n bit l;\n\ + `else\n typedef struct{\n rand bit l;\n`endif\n } pmp_cfg_reg_t;\n`endif\n \ + parameter int AFTER = 1;\nendpackage\n", + ); + let ItemKind::Package { items, .. } = &b.items[0].kind else { panic!("expected package") }; + let ItemKind::Verbatim(raw) = &items[2].kind else { panic!("expected a verbatim block") }; + assert!(raw.text.ends_with("} pmp_cfg_reg_t;"), "{:?}", raw.text); + assert!(matches!(items[4].kind, ItemKind::ParamDecl(_)), "the next item survived"); + } + + /// `Parser::open_conds` once the whole file has parsed. The invariant it + /// pins: this is the number of `` `ifdef ``/`` `ifndef `` regions opened + /// **at item scope** and not closed at item scope — nothing consumed + /// inside an opaque verbatim body may move it. + fn open_conds_after(src: &str) -> u32 { + let toks = tokenize(src).expect("lex error"); + let mut p = Parser::new(toks, src, false); + p.parse_source_file().expect("parse error"); + p.open_conds + } + + #[test] + fn item_scope_conditional_nesting_ignores_opaque_bodies() { + // QA repro (2026-08-26, round 4): an unbalanced `ifdef written inside + // a construct lucisv keeps as opaque bytes used to leak into the + // file's item-scope nesting, because those bodies are walked token by + // token through `bump`. Every one of them must leave the count alone. + assert_eq!(open_conds_after("wire x;\n"), 0); + assert_eq!(open_conds_after("`ifdef A\nwire x;\n"), 1, "an item-scope region does count"); + assert_eq!(open_conds_after("`ifdef A\nwire x;\n`endif\n"), 0); + for body in [ + "class c;\n constraint co {\n`ifdef FAKE\n x < 10;\n }\nendclass\n", + "covergroup cg;\n`ifdef FAKE\n cp: coverpoint x;\nendgroup\n", + "module m;\n property p;\n`ifdef FAKE\n a |-> b;\n endproperty\nendmodule\n", + "module m;\n assert property (\n`ifdef FAKE\n a |-> b);\nendmodule\n", + ] { + assert_eq!(open_conds_after(body), 0, "an opaque body leaked: {body:?}"); + } + } + + #[test] + fn an_unbalanced_ifdef_inside_an_opaque_body_cannot_launder_a_later_stray_endif() { + // The end-to-end shape of the leak above: the polluted count used to + // make an unrelated stray `endif look like a live region's closer. + let msg = parse_err( + "class c;\n constraint co {\n`ifdef FAKE\n x < 10;\n }\nendclass\nint y[] = \ + {\n`endif\n1\n};\n", + ); + assert!(msg.contains("`endif"), "{msg}"); + let msg = parse_err( + "covergroup cg;\n`ifdef FAKE\n cp: coverpoint x;\nendgroup\nint y[] = \ + {\n`endif\n1\n};\n", + ); + assert!(msg.contains("`endif"), "{msg}"); + let msg = parse_err( + "module m;\n property p;\n`ifdef FAKE\n a |-> b;\n endproperty\n int y[] = \ + {\n`endif\n1\n};\nendmodule\n", + ); + assert!(msg.contains("`endif"), "{msg}"); + // Control: the same shape with the inner directive balanced. The tail + // is still a stray `endif with no live region, so it still refuses -- + // the count was never the thing making the tail legal. + let msg = parse_err( + "class c;\n constraint co {\n`ifdef FAKE\n x < 10;\n`endif\n }\nendclass\nint \ + y[] = {\n`endif\n1\n};\n", + ); + assert!(msg.contains("`endif"), "{msg}"); + } + + #[test] + fn suppressing_opaque_bodies_does_not_suppress_the_regions_around_them() { + // Over-suppression guard: balanced directives inside an opaque body, + // then a genuine split later in the same file. + let f = parse_ok( + "class c;\n constraint co {\n`ifdef X\n x < 10;\n`endif\n }\nendclass\n`ifdef \ + DSIM\nint y[] = {\n`else\nconst int y[] = {\n`endif\n 1\n};\nparameter int AFTER = \ + 1;\n", + ); + assert!(matches!(f.items[2].kind, ItemKind::Verbatim(_)), "{:?}", split_items(&f)); + + // Under-suppression guard: an earlier verbatim item (a constraint) + // inside the very region the split sits in. + let f = parse_ok( + "`ifdef OUTER\nclass c;\n constraint co {x < 10;}\nendclass\n`ifdef DSIM\nint y[] = \ + {\n`else\nconst int y[] = {\n`endif\n 1\n};\n`endif\nparameter int AFTER = 1;\n", + ); + let kinds = split_items(&f); + assert_eq!(kinds[3], "verbatim:int y[] = {\n`else\nconst int y[] = {\n`endif\n 1\n};"); + assert_eq!(kinds[4], "directive:`endif"); + assert_eq!(kinds[5], "param"); + assert_eq!(open_conds_after( + "`ifdef OUTER\nclass c;\n constraint co {x < 10;}\nendclass\n`ifdef DSIM\nint y[] = \ + {\n`else\nconst int y[] = {\n`endif\n 1\n};\n`endif\nparameter int AFTER = 1;\n" + ), 0, "the recovered block accounted for the `endif it swallowed"); + } + + #[test] + fn a_recovered_block_leaves_the_right_nesting_behind_it() { + // The block swallows the region's own `endif, so the count has to come + // down with it -- otherwise the next `endif looks like it closes + // something and the stray after it gets laundered. + let src = "`ifdef OUTER\n`ifdef A\nint x[] = {\n`else\nconst int x[] = {\n`endif\n \ + 1\n};\n`endif\nparameter int AFTER = 1;\n"; + assert_eq!(open_conds_after(src), 0); + let msg = parse_err( + "`ifdef OUTER\n`ifdef A\nint x[] = {\n`else\nconst int x[] = {\n`endif\n \ + 1\n};\n`endif\nint z[] = {\n`endif\n 1\n};\n", + ); + assert!(msg.contains("`endif"), "{msg}"); + // Two splits under one outer region both recover, and the outer region + // is still open between them. + let f = parse_ok( + "`ifdef OUTER\n`ifdef A\nint x[] = {\n`else\nconst int x[] = {\n`endif\n \ + 1\n};\n`ifdef B\nint y[] = {\n`else\nconst int y[] = {\n`endif\n \ + 2\n};\n`endif\nparameter int AFTER = 1;\n", + ); + let kinds = split_items(&f); + assert_eq!(kinds.iter().filter(|k| k.starts_with("verbatim:")).count(), 2, "{kinds:?}"); + assert_eq!(kinds[kinds.len() - 1], "param", "{kinds:?}"); + } + + #[test] + fn a_region_whose_arms_are_whole_items_still_parses_arm_by_arm() { + let f = parse_ok("`ifdef A\nwire x;\n`else\nwire y;\n`endif\n"); + assert_eq!( + split_items(&f), + ["directive:`ifdef A", "decl", "directive:`else", "decl", "directive:`endif"] + ); + } } diff --git a/docs/features/directive-split/README.md b/docs/features/directive-split/README.md new file mode 100644 index 0000000..fbedeb2 --- /dev/null +++ b/docs/features/directive-split/README.md @@ -0,0 +1,1262 @@ +# directive-split + +## Goal + +Stop refusing files where the arms of a `` `ifdef ``/`` `else ``/`` `endif `` +region are each an **incomplete fragment of one construct** — two rival +spellings of a declaration head sharing one body, two struct bodies sharing +one closing brace. Such a region is not a tree: there is no AST that holds +"either this head or that one", and there is no layout to apply to something +that only becomes a construct after the preprocessor has chosen an arm. So it +joins `constraint`, `covergroup` and the concurrent assertions in the +**verbatim** bucket — the exact source bytes, re-indented on the first line +only — reached by a *recovery* in the strict parser rather than by a grammar +rule. This is the `directive-split` bucket of `scripts/score.sh`: 13 of its 14 +files, the largest remaining blocker before this round. + +The two shapes, both taken from the corpus: + +| shape | corpus evidence | +|---|---| +| A — alternative declaration heads sharing one body | `corpus/ibex/vendor/google_riscv-dv/target/rv32imc/riscv_core_setting.sv:98` (and 11 more copies of that file under `target/*/`) | +| B — alternative struct bodies sharing one closing | `corpus/ibex/vendor/google_riscv-dv/src/riscv_instr_pkg.sv:1236` | + +```verilog +// A +`ifdef DSIM +privileged_reg_t implemented_csr[] = { +`else +const privileged_reg_t implemented_csr[] = { +`endif + MVENDORID, // Vendor ID + ... +}; + +// B +`ifdef _VCP + typedef struct packed { + bit l; +`else + typedef struct{ + rand bit l; +`endif + } pmp_cfg_reg_t; +``` + +Explicitly **not** in scope: +`corpus/ibex/vendor/google_riscv-dv/src/riscv_instr_cover_group.sv`, the 14th +file of the bucket. Its failure is macro-bracketed covergroups +(`` `R_INSTR_CG_BEGIN `` / `` `CG_END `` needing expansion), not a split +region, and it still fails after this work — which is the check that the +trigger is not too loose. + +## Assumptions + +- **The recovery starts at the item, not at the `` `ifdef ``.** The opening + `` `ifdef `` has already been parsed as its own `ItemKind::Directive` by the + time the *next* item fails, and a `Directive` item prints as its own raw + text. So the verbatim block runs from the first token of the failed item + through the construct's terminating `;`, and the `` `ifdef `` line is + printed by the directive path exactly as it always was. Nothing has to be + retracted from an item list, and the emitted bytes are the same either way. + The `` `else `` / `` `elsif `` / `` `endif `` of the region *are* inside the + block, because they fall between the failed item's first token and the `;`. + +- **The trigger is four conditions at once**, checked in + `Parser::at_split_conditional`: + + 1. the cursor — where the failure was raised — stands on a `` `else ``, + `` `elsif `` or `` `endif ``; + 2. a conditional region **was already open** when the item started, so that + directive has something to close (`ItemMark::conds`, below); + 3. the failed item's *own* conditional nesting is back to zero there, so the + live region is one opened *before* the item rather than by it; + 4. the item left a **bracket open** (`(`, `[` or `{` unmatched) at that + point, i.e. the arm is structurally a fragment. + + Condition 2 was added for QA round 3 (see the 2026-08-26 work log entry): a + stray `` `endif `` closes nothing, so an arm in front of it is a fragment of + nothing, and recovering there would reformat input a real toolchain rejects + at preprocessing. + + Condition 4 is what keeps an ordinary syntax error near a directive an + ordinary syntax error. A *missing `;`* leaves nothing open: + + ```verilog + `ifdef A + wire x // forgotten semicolon, or the head of a split? Unknowable. + `else + wire y + `endif + ; + ``` + + is refused, deliberately, and the parse error stands. The same reasoning + refuses a bracketless split such as `` `ifdef A assign x = `else assign x = + y + `endif z; `` — it is not in the corpus, and accepting it would mean + accepting every forgotten terminator inside a conditional region. + +- **The extent follows the FIRST arm and skips the alternatives whole.** The + arms are rival spellings of the same thing, so counting all of their + brackets would demand as many closers as there are arms. `scan_split_extent` + therefore, on a `` `else `` / `` `elsif `` at the region's own level, jumps + to just past the `` `endif `` that closes that region (nested regions + counted) without counting anything in between. The block ends at the first + `;` where **both** (a) conditional nesting is back to the level the scan + started at and (b) the brackets the chosen scan opened are closed. A + *balanced* region met later in the shared tail is ordinary conditional text: + it raises and lowers the nesting counter and ends nothing. + +- **The extent scan carries the same "is a region live" guard.** It walks past + the point the trigger looked at, so it repeats the check rather than trusting + it: it tracks the regions *it* opened separately from the regions that were + already open (`live`, seeded from `ItemMark::conds`), and a `` `else `` / + `` `elsif `` / `` `endif `` met at scan level zero with `live == 0` gives up. + It also requires that the already-open region actually got closed + (`closed_outer`) before it will accept a `;` as the terminator, so a `;` met + before any split point cannot end the block. + +- **`Parser::open_conds` counts *item-scope* regions only, and is maintained + at the item-scope directive itself — never in `bump`.** `bump` cannot tell + item scope from anything else, and the constructs lucisv keeps as opaque + bytes (`constraint`, `covergroup`, `property`/`sequence`, concurrent + assertions, and the split blocks this feature produces) walk their bodies + token by token *through* `bump` to find their closer. Counting there let a + `` `ifdef `` written inside a constraint body leak into the file's nesting + (QA round 4). So the count lives in `Parser::note_item_conditional`, called + from the one arm of `parse_item_kind` that consumes a directive **as an + item**, and the default for everything else is "does not count". It is + **saturating** on the way down, so a stray closer near the top of a file + cannot make a later, genuine region look unopened. + + The stated invariant, pinned directly by `open_conds_after` in the parser + tests: **after parsing any item, `open_conds` is the number of + `` `ifdef ``/`` `ifndef `` regions opened at item scope and not yet closed + at item scope.** + + The **rule for future verbatim constructs**, and the reason this shape was + chosen over a suppression flag or an RAII guard: a new opaque construct + inherits the correct behaviour by doing *nothing*. There is no flag to set + and therefore none to forget. The only thing a future author must not do is + count conditional directives from inside a body walk. + +- **A recovered split block accounts for the directives it swallowed.** The + region's own `` `else ``/`` `endif `` *are* item-scope nesting even though + they end up inside opaque bytes, so `scan_split_extent` returns the nesting + left open after the block alongside the block's end, and + `split_conditional_item` assigns it. This is the second and last place + `open_conds` moves. Without it a recovered split inside an outer region left + the count one too high and the *next* stray `` `endif `` was laundered — + the same failure mode one level up. Pinned by + `a_recovered_block_leaves_the_right_nesting_behind_it`. + +- **lucisv still does not validate directive nesting, and this work did not + start.** A lone `` `endif `` at item position is an ordinary + `ItemKind::Directive`, accepted before this work and after it — the baseline + binary at `HEAD` accepts `wire a;` / `` `endif `` / `wire b;` exactly as the + patched one does. What the guard above buys is narrower and is the whole + point: no bracket-opening item near a stray closer is ever *swallowed* into a + verbatim block. Validating `` `ifdef ``/`` `endif `` balance across a file is + a separate feature (and a wrong one for a formatter that must accept a header + whose region is opened in an includer). + +- **No end means no recovery.** If the scan reaches end of file without that + `;`, or sees a closing bracket with nothing open, the original parse error is + returned unchanged. An unterminated region is still an error, as it was. + +- **The construct's terminator is a `;`.** Every split in the corpus is a + declaration, and declarations end in `;`. A split whose shared tail ends in + `endmodule` / `endcase` / `end` is not handled and still errors out; nothing + in the corpus asks for it and guessing at a second terminator would widen the + scan for no evidence. + +- **A verbatim block's *relative* layout is what survives, not its absolute + indent** — the same statement the assertions and classes rounds make. Only + the first line is re-indented to the item's level; the continuation lines are + dedented by the block's original start column and the printer indents them + back (`Fmt::raw_lines`), which is what makes the second pass a fixed point. + Visible consequence, pinned by a case: shape B's `` `ifdef `` (written at + column 1 inside a package) comes out at the package's item indent, and so do + its `` `else `` / `` `endif ``, because the block's own dedent is measured + from the `typedef` at column 3. + +- **The recovery runs in tolerant mode too.** It sits in `parse_item_inner`, + which both modes share, so an editor buffer gets the verbatim block instead + of an `ItemKind::Error` leaf. The tolerant path's diagnostics from the parse + being replaced are truncated, so a recovered region reports nothing. No + existing tolerant test changed. + +- **A currently-passing file cannot be affected.** The recovery is only ever + reached from the `Err` arm of `parse_item_kind`, and a file that formats + today produces no such `Err`. Confirmed empirically: the pass set after is a + strict superset of the pass set before, with no file moving out. + +## Handshakes + +### Consumed + +- `Parser::verbatim_since(start, col)` — slices `source[span]` into a + `RawText` and drops the comment copies that fall *inside* the span, so a + comment written inside the region prints once and the comment written after + the terminating `;` stays pending for the next node. Used unchanged. +- `Fmt::raw_text(raw)` / `Fmt::raw_lines(text, col)` — the verbatim printer, + including its `crosses_line_inside_string` escape hatch, which is what keeps + a multi-line string inside a split region byte-identical. Used unchanged. + + **Known pre-existing issue, logged not fixed** (QA round 3, 2026-08-26): + `Fmt::raw_text` (`crates/vlog_formatter/src/format.rs:225`) on the + `crosses_line_inside_string == true` path emits a `Doc::Text` whose content + holds embedded newlines, which that variant's own doc contract says it never + does; the printer's column tracker therefore goes stale after one. The only + observed effect is conservative line breaking further down the same + construct — no corruption, no idempotency break, and the safety net still + refuses any change to those bytes. It predates this feature (it arrived with + the assertions round) and is untouched here; this cluster is simply the + first to reach it from *corpus-shaped* input, because a split region is the + first verbatim block that routinely carries a multi-line string. Fixing it + means teaching `Doc` about a multi-line literal, which is a printer change + and belongs to whoever owns `print.rs`, not to a parser recovery. +- `ItemKind::Verbatim(RawText)` — gained a **fifth producer** (after + `constraint`, `covergroup`, concurrent assertions, `property`/`sequence` + declarations). No signature changed; every consumer already treats it as an + opaque leaf, so no exhaustive match anywhere needed a new arm — `bind.rs`, + `visit.rs`, `spans.rs` and `format.rs` are untouched. + +### Promised / changed for others + +- **`crates/vlog_formatter/src/verify.rs` is untouched.** No normalization was + added and no forgiveness was widened: verbatim bytes need none, and all 13 + new corpus files pass through the runtime safety net as `scripts/score.sh` + runs it (`lucisv --check`, which verifies). The eight invariant-#4 attack + tests below were written anyway, because a verbatim capture is + forgiveness-*adjacent* — the block is re-lexed as ordinary tokens on both + sides, so every token inside it must still match. +- **`Parser` gained one field, `open_conds: u32`.** `Parser::bump` is + **unchanged** and deliberately knows nothing about it — see the Assumptions + entry above for why, and for the rule a future verbatim construct inherits. + It is written in exactly two places: `note_item_conditional` (the + item-position directive arm of `parse_item_kind`) and + `split_conditional_item` (which assigns what the extent scan computed). + Nothing outside this feature reads it. +- **New private parser surface only**: one struct (`ItemMark`), three free + predicates + (`directive_word`, `opens_conditional`, `continues_conditional`, + `closes_conditional`) and five `Parser` methods (`note_item_conditional`, + `split_conditional_item`, `at_split_conditional`, `scan_split_extent`, + `skip_conditional_arms`). Nothing is `pub`. +- **`parse_item_inner` now matches on `parse_item_kind`'s result** instead of + using `?`. The recovery is placed *inside* `parse_item_inner`, after the + meta/attribute harvest, precisely so the failed item's leading comments — + already moved into `meta` — are still owned by the frame that builds the + replacement item, and are printed in front of it. + +### Requests to other clusters + +- **macro-items / covergroup cluster**: `riscv_instr_cover_group.sv` remains + the one file in the `directive-split` bucket. Its blocker is + `` `R_INSTR_CG_BEGIN(...) ``-bracketed covergroup bodies, which need macro + expansion, not conditional recovery. It is classified here only because + `scripts/score.sh`'s classifier routes a `coverpoint` context line to this + bucket; the categorisation, not the file, is what is misleading. +- **linter**: AST-driven rules do not descend into a split region, exactly as + they do not descend into a `constraint` or a `covergroup`. The text-driven + rules (`no-tabs`, `no-trailing-whitespace`) still fire over those lines. + This is the pre-existing posture and is left as is. + +## Status / TODO + +- [x] Baseline `scripts/score.sh` recorded (`/tmp/score-before.tsv`) before + any edit. +- [x] Parser: `directive_word` / `opens_conditional` / `continues_conditional` + / `closes_conditional` predicates. +- [x] Parser: `split_conditional_item` (the recovery), `at_split_conditional` + (the trigger), `scan_split_extent` + `skip_conditional_arms` (the + extent). +- [x] Parser: one dispatch change, in `parse_item_inner`. +- [x] **QA round 3 (BLOCK):** `Parser::open_conds` running state, maintained + in `bump`; the "a region is live" guard in both `at_split_conditional` + and `scan_split_extent`; `ItemMark` carrying the count across the + recovery's rewind. +- [x] **QA round 4 (BLOCK):** `open_conds` moved out of `bump` and into + `note_item_conditional`, so opaque verbatim bodies cannot perturb + item-scope nesting; `scan_split_extent` returns the nesting left after a + recovered block. +- [x] 18 parser unit tests, including 10 refusal ("attack") tests and the + `open_conds` invariant test. +- [x] 13 cases in `crates/vlog_formatter/tests/cases/directive_split.cases` + (the case harness asserts idempotency on every one of them). +- [x] 10 invariant-#4 attack tests in + `crates/vlog_formatter/tests/verification.rs`. +- [x] `cargo fmt --all`, `cargo clippy --all-targets`, `cargo test` + (whole workspace) all clean. +- [x] `scripts/score.sh` 800 → 813, pass set a strict superset, + `riscv_instr_cover_group.sv` still failing. +- [ ] **Not done, deliberately:** a split whose shared tail ends in a keyword + rather than a `;`; a bracketless split (a missing terminator and a split + head are the same token stream); macro-bracketed covergroups + (`riscv_instr_cover_group.sv`); any canonical *layout* for the inside of + a split region — it stays byte-for-byte. +- [ ] **Logged, not fixed** (QA round 3, non-blocking, out of scope): + `Fmt::raw_text`'s `crosses_line_inside_string` path emits a `Doc::Text` + with embedded newlines and leaves the printer's column stale. Pre-existing + (assertions round), no corruption. See Handshakes → Consumed. + +## Work log + +### 2026-08-26 — dev + +**Baseline** (`cargo build --release && scripts/score.sh -o /tmp/score-before.tsv`): + +```json +{"passing":800,"total":820,"pct":97.6,"failures_by_category":{"directive-split":14,"invalid-or-fragment":3,"macro-items":1,"not-verilog":1,"other":1}} +``` + +**After** (`scripts/score.sh -o /tmp/score-after.tsv`): + +```json +{"passing":813,"total":820,"pct":99.1,"failures_by_category":{"invalid-or-fragment":3,"directive-split":1,"macro-items":1,"not-verilog":1,"other":1}} +``` + +`comm -23` over the two sorted pass lists is **empty** (nothing regressed) and +`comm -13` is exactly the 13 files of this cluster: + +``` +corpus/ibex/vendor/google_riscv-dv/src/riscv_instr_pkg.sv +corpus/ibex/vendor/google_riscv-dv/target/ml/riscv_core_setting.sv +corpus/ibex/vendor/google_riscv-dv/target/multi_harts/riscv_core_setting.sv +corpus/ibex/vendor/google_riscv-dv/target/rv32i/riscv_core_setting.sv +corpus/ibex/vendor/google_riscv-dv/target/rv32imafdc/riscv_core_setting.sv +corpus/ibex/vendor/google_riscv-dv/target/rv32imc/riscv_core_setting.sv +corpus/ibex/vendor/google_riscv-dv/target/rv32imc_sv32/riscv_core_setting.sv +corpus/ibex/vendor/google_riscv-dv/target/rv32imcb/riscv_core_setting.sv +corpus/ibex/vendor/google_riscv-dv/target/rv64gc/riscv_core_setting.sv +corpus/ibex/vendor/google_riscv-dv/target/rv64gcv/riscv_core_setting.sv +corpus/ibex/vendor/google_riscv-dv/target/rv64imafdc/riscv_core_setting.sv +corpus/ibex/vendor/google_riscv-dv/target/rv64imc/riscv_core_setting.sv +corpus/ibex/vendor/google_riscv-dv/target/rv64imcb/riscv_core_setting.sv +``` + +`riscv_instr_cover_group.sv` still fails with the *same* message it failed +with before (`514:5: expected declaration or instantiation (found +"cp_sign_cross")`), so the trigger did not reach it. + +Key decisions and how they were reached: + +1. **Recovery at the failed item, not a retraction back to the + `` `ifdef ``.** The brief allowed the verbatim span to begin at the + `` `ifdef `` that opened the region. It does not need to: that directive is + already its own `ItemKind::Directive`, printed verbatim by the same + `raw_text` path, and starting the block one token later means no item list + anywhere has to be rewound. Both spellings emit the same bytes; this one + touches one function. The `` `else `` / `` `endif `` still land *inside* the + block, which is where they must be for the bracket bookkeeping to work. + +2. **The "bracket left open" condition is the whole safety of the trigger.** + Without it the recovery would also fire on a forgotten `;` inside an + `` `ifdef `` arm — a shape that is genuinely ambiguous, and one that a + coverage loop would be wrong to resolve in favour of "swallow to the next + `;`". Refusing it is pinned by `a_missing_semicolon_is_not_a_split`. + +3. **The extent follows one arm.** The first thing tried was counting every + token between the item start and the terminator; on shape A that asks for + two `}` because both arms open one. Skipping the alternatives whole + (`skip_conditional_arms`) is the rule that makes shapes A and B fall out of + the same three lines, and it is why an `` `elsif `` chain of any length + works — pinned by `an_ifndef_and_an_elsif_chain_are_the_same_shape` and by + a case. + +4. **The re-walk, rather than a cursor jump.** `split_conditional_item` sets + `self.pos` back to the item's first token and `bump()`s forward to the + computed end instead of assigning the end directly. `bump` is what moves a + token's *trailing* comment into the pending bucket; jumping the cursor + would leave the comment written after the block's `;` attached to a token + nobody ever consumed, and it would be dropped — a hard-invariant break. + The duplicate comment copies the failed parse already produced all fall + inside the span and are dropped by `verbatim_since`. Pinned by + `comments_inside_a_split_region_are_kept_and_the_one_after_it_is_not`. + +5. **`verify.rs` untouched.** Nothing about verbatim bytes needs forgiveness: + the block is re-lexed on both sides and every token matches. All 13 files + pass `lucisv --check`, which runs equivalence *and* convergence. The eight + attack pairs are each refused — a dropped arm, a dropped `` `endif ``, a + dropped comment inside the region, swapped arms, a changed `` `ifdef `` + condition, a dropped element of the shared body — and the matching + *legitimate* transformation (`a_split_conditional_region_may_be_reindented`) + is accepted, so the refusals are not vacuous. + +6. **Idempotency.** The case harness re-formats every expected output and + demands a fixed point, so all 8 cases assert it. Beyond that, the whole + corpus was swept two-pass (see the sweep note below) and `lucisv --check` + on the 13 new files runs the convergence check itself. + +Files changed: + +- `crates/vlog_parser/src/parser.rs` — four free predicates, four `Parser` + methods, one dispatch change in `parse_item_inner`, 10 unit tests +- `crates/vlog_formatter/tests/cases/directive_split.cases` — new, 8 cases +- `crates/vlog_formatter/tests/verification.rs` — 8 attack tests +- `docs/features/directive-split/README.md` — this file + +Test inventory: + +| where | name | +|---|---| +| parser | `alternative_declaration_heads_sharing_one_body_are_captured_verbatim` | +| parser | `alternative_struct_bodies_sharing_one_closing_are_captured_verbatim` | +| parser | `an_ifndef_and_an_elsif_chain_are_the_same_shape` | +| parser | `a_balanced_region_inside_the_shared_tail_does_not_end_the_scan` | +| parser | `comments_inside_a_split_region_are_kept_and_the_one_after_it_is_not` | +| parser | `a_plain_syntax_error_inside_a_complete_arm_is_still_an_error` | +| parser | `a_garbage_token_run_between_directives_is_still_an_error` | +| parser | `an_unterminated_region_with_broken_code_is_still_an_error` | +| parser | `a_missing_semicolon_is_not_a_split` | +| parser | `a_region_whose_arms_are_whole_items_still_parses_arm_by_arm` | +| verify | `a_split_conditional_region_may_be_reindented` (the legitimate one) | +| verify | `a_dropped_arm_of_a_split_region_is_rejected` | +| verify | `a_dropped_endif_of_a_split_region_is_rejected` | +| verify | `a_dropped_comment_inside_a_split_region_is_rejected` | +| verify | `a_split_regions_arms_may_not_be_swapped` | +| verify | `a_changed_ifdef_condition_is_rejected` | +| verify | `a_dropped_element_of_a_split_regions_shared_body_is_rejected` | +| verify | `a_split_region_keeps_a_multiline_string_byte_for_byte` | +| cases | 8 cases in `directive_split.cases`, two of them NEGATIVE | + +### 2026-08-26 — dev (response to QA round 3) + +**The BLOCK is fixed.** QA's finding was exact: the trigger's own stated +safety condition — "closes a region the failed item never opened" — never +checked that *anyone* had opened it. The parser tracked no conditional-region +state at all, so `at_split_conditional` could only measure the failed item's +own nesting, and `scan_split_extent`'s `cond = (cond - 1).max(0)` treated any +`` `endif `` met at level zero as a legitimate closer and carried on hunting +for a `;`. A stray `` `endif `` next to any bracket-opening construct was +therefore swallowed as verbatim and reformatted with exit 0, where the +baseline refused with exit 2. + +QA also named the asymmetry that explains why only `` `endif `` leaked: +`` `else ``/`` `elsif `` got an accidental sanity check from +`skip_conditional_arms`, which demands a downstream matching `` `endif ``, so +a stray `` `else `` already refused. That was luck, not design, and it is now +design. + +**What changed** (option (a) of QA's two suggestions — file-scope open-region +state — because it also lets the extent scan reuse the same number, and +because computing it lazily by re-scanning `tokens[0..pos]` on every failed +item would be quadratic on a broken buffer in tolerant mode): + +1. `Parser` gained `open_conds: u32`, maintained in `Parser::bump` — the one + place every cursor advance in the file goes through. Saturating on + `` `endif ``, so a stray closer at the top of a file cannot make a later + genuine region look unopened. +2. A small `ItemMark { pos, conds, diags }` replaces the three loose + parameters `parse_item_inner` was passing. `conds` is the count live at the + item's first token; `split_conditional_item` restores it before re-walking + the span, so the re-walk (which goes through `bump`) does not double count. +3. `at_split_conditional` gained condition 2: `mark.conds == 0` → refuse. +4. `scan_split_extent` no longer floors at zero. It tracks `cond` (regions the + scan itself opened) separately from `live` (regions already open, seeded + from `mark.conds`), and a `` `else ``/`` `elsif ``/`` `endif `` at scan + level zero does `live.checked_sub(1)?` — i.e. gives up when nothing is + live. It also records `closed_outer` and refuses to accept a `;` as the + terminator until the already-open region has actually been closed, so a `;` + met *before* any split point can no longer end the block. That last one + closes a hole QA did not report: without it the extent could, in principle, + be shorter than the error position it was recovering. + +**Repro results** — every one of QA's files, plus the variants asked for, run +against the baseline binary built from `HEAD` in a throwaway worktree so the +comparison is exact: + +| file | baseline | before fix | after fix | +|---|---|---|---| +| `e2b_minimal.sv` (stray `` `endif ``, file scope) | exit 2 | **exit 0** | exit 2, `2:1: expected expression (found "`endif")` | +| `e2_stray_endif.sv` (same, inside a module) | exit 2 | **exit 1** | exit 2, `3:1: expected expression (found "`endif")` | +| `e9_realistic_dup_endif.sv` | exit 1 | exit 1 | exit 1 | +| `r_dup_split.sv` (duplicate `` `endif ``, then a real-looking split) | exit 2 | **exit 1** | exit 2, `7:1: expected expression (found "`else")` | +| `r_stray_far.sv` (stray `` `endif `` far from any item) | exit 1 | exit 1 | exit 1 | +| `r_nested_a.sv` (shape A inside an open outer region) | exit 2 | exit 0 | exit 0 | +| `r_nested_b.sv` (shape B inside an open outer region) | exit 2 | exit 1 | exit 1 | + +Two rows need a word, because they are the ones where "refuse" was not the +right answer: + +- **`e9_realistic_dup_endif.sv` was never a regression.** The baseline accepts + it too (exit 1), and so does the patched build — identically. There is no + split in that file: `int x[] = { 1, 2 };` is a complete declaration, so the + recovery is never even reached, and the two `` `endif `` are ordinary + `ItemKind::Directive` items. I built the file's real teeth as + `r_dup_split.sv` (the same duplicate-closer setup, but with a `` `else `` + arm after it so the recovery *would* have fired) and that one does refuse. +- **`r_stray_far.sv` is deliberately still accepted.** QA's list asked for "a + stray `` `endif `` at file scope far from any item → still refused", but the + baseline accepts it: lucisv has never validated directive nesting, and a + lone `` `endif `` at item position is an ordinary directive item. Making it + an error would be a new feature (whole-file `` `ifdef ``/`` `endif `` + balance checking), it is outside this cluster's scope, and it would be wrong + for a formatter that has to accept a header whose region is opened by its + includer. What this fix guarantees is the narrower and actually-load-bearing + property: no bracket-opening item near a stray closer is ever *swallowed*. + That is what `a_stray_endif_with_no_item_to_break_is_left_exactly_as_it_was` + pins — the items around it are still `decl` / `directive` / `decl`, never a + verbatim block. Flagged here for the lead in case a directive-balance lint + is wanted as its own item. + +**Over-tightening check** (QA's guard test, and the reason `open_conds` is a +count rather than a bool): both corpus shapes nested inside a legitimately +open outer `` `ifdef `` still recover — `a_split_nested_inside_an_open_region_ +is_still_recovered` plus two new cases. The outer region's own `` `endif `` +stays its own directive item and the item past it is not swallowed. + +**Score after the fix** — unchanged, and the pass *set* is byte-identical to +the pre-fix run (`diff` over the two sorted pass lists is empty): + +```json +{"passing":813,"total":820,"pct":99.1,"failures_by_category":{"invalid-or-fragment":3,"directive-split":1,"macro-items":1,"not-verilog":1,"other":1}} +``` + +`comm -23` against the original 800 is empty, `comm -13` is the same 13 files, +`riscv_instr_cover_group.sv` still fails with its original message. Two-pass +idempotency sweep over all 813: clean. `cargo fmt --all` clean, `cargo clippy +--all-targets` zero warnings, `cargo test --workspace` 1667 passed / 0 failed. +`verify.rs` still untouched (`git diff --stat` on it is empty). + +**Test inventory delta** (+5 tests, +3 cases): + +| where | name | +|---|---| +| parser | `a_stray_endif_is_never_a_split` (QA's `e2b` and `e2`) | +| parser | `a_closed_region_does_not_leave_a_later_endif_something_to_close` (`r_dup_split`) | +| parser | `a_stray_endif_with_no_item_to_break_is_left_exactly_as_it_was` | +| parser | `a_split_nested_inside_an_open_region_is_still_recovered` (both shapes) | +| verify | `a_stray_endif_next_to_an_open_bracket_is_refused_not_reformatted` | +| cases | shape A nested in an open region; shape B nested in an open region; NEGATIVE stray `` `endif `` beside a declaration | + +The five pre-existing refusal tests are green, unchanged. + +**Non-blocking item logged, not fixed**, as instructed: `Fmt::raw_text`'s +`crosses_line_inside_string` path emits a `Doc::Text` carrying embedded +newlines, against that variant's doc contract, leaving the printer's column +tracker stale (observed effect: conservative later breaks only). Pre-existing +from the assertions round; written up under Handshakes → Consumed and in +Status / TODO as a printer-owner item. + +### 2026-08-26 — dev (response to QA round 4) + +**The BLOCK is fixed, and the fix removes the class of bug rather than the +instance.** QA was right that round 3's guard had a second door: `Parser::bump` +counted every directive token it saw, and the constructs lucisv keeps as +opaque bytes — `constraint`, `covergroup`, `property`/`sequence`, concurrent +assertions, and this feature's own re-walk — all find their closer by walking +their body token by token *through* `bump`. An unbalanced `` `ifdef `` written +inside one of those bodies left `open_conds` one too high for the rest of the +file, and a later, wholly unrelated stray closer then passed the "a region is +live" test. + +**Mechanism chosen: move the count to the item-scope choke point, not a +suppression flag.** QA offered a guard around opaque walks or counting in a +layer that knows the context; this is the second, in its strongest form. +`bump` no longer touches `open_conds` at all. The count now lives in +`Parser::note_item_conditional`, called from the single arm of +`parse_item_kind` that consumes a directive **as an item** — which is the +literal definition of the invariant QA asked to be stated. The property that +matters for "impossible to forget on the NEXT opaque construct someone adds" +is that this inverts the default: *nothing* counts unless it is an item-scope +directive, so a new verbatim construct inherits the right behaviour by doing +nothing at all. A suppression flag or RAII guard would have kept the opt-out +shape — safe only as long as every future author remembers to opt out. The +rule is written up in Handshakes → Promised and in the Assumptions entry on +`open_conds`. + +One consequence had to be handled explicitly, and it is the same bug one level +up: a recovered split block swallows the region's own `` `else ``/`` `endif ``, +which *are* item-scope nesting even though they now sit inside opaque bytes. +So `scan_split_extent` now returns the nesting left open after the block +alongside the block's end, and `split_conditional_item` assigns it. Without +that, a split inside an outer region left the count one too high and the next +stray `` `endif `` was laundered. Pinned by +`a_recovered_block_leaves_the_right_nesting_behind_it`, whose second half is +exactly that shape. + +**Repro results** — QA's five files plus the four shapes their required-tests +list asks for: + +| file | before this fix | after | +|---|---|---| +| `g8_constraint_pollution_then_stray_endif.sv` | **exit 0** | exit 2 | +| `g10_covergroup_pollution.sv` | **exit 0** | exit 2 | +| `g11_property_pollution.sv` | **exit 1** | exit 2 | +| `g8b_isolated.sv` (tail alone) | exit 2 | exit 2 | +| `g9_balanced_constraint_control.sv` (control) | exit 2 | exit 2 | +| `s_opaque_then_split.sv` — balanced directives in an opaque body, genuine split after | — | exit 1 (recovered) | +| `s_verbatim_inside_region.sv` — a constraint inside the region the split sits in | — | exit 0 (recovered) | +| `s_two_splits.sv` — two splits under one outer region | — | exit 0 (both recovered) | +| `s_leak_after_split.sv` — stray `` `endif `` after a recovered split | — | exit 2 | + +Every round-3 repro and every earlier scratch file is unchanged +(`e2`/`e2b`/`r_dup_split` still exit 2; `e9`/`r_stray_far` still exit 1; +`r_nested_a`/`r_nested_b` still recover). + +**Under/over-count audit**, as asked. Because the count no longer rides on +`bump`, the "advances without bump" question is moot — a jump or seek cannot +affect a counter that only moves at an item-position directive. The audit that +*does* apply is the mirror one: which paths consume an item-scope directive +without going through `parse_item_kind`'s `TokenKind::Directive` arm? There is +exactly one producer of `ItemKind::Directive` in the file (parser.rs:1194), so +the answer is: + +- `StmtKind::Directive` (parser.rs:3590) — **statement** scope, correctly not + counted: no item-scope split can be delimited by it. +- `take_list_directives` (port lists, parameter lists, connection lists) — + **list** scope, inside brackets, correctly not counted. +- Opaque verbatim bodies — not item scope, correctly not counted; that is the + whole point of this fix. +- Tolerant mode's `skip_to_sync` / `recover`, which can swallow a directive + into an `ItemKind::Error` leaf — **under**-counts. This is the safe + direction: an undercount can only make a later split *refuse* recovery, and + it is unreachable in strict mode (the formatter's path), which stops at the + first error. Recorded here rather than fixed, because making error leaves + re-scan their own bytes for directives would be complexity in service of a + degraded-editor-buffer case that already produces an error leaf. + +The invariant is now pinned directly rather than inferred: the test helper +`open_conds_after` parses a whole file with a `Parser` and asserts the field, +over a balanced file, an open region, and each of the four opaque body kinds. + +**Score** — unchanged, and the pass *set* is byte-identical to both previous +runs (`diff` over the sorted lists is empty): + +```json +{"passing":813,"total":820,"pct":99.1,"failures_by_category":{"invalid-or-fragment":3,"directive-split":1,"macro-items":1,"not-verilog":1,"other":1}} +``` + +`comm -23` against the original 800 is empty, `comm -13` is the same 13 files, +`riscv_instr_cover_group.sv` still fails with its original message. Two-pass +idempotency sweep over all 813: clean. `cargo fmt --all` clean, `cargo clippy +--all-targets` zero warnings, `cargo test --workspace` 1672 passed / 0 failed. +`verify.rs` still untouched. + +**Test inventory delta** (+4 parser tests, +1 verification test, +2 cases): + +| where | name | +|---|---| +| parser | `item_scope_conditional_nesting_ignores_opaque_bodies` (the invariant, all four opaque kinds) | +| parser | `an_unbalanced_ifdef_inside_an_opaque_body_cannot_launder_a_later_stray_endif` (QA's three repros + the balanced control) | +| parser | `suppressing_opaque_bodies_does_not_suppress_the_regions_around_them` (over- and under-suppression guards) | +| parser | `a_recovered_block_leaves_the_right_nesting_behind_it` (the swallowed-`` `endif `` accounting, two splits under one region) | +| verify | `an_opaque_body_cannot_launder_a_stray_endif_into_a_split` | +| cases | over-suppression guard (constraint body + later split); under-suppression guard (constraint inside the split's own region) | + +**For the record, as asked:** QA could not find a case where the `closed_outer` +gate in `scan_split_extent` is load-bearing — removing it in an isolated +worktree diverged on nothing (813 corpus files, the parser suite, the attack +files). It stays, but it is **defensive hardening, not demonstrated +necessity**: the reasoning behind it is that without it a `;` met *before* any +split point could end the block, making the recovered extent shorter than the +error position it was recovering. I have not been able to build that input +either. Cheap to keep, and it is the kind of thing that only shows up once +some future construct changes what a depth-zero `;` can mean. + +## QA log + +### 2026-08-26 — QA (round 3) + +**Verdict: BLOCK.** One soundness hole in the trigger, no byte-corruption +found. Full inventory and repro below; the same content was returned as the +round's report. + +**1. Blocking — a stray, unmatched `` `endif `` next to any bracket-opening +construct is silently captured as verbatim instead of refused.** + +`at_split_conditional` (`crates/vlog_parser/src/parser.rs:1867`) only checks +the *failed item's own* directive nesting (the tokens between the item's +start and the cursor) to decide "this directive closes a region the item +never opened." It never checks that a real `` `ifdef ``/`` `ifndef `` for that +`` `endif `` actually exists anywhere earlier in the file — there is no such +state tracked by the parser at all (confirmed: no `conditional_depth` / +`ifdef_depth` field anywhere in `parser.rs`). `scan_split_extent` +(`parser.rs:1899`) compounds it: on `closes_conditional(t)` at `cond == 0` +(`parser.rs:1910-1913`) it does `cond = (cond - 1).max(0)` and carries on +scanning for a `;` — i.e. it treats *any* `` `endif `` met at level zero as +"the legitimate closer of the region opened before the item," unconditionally. + +This is asymmetric with the `` `else ``/`` `elsif `` path: those require +`skip_conditional_arms` to find a *matching* `` `endif `` later in the file, +which acts as an implicit sanity gate (confirmed: a stray `` `else ``/`` `elsif `` +with no downstream `` `endif `` correctly still refuses, exit 2). A stray +`` `endif `` has no such gate. + +Minimal reproduction (no module wrapper needed): +```verilog +int x[] = { +`endif +1 +}; +``` +- Before this round's patch (verified via `git stash` on `parser.rs` alone, + rebuild): `lucisv --stdout` exits 2, `parse error: 2:1: expected expression + (found "`endif")`. Correct: this is not valid Verilog — a bare `` `endif `` + with no matching `` `ifdef `` anywhere in the file is a preprocessor error. +- After the patch: `lucisv --stdout` exits **0** and prints the input back + (reindented), no diagnostic. The construct is captured whole as + `ItemKind::Verbatim` and accepted. + +A more realistic variant — a legitimate, already-*closed* `` `ifdef ``/`` `endif `` +region followed by an accidental duplicate `` `endif `` (a plausible copy-paste +typo), immediately before an unrelated declaration that happens to open a +bracket: +```verilog +module m; +`ifdef FOO + wire a; +`endif +`endif + int x[] = { + 1, 2 +}; +endmodule +``` +Patched `lucisv --stdout` exits 0, no diagnostic, reformats it as if nothing +were wrong (`int x [] = {1, 2};` on one line, both `` `endif ``s reindented +under the module). Note: this *particular* file already round-tripped at +baseline too, at exit 0 — the parser has never validated directive balance, +independent of this round — so it is evidence of scope (how a duplicate-`endif` +typo interacts with the new trigger the moment *any* bracket-opening +construct follows), not a new regression by itself. The first two reproes +(`e2b_minimal.sv`, `e2_stray_endif.sv`) are the confirmed regressions: +baseline refuses them (exit 2), the patch silently accepts them (exit 0). + +Repro files saved under +`/private/tmp/claude-501/-Users-guoliangchen-repo-verilogrustformatter/8c09e98e-a357-4a62-b0ee-ebef9e9b5c93/scratchpad/blocking_repros/` +(`e2b_minimal.sv`, `e2_stray_endif.sv`, `e9_realistic_dup_endif.sv`). + +Why this is a real defect and not pedantry: CLAUDE.md invariant #1 says the +formatter "either produces verified-correct output or emits the input +unchanged with an error. No partial output." This is not a byte-corruption +(the captured bytes are exactly the source bytes, only reindented, so +`verify.rs`'s equivalence check has nothing to catch — it checks token +equivalence, not directive balance) but it *is* the formatter accepting and +silently "fixing" genuinely invalid Verilog that a real toolchain would +reject at preprocessing, with exit 0 instead of the exit 2 + diagnostic the +task's contract (and the pre-patch behavior) both require. It also weakens +the trigger's own stated safety condition 2 ("that directive closes a region +the item never opened") — it's currently only verified for regions the item +opened, not that anyone opened at all. + +Suggested direction (not prescriptive — QA doesn't redesign): route the +`closes_conditional` branch in `scan_split_extent` through the same kind of +validation `` `else ``/`` `elsif `` already gets, or have `at_split_conditional` +refuse when there is no open `` `ifdef `` in scope. That likely needs the +parser to track (at least locally) whether a conditional region is actually +open at the point item-parsing starts — which does not exist today. + +**2. Multi-line strings / macro re-indentation — no corruption found.** +Crafted split regions and verbatim blocks with backslash-continued +multi-line string literals (including a literal backtick inside the string, +to check it isn't mistaken for a directive), at odd/mismatched indentation, +inside modules, packages, and nested split regions with a trailing line +comment after the block. All cases: byte-identical string contents preserved +(`diff` against input showed only header-line reindentation, nothing inside +the string), `--check` round-trip idempotent (`cmp` fixed point). + +One **non-blocking** observation, filed separately (not a corruption, not an +idempotency break, pre-existing code untouched by this round): `Fmt::raw_text` +(`crates/vlog_formatter/src/format.rs:225`), when +`crosses_line_inside_string` is true, returns `Doc::Text(raw.text.clone())` — +a single `Doc::Text` carrying embedded newlines. `Doc::Text`'s own doc +comment (`crates/vlog_formatter/src/doc.rs:8`) says "Must not contain +newlines (use `HardLine`)," and the printer's `Doc::Text` arm +(`crates/vlog_formatter/src/printer.rs:29-32`) does +`col += s.chars().count()` without resetting on embedded `\n` — so `col` +after such a block is a garbage (inflated) value rather than the true last- +line length. In every case tried this only ever feeds into a later +`fits()` check that conservatively forces `Break` mode (never corrupts bytes, +never mis-places a trailing comment — verified with a case placing `// trailing +comment` right after such a block, which rendered correctly and was a fixed +point). Flagged for the record since this round is the first trigger that +reaches this pre-existing escape hatch from real corpus-shaped input; no +action taken (out of this round's scope per the Handshakes section, which +marks `raw_text`/`crosses_line_inside_string` "Used unchanged"). + +**3. `verify.rs` diff: confirmed empty.** `git diff --stat -- +crates/vlog_formatter/src/verify.rs` → no output, 0 lines. No forgiveness was +added or widened. + +**4. Idempotency + equivalence at scale: 0 failures.** All 813 +`scripts/score.sh`-passing corpus files, formatted twice via `--stdout` +(scratch copies only, corpus/ untouched), asserting the second pass is a +byte-for-byte fixed point of the first, at three configs: +- default: 0/813 failures +- `--line-length 40`: 0/813 failures +- `--indent 4`: 0/813 failures + +Comment-preservation: for all 13 newly-passing corpus files, extracted the +multiset of `//`/`/* */` comment texts (string-literal-aware, backslash-escape +aware) from input vs. `--stdout` output — exact multiset match on every file +(54-479 comments per file). + +**5. Mutation fuzz: 800 trials, 0 crashes/hangs/non-idempotent +outputs/silent-diagnostic-loss.** Seeds: the two synthetic shapes from the +feature's own `.cases` file plus the two real corpus files +(`riscv_core_setting.sv`, `riscv_instr_pkg.sv`), and separately the 8 +individual case-file inputs. 1-3 chained mutations per trial (delete/duplicate/ +swap a random line; delete/duplicate/swap a random directive word, bracket, +or `;` token), 400 trials per seed set (800 total). Every mutant was required +to either format and be a fixed point on a second pass, or exit 2 with a +non-empty diagnostic and empty stdout — 0 violations of either. This fuzzing +approach has no oracle for "is this still semantically sound," which is +exactly the gap defect #1 lives in — it would not have found #1 on its own; +#1 was found by targeted construction, not fuzzing. + +**6. Tolerant mode (`lucisv check`): no new diagnostic loss.** Ran `check` on +all 13 newly-passing files and on the stray-`` `endif `` repros, at both +baseline (`git stash` on `parser.rs`) and patched. Identical diagnostic +output before/after in every case (0 diagnostics on the 13 corpus files both +times; the one unrelated `module-filename` diagnostic on the synthetic repros +present both times). The linter has never validated directive balance either +(pre-existing, confirmed at baseline), so defect #1 is not a *new* leak +specific to tolerant mode — it is a parser-level soundness gap that both +`format` and `check` inherit identically. + +**7. Build/test: clean.** `cargo build --release`: success. `cargo test +--workspace --release`: every crate green, 0 failures (33+81+69+557+29+3+30+1+ +4+6+2+22+112+190+14+197+24+20+17+72+5+50+48+6+25+1+23+20 = every reported +`test result: ok`, no `FAILED` anywhere). `cargo fmt --all -- --check`: clean. +`cargo clippy --all-targets --release`: clean, 0 warnings. +`scripts/score.sh`: `{"passing":813,...,"directive-split":1,...}` — confirmed +`riscv_instr_cover_group.sv` is the sole remaining `directive-split` failure, +matching the dev's work log. + +No fixes were made directly (defect #1 is not a "typo, missing test +assertion"-class fix — it needs a parser-level decision the dev/lead should +make, e.g. whether to track open-conditional state or restrict the +`closes_conditional` trigger branch). + +### 2026-08-26 — QA re-verification (round 4, response to the dev's fix) + +**Verdict: BLOCK.** The original finding is fixed. A new, structurally +identical hole was found in the fix's own mechanism, reached through a +different vector: an unbalanced directive inside a verbatim-captured +construct (`constraint`/`covergroup`/`property`) pollutes the new +`open_conds` counter and revives the original bug for an unrelated, later +stray closer. + +**Original repros: confirmed fixed.** `e2b_minimal.sv` and +`e2_stray_endif.sv` both now exit 2 with the expected diagnostic +(`parse error: N:1: expected expression (found "`endif")`). `cargo build +--release` clean, `cargo test --workspace --release`: every crate green, 0 +failures (spot-checked: no `FAILED` anywhere in the full run). `cargo fmt +--all -- --check` clean, `cargo clippy --all-targets --release` clean, 0 +warnings. `git diff --stat -- crates/vlog_formatter/src/verify.rs`: still +empty. + +**2. New blocking defect — an unbalanced directive inside a +`constraint`/`covergroup`/`property` body pollutes `open_conds`, reviving +defect #1 for a later, unrelated stray closer.** + +`Parser::bump` (`crates/vlog_parser/src/parser.rs:360-368`) is, per its own +comment, "the one place every cursor advance in the file goes through," and +it unconditionally updates `open_conds` for *every* token it steps over — +including tokens inside a construct whose contents are captured as opaque +verbatim bytes (`constraint`, `covergroup`, `property`/`sequence` bodies: +these are walked token-by-token via `bump` to find their closing bracket, +exactly like the split-conditional re-walk is). `bump` has no notion of +"this token is inside a verbatim region and its directive-shaped spelling is +just bytes, not real conditional-compilation structure." So a genuinely +unbalanced `` `ifdef `` written inside one of these bodies (with no matching +`` `endif `` anywhere — itself a malformed, invalid-Verilog input) leaves +`open_conds` one too high for the rest of the file. A later, wholly +unrelated stray `` `endif ``/`` `else ``/`` `elsif `` next to *any* +bracket-opening item then reads `mark.conds != 0` as "a region is live," and +is silently captured as verbatim and accepted at exit 0 — the exact defect +#1 failure mode, reopened through a different door. + +Minimal reproductions (in +`/private/tmp/claude-501/-Users-guoliangchen-repo-verilogrustformatter/8c09e98e-a357-4a62-b0ee-ebef9e9b5c93/scratchpad/round2_blocking_repros/`): + +```verilog +class c; + constraint co { + `ifdef FAKE + x < 10; + } +endclass +int y[] = { +`endif +1 +}; +``` +(`g8_constraint_pollution_then_stray_endif.sv`) — patched build: exit 0, no +diagnostic, prints the input back. The isolated tail alone +(`g8b_isolated.sv`, no constraint before it) correctly exits 2 — confirming +the constraint is what causes the divergence, not the tail shape. + +Same result with a `covergroup` (`g10_covergroup_pollution.sv`): +```verilog +covergroup cg; + `ifdef FAKE + cp: coverpoint x; +endgroup +int y[] = { +`endif +1 +}; +``` +and with a `property` (`g11_property_pollution.sv`): +```verilog +module m; + property p; + `ifdef FAKE + a |-> b; + endproperty + int y[] = { +`endif +1 +}; +endmodule +``` +Both: exit 0, no diagnostic. Both idempotent (`cmp` fixed point on a second +pass) — the acceptance is stable, not a corruption or non-convergence; it is +the same "silently accepts genuinely invalid Verilog" class as defect #1. + +**Control, to isolate cause:** the same constraint shape with the internal +directive *balanced* (`` `ifdef FAKE `` ... `` `endif `` both inside the +`constraint` body, `g9_balanced_constraint_control.sv`) correctly exits 2 — +confirming the trigger is specifically the *imbalance* inside the opaque +region, not the presence of a verbatim construct per se, and that `bump`'s ++1/-1 bookkeeping is otherwise sound. + +Why this matters at the same severity as defect #1: it defeats the fix's own +central mechanism (`open_conds`) using a vector the checklist specifically +asked to probe ("`` `ifdef `` inside a verbatim/passed-through construct"), +via a `constraint`/`covergroup`/`property` body containing a typo'd, +unmatched directive — plausible in real, buggy source, not a contrived edge +case. Bytes are not corrupted (same reasoning as defect #1: `verify.rs` +checks token equivalence, not directive balance, so it has nothing to catch +here), but genuinely invalid Verilog is again silently accepted and +reformatted at exit 0 instead of refused at exit 2. + +**Judgment call 1 — `e9_realistic_dup_endif.sv` was never a regression: +confirmed.** Rebuilt the baseline via `git stash` on `parser.rs` alone (same +method as round 3) and ran `e9_realistic_dup_endif.sv` against both baseline +and the round-2-patched build: byte-identical output, exit 0, both times. +The recovery is never reached for that file — `int x[] = {1, 2};` is a +complete, self-closing declaration, so `parse_item_kind` never fails and +`split_conditional_item` is never called; the two `` `endif ``s are ordinary +`ItemKind::Directive` items both before and after this round's work, exactly +as the dev states. The sharper variant (`r_dup_split.sv`, reconstructed from +the dev's description and matching the new unit test +`a_closed_region_does_not_leave_a_later_endif_something_to_close`) — +duplicate closer immediately followed by a real `` `else ``-based split — +does exit 2 as claimed: +`7:1: expected expression (found "`else")`. Judgment call accepted: e9 was +correctly characterized as a non-regression, and the sharper variant covers +the real risk that file was meant to represent. + +**Judgment call 2 — "a stray `` `endif `` far from any item stays +accepted": scope call accepted, but the load-bearing guarantee is not +universally true.** Reconstructed `r_stray_far.sv` from the dev's +description (`wire a;\n`endif\nwire b;\n`endif\nint x[] = {1};\n`, matching +the new test `a_stray_endif_with_no_item_to_break_is_left_exactly_as_it_was`) +and confirmed: exit 0, output unchanged in structure, both `` `endif ``s +still their own `ItemKind::Directive` items — nothing was swallowed, because +`int x[] = {1}` is complete on its own and the recovery is never reached. I +agree with the scope call itself: whole-file `` `ifdef ``/`` `endif `` +balance validation is a different feature (a directive-balance lint), is +correctly out of this cluster's scope, and would be wrong for a formatter +that must accept a header whose region is opened by its includer. + +*However*, the dev's stated guarantee — "no bracket-opening item near a +stray closer is ever swallowed" — is exactly the property defect #2 (above) +breaks. It still holds for a stray closer sitting in *otherwise-plain* code +(everything in this round's own test suite, and every one of my attacks that +does not route through a `constraint`/`covergroup`/`property` body first), +but it does not hold once an earlier, unrelated verbatim-opaque construct +with an internal unmatched directive is in the file. That is not a +scope-widening request — it's the same guarantee the dev already committed +to, just not fully delivered. + +**Extent-scan hole (`closed_outer`) — attempted but not independently +reproduced; assessed as legitimate defensive hardening, not confirmed as a +live exploit.** Built an isolated `git worktree`, copied the round-2 +`parser.rs`, and patched out only the `closed_outer` gate on +`scan_split_extent`'s `;`-acceptance condition (kept everything else, +including the `mark.conds == 0` refusal), to get a build that has the +`open_conds`/`live` machinery but not the "was the live region actually +closed" check. Ran this variant against: all 813 `scripts/score.sh`-passing +corpus files (identical pass set, identical output — `diff` over sorted pass +lists empty), the full existing parser/verify test suite (`cargo test -p +vlog_parser --lib`: 201/201 still pass *without* `closed_outer`, meaning the +dev's own new tests do not by themselves demonstrate the gate is load-bearing), +and every attack file from both this round and round 3 (including the new +pollution repros): zero divergence found anywhere. + +Reasoned through why: for `closed_outer` to matter, `scan_split_extent` needs +to reach a `;` at `brackets == 0 && cond == 0` *before* processing any +directive that decrements `live` — which requires the failed item's own +pre-failure span (`mark.pos..self.pos`) to contain an earlier, +self-contained bracket-balanced sub-construct with its own `;`, while a +directive sits inside an *open* bracket the whole time otherwise (since +`at_split_conditional` already requires `brackets > 0` at the real failure +position `self.pos`). Confirmed empirically that ordinary declaration/array- +literal grammar does *not* tolerate an embedded directive at all — it fails +at the very first one it meets (`int x[] = { `ifdef A ... }` errors right at +`` `ifdef A ``) — which rules out the most natural construction. Port lists +*do* tolerate embedded directives, but use commas, not semicolons, so they +do not supply the needed early `;`. I could not find a real Verilog +construct that supplies both an embedded-directive tolerance and an internal +semicolon at net-zero bracket depth ahead of the real failure. Conclusion: +`closed_outer` is correct, cheap, and worth keeping — it makes the +termination condition correct by construction rather than "correct because +the grammar happens to prevent the bad case" — but I did not find, and am +not asserting, a concrete input that the fix's `closed_outer` fixed. This is +reported as an honest gap in my verification, not agreement or disagreement +with the dev's claim. + +**Regression re-check.** `scripts/score.sh`: `{"passing":813,..., +"directive-split":1,...}`, identical to round 3. Sorted pass-file list +`diff`s empty against round 3's — the pass *set* is byte-identical, this +round neither gained nor lost a file. Idempotency spot-check (all 13 newly- +passing files, `--stdout` twice, default and `--line-length 40`): 0/13 +failures at each. Focused mutation fuzz on directive tokens around the new +guard (200 trials: seeds = the constraint/covergroup/property pollution +repros, the elsif-chain-nested and two-splits-in-sequence guard-attack +files, plus the two real corpus files; mutations biased toward +inserting/deleting/duplicating directive tokens and lines): 0 crashes, 0 +hangs, 0 bad exit codes, 0 non-idempotent outputs, 0 missing diagnostics — +same caveat as round 3's fuzzing: it has no "should this have been refused" +oracle, so it did not and could not have found defect #2 on its own (found +by targeted construction, matching the checklist's own explicit prompt to +try "`` `ifdef `` inside a verbatim/passed-through construct"). + +**Other targeted guard attacks, all correct:** `` `endif ``/`` `ifdef `` +text inside a string literal or a `//` comment does not affect `open_conds` +(lexer-level token kind, not text-level — confirmed via +`g1_endif_in_string.sv`, `g2_endif_in_comment.sv`, both recover correctly +and are idempotent); saturation abuse (five stray `` `endif ``s before a +genuine `` `ifdef ``+split, `g4_saturation_abuse.sv`) still recovers +correctly, confirming the `saturating_sub` design does its job; two splits +in sequence inside the same outer open region +(`g5_two_splits_in_sequence.sv`) both recover correctly with no double- +counting from the first recovery's re-walk into the second item's `mark`; +`` `ifndef `` as the opener (`g6_ifndef_opener.sv`) and an `` `elsif `` +chain nested inside an open outer region (`g7_elsif_chain_nested.sv`) both +recover correctly. All idempotent. + +**Inventory of what was run this round:** build + full workspace test suite ++ fmt + clippy (all clean); `verify.rs` diff re-confirmed empty; original +two repros re-confirmed fixed; both judgment calls independently +reconstructed and verified (not taken on the dev's word); 12 new targeted +attack files against the guard (comments/strings, verbatim-opaque-construct +pollution × 3 constructs + 1 control, saturation, re-walk double-counting, +`` `ifndef `` opener, nested `` `elsif `` chain, `r_stray_far`/`r_dup_split` +reconstructions); one isolated `git worktree` build with `closed_outer` +surgically removed, run against the full 813-file corpus and the full +existing test suite to probe the extent-scan-hole claim; `scripts/score.sh` +regression re-check (813/813, pass set unchanged); idempotency spot-check on +the 13 newly-passing files at 2 configs; 200-trial focused mutation fuzz. +No fixes made directly — defect #2 needs the same class of design decision +as defect #1 (the dev/lead should decide whether `bump` should track +verbatim-region boundaries and stop updating `open_conds` inside them, or +whether the guard should be restructured some other way). + +### 2026-08-26 — QA re-verification (round 5, decisive) + +**Verdict: PASS.** The round-4 pollution defect is fixed, at the root: `bump` +no longer touches `open_conds` at all, so no opaque token walk (constraint / +covergroup / property / sequence / assertions / a split's own re-walk) can +move it. Counting moved to `note_item_conditional`, called only from +`parse_item_kind`'s one `ItemKind::Directive` arm — the single place an +item-scope directive is actually consumed. Re-attacked this from every angle +the checklist named; nothing broke an invariant. + +**Round-4 repros: confirmed fixed.** All five files in +`round2_blocking_repros/` (`g8_constraint_pollution_then_stray_endif.sv`, +`g8b_isolated.sv`, `g9_balanced_constraint_control.sv`, +`g10_covergroup_pollution.sv`, `g11_property_pollution.sv`) now exit 2 with +the expected diagnostic. Controls unchanged: `e9_realistic_dup_endif.sv` +still exit 0 (never a regression, confirmed round 3); `r_dup_split.sv` still +exit 2; `r_stray_far.sv` still exit 0 (the accepted scope call). All round-3 +repros (`e2b_minimal.sv`, `e2_stray_endif.sv`) still exit 2. + +**Root-cause check.** `bump` (`crates/vlog_parser/src/parser.rs:362-373`) — +read in full — has zero references to `open_conds`; confirmed by direct +reading, not by trusting the commit message. The only writer is +`note_item_conditional` (`parser.rs:1841` area, called once from +`parser.rs:1190` inside `parse_item_kind`'s `TokenKind::Directive` arm) and +`split_conditional_item`'s explicit `self.open_conds = conds_after;` +(the recovered block's own `else`/`endif` are real item-scope nesting even +though they now sit inside opaque bytes, so `scan_split_extent` computes +what they leave open and hands it back explicitly — `scan_split_extent` +now returns `Option<(usize, u32)>` rather than `Option`). +Cross-checked the "doesn't count" claims by reading the actual call sites, +not just the audit note: `take_list_directives` (`parser.rs:740-752`, list +scope — port/param/connection/enum lists) consumes directives via +`take_raw_text()` directly, never calling `note_item_conditional`. +`StmtKind::Directive` (`parser.rs:3618-3620`, statement scope — +`begin`/`end`, function/task bodies) does the same. Both confirmed correct +by reading, matching the dev's audit. + +**Targeted re-attack on the new accounting — nothing found:** + +- *List-scope and statement-scope directives, both directions.* A `` `ifdef `` + written between port-list elements (list scope, uncounted) with no `` `endif `` + at list scope, followed later by a real split protected by a genuinely-open + outer region: recovers correctly + (`r1b_port_list_balanced_then_split.sv`). Same for a statement-scope + directive balanced inside `begin`/`end` + (`r1d_statement_scope_balanced_then_split.sv`). An *unmatched* directive at + list scope with no protecting outer region, followed by an attempted split: + correctly refused (`r1a_v3_no_outer.sv`, exit 2) — this is the "under-count, + safe direction" the dev's audit describes, verified rather than assumed. +- *Cross-scope nesting interleaving — the one real finding, not blocking.* + Wrapped a legitimate outer `` `ifdef OUTER ``, a module whose *port list* + has its own unmatched (list-scope) `` `ifdef EXTRA ``, an item-scope + `` `endif `` sitting right after the port list closes, and a genuine split — + all inside `OUTER` (`r1a_v4_indent_probe.sv`, + `r2c_v2_split_then_outer_endif_then_stray.sv`). Traced why: the module's own + body-item-list parse fails partway through (at the split's own `` `else ``), + that failure propagates up as the failure of the *whole* `module` item (not + just the inner declaration), and `split_conditional_item` is re-entered + with `mark` at `module`'s own first token — whose `mark.conds == 1` (from + `OUTER`) passes the trigger. Net effect: the entire module — header, a + legitimate port list, and the split — gets captured as **one** verbatim + block instead of the module being parsed and laid out normally. + Checked against every hard invariant, not waved through: bytes preserved + (confirmed by inspection — the dedent-then-reindent transform is the same + `raw_lines` mechanism every other verbatim producer uses, and I verified + the actual output matches what that transform predicts, not just that it + "looked plausible"), idempotent (`cmp` fixed point on a second pass), + comments preserved (multiset match, `r1a_v5_comment_probe.sv`, 6/6), and + `lucisv --check` on it reports "would reformat" at **exit 1**, not exit 2 — + meaning `verify.rs`'s own equivalence+convergence check passed on this + output; the safety net does not consider it wrong. And, unlike every + round-3/4 finding, the *input itself is preprocessor-valid* here — traced + by hand as a real preprocessor would: `` `ifdef OUTER `` → `` `ifdef EXTRA `` + → `` `endif `` (closes `EXTRA`) → `` `else `` (arm switch, `OUTER` still + open) → `` `endif `` (closes `OUTER`) is fully balanced. So this is not + "invalid Verilog silently accepted" (the round-3/4 failure mode) — it's + valid, preprocessor-balanced Verilog where the recovery's capture reaches + wider than its own stated design intent (an ordinary module swallowed whole + instead of formatted), producing a byte-correct, idempotent, + comment-preserving, `--check`-clean result. No CLAUDE.md hard invariant + (never corrupt code / idempotent / comments never dropped) is violated by + this — it is a quality/precision gap in *when* the trigger fires, not a + safety gap in *what* it produces. Recorded as residual risk below, not as + a blocker, per the coordinator's standing instruction to block only on a + real, reproducible invariant violation. +- *Recovered-block accounting.* Three sequential splits under one outer + region (`r2a_three_splits.sv`): each recovers as its own verbatim item, + the item after the outer `` `endif `` (`parameter int AFTER`) is not + swallowed, idempotent. A split whose own region is an `` `elsif `` chain, + itself nested under an outer open region (`r2b_elsif_chain_under_outer.sv`): + recovers correctly, idempotent. A split, then the outer region's own real + `` `endif ``, then a genuinely stray extra `` `endif `` next to a new + bracket-opening item (`r2c_v2_split_then_outer_endif_then_stray.sv`): + correctly refused, exit 2 — confirming `conds_after` leaves exactly the + right count behind and the stray closer that follows is not laundered. +- *Re-walk double-counting via `note_item_conditional`.* Checked by reading, + not by testing alone: `split_conditional_item`'s re-walk + (`parser.rs:1890-1893`) calls `self.bump()` directly in a loop — it never + calls `parse_item_kind` or `parse_item_inner` recursively, so + `note_item_conditional` (reachable only from inside `parse_item_kind`'s + `Directive` arm) cannot fire during a re-walk, and `bump` itself no longer + touches `open_conds` at all. The final `self.open_conds = conds_after` + assignment is a hard overwrite, not an increment, so even a hypothetical + stray touch during the re-walk couldn't survive it. No double-counting + possible by construction. Separately confirmed an item cannot *start* on a + directive and still reach `split_conditional_item`: `parse_item_kind`'s + `Directive` arm unconditionally succeeds (`take_raw_text` cannot fail), so + `split_conditional_item` is only ever entered for items that started on + something else. +- *Tolerant mode.* `lucisv check --no-cache` on all five round-4 repros, the + two round-3 repros, and the two new cross-scope-nesting files: no crash, no + signal death, exit 0 or 1 in every case (the lint contract, not the format + one). Constructed a file where a genuine syntax error sits inside an open + `` `ifdef `` region so that tolerant-only `skip_to_sync` (`parser.rs:484`, + gated on `self.tolerant` at every call site — confirmed strict mode never + reaches it) would skip over the region's own `` `endif `` via `bump` + (`r3_tolerant_skip_swallows_endif.sv`): strict mode correctly refuses + (exit 2); tolerant mode does not crash, exits 1 with an ordinary + diagnostic. Since `bump` no longer touches `open_conds`, a directive + swallowed into an Error leaf by `skip_to_sync` is simply never counted — + matching the dev's "safe direction" characterization for the strict-mode + (file-rewriting) path, which never takes this branch at all. For tolerant + mode itself, confirmed `--fix`/`--unsafe-fixes` are current no-ops (no + lint rule ships a fix yet, per `lucisv --help`), so there is no file-write + path for any tolerant-mode AST oddity to reach — worst case is a + diagnostic gap inside an unusual capture, the same pre-existing posture as + a `constraint`/`covergroup` region already has. + +**Regression re-check.** `scripts/score.sh`: `{"passing":813,...}`, sorted +pass-file list `diff`s empty against round 1's — the pass set is +byte-identical across all five rounds. Idempotency spot-check (13 +newly-passing files, `--stdout` twice, default and `--line-length 40`): 0/13 +failures at each. 150-trial focused mutation fuzz (seeds: the port-list/ +statement-scope/three-splits/elsif-chain/cross-scope-nesting/covergroup/ +property files above, plus the two real corpus files; mutations biased +toward directive tokens and lines at all four scopes): 0 crashes, 0 hangs, +0 bad exit codes, 0 non-idempotent outputs, 0 missing diagnostics — same +standing caveat as every prior round: this fuzzer has no "should this have +been refused" oracle, so a silent-over-acceptance bug (had one existed) +would not reliably surface this way; every real finding across all four +rounds was found by targeted construction, not fuzzing. `cargo test +--workspace --release`: 1672 passed, 0 failed, matching the dev's number +exactly (counted independently via `grep -oE "[0-9]+ passed" | awk +'{sum+=$1}'`, not copied from the report). `cargo fmt --all -- --check` and +`cargo clippy --all-targets --release`: both clean. `git diff --stat -- +crates/vlog_formatter/src/verify.rs`: empty, re-confirmed. Full change +scope: `git status --porcelain` shows only +`crates/vlog_parser/src/parser.rs`, `crates/vlog_formatter/tests/ +verification.rs`, `crates/vlog_formatter/tests/cases/directive_split.cases`, +and `docs/features/directive-split/` — nothing outside the allowed scope. + +**Residual risk (for the lead's review):** the cross-scope-nesting finding +above — an ordinary, preprocessor-valid module whose port list carries a +list-scope conditional can, if a later item-scope directive and a genuine +split line up around it just so, get captured whole as one verbatim block +instead of being parsed and formatted normally. It is real and reproducible +(`r1a_v4_indent_probe.sv`), but every CLAUDE.md hard invariant holds on it +(byte-preserving, idempotent, comments kept, `--check`-clean, and the input +is itself preprocessor-valid — nothing invalid is being accepted). It is a +precision gap in the trigger's reach, not a safety gap in its output, and +constructing it requires a fairly specific coincidence (an inner list-scope +directive plus an item-scope closer landing in exactly the wrong place +relative to a real split) that is very unlikely to occur by accident in real +source and did not affect any of the 813 corpus files. Acceptable to ship; +worth a follow-up note in `TODO.md` or this feature's own Status/TODO if the +lead wants the trigger narrowed later (e.g., requiring the failed item's +`mark.pos` to be the same item whose grammar directly produced the bracket, +rather than letting a failure inside a nested item-list propagate outward) +— not blocking this round. + +## Review + +2026-08-26, lead. **Accepted after two rejection cycles; committing.** + +The feature went through three dev passes and three adversarial QA passes. +Both QA blocks were the same failure mode — the recovery trigger trusting +conditional-nesting state it had not actually established (first: no check +that any region was open at all; second: `open_conds` polluted by tokens +inside opaque verbatim bodies). The final design is the right shape: the +count lives at the single producer of `ItemKind::Directive`, so item scope +is the definition rather than an approximation, and future verbatim +constructs are safe by default. That inversion is why I am confident this +does not have a third door. + +Independently re-verified before commit: score 813/820 (99.1%), pass set a +strict superset of the 800 baseline, `cargo test --workspace` 1672/0, +fmt/clippy clean, `verify.rs` diff empty — the safety net gained no new +forgiveness, which was this feature's non-negotiable. + +Accepted residual risk, per QA round 5: (a) the cross-scope +trigger-precision gap — a preprocessor-valid module can be captured whole +as verbatim under a specific coincidence of list-scope and item-scope +directives around a genuine split; all hard invariants hold (bytes, +comments, idempotency, exit codes) and no corpus file is affected. Follow-up +if it ever bites: narrow the trigger so a nested item-list failure does not +propagate to the enclosing item's mark. (b) `closed_outer` stands as +undemonstrated defensive hardening — QA could not construct an input where +it is load-bearing; keep it. (c) tolerant-mode `skip_to_sync` can +under-count `open_conds` — refusal-direction only, unreachable in strict +mode. (d) the pre-existing `Fmt::raw_text` embedded-newline `Doc::Text` +contract violation is the printer owner's, filed separately.