diff --git a/TODO.md b/TODO.md index 2ef95be..489d143 100644 --- a/TODO.md +++ b/TODO.md @@ -34,11 +34,7 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both. but `)` is unconditionally lexed as an attribute (`lexer.rs`), so a bare space inside `@( * )`-style spellings errors out. Make the attribute scan back off when the contents are just `*`. -- [ ] **Recursion-depth limit in the parser.** (In progress: five gates - landed and the original repro is fixed, but QA found postfix chains - — `a.b.b...`, `x[0][0]...`, `p::q::...` — are parsed iteratively with - unbounded AST depth and crash the formatter's recursion; the gate must - also cover `parse_postfix` before this checks off.) Found by cli-polish QA: +- [x] **Recursion-depth limit in the parser.** Found by cli-polish QA: ~150 levels of expression nesting overflow the stack and abort the whole process — uncatchable by `catch_unwind`, so mid-batch files after the crash never get processed. Add an explicit depth counter in diff --git a/crates/vfmt/tests/cli.rs b/crates/vfmt/tests/cli.rs index fafdab4..28c016e 100644 --- a/crates/vfmt/tests/cli.rs +++ b/crates/vfmt/tests/cli.rs @@ -241,6 +241,41 @@ fn unformattable_file_exits_2_and_is_left_untouched() { assert_eq!(code(&run(&["--diff", &dir.root()])), 2); } +#[test] +fn deeply_nested_file_does_not_kill_the_batch() { + // Before `vlog_parser`'s depth limit this input overflowed the stack and + // aborted the process, so files sorted after it were never processed — + // and a stack overflow is not a panic, so `catch_unwind` cannot help. + let deep = format!( + "module m;\nalways @(posedge clk) begin\n{}x <= 1;\n{}end\nendmodule\n", + "if (clk) begin\n".repeat(150), + "end\n".repeat(150) + ); + // A postfix chain is built by a loop, not by recursion: it costs the + // parser no depth but hands the formatter an equally deep AST, which + // crashed it the same way until chains got a budget of their own. + let chain = format!("module m;\nassign x = a{};\nendmodule\n", ".b".repeat(1500)); + let dir = TempDir::new("deep"); + dir.write("a_before.sv", UNFORMATTED); + dir.write("b_deep.sv", &deep); + dir.write("c_chain.sv", &chain); + dir.write("d_after.sv", UNFORMATTED); + + let out = run(&[&dir.root()]); + assert_eq!(code(&out), 2, "a file that cannot be parsed exits 2"); + assert_eq!(dir.read("b_deep.sv"), deep, "the offending file is left untouched"); + assert_eq!(dir.read("c_chain.sv"), chain, "the offending file is left untouched"); + assert_eq!(dir.read("a_before.sv"), FORMATTED); + assert_eq!(dir.read("d_after.sv"), FORMATTED, "files after the bad ones are still processed"); + let err = stderr(&out); + assert!(err.contains("b_deep.sv: parse error"), "{err}"); + assert!(err.contains("nesting too deep"), "{err}"); + assert!(err.contains("c_chain.sv: parse error"), "{err}"); + assert!(err.contains("expression chain too long"), "{err}"); + assert!(err.contains("2 files reformatted"), "{err}"); + assert!(err.contains("2 files failed to format"), "{err}"); +} + #[test] fn usage_errors_exit_2() { assert_eq!(code(&run(&[])), 2, "no inputs"); diff --git a/crates/vlog_formatter/tests/deep_nesting.rs b/crates/vlog_formatter/tests/deep_nesting.rs new file mode 100644 index 0000000..0f5476c --- /dev/null +++ b/crates/vlog_formatter/tests/deep_nesting.rs @@ -0,0 +1,86 @@ +//! The formatter's recursive walk against the parser's depth limit. +//! +//! `vlog_parser` bounds AST depth (`MAX_NESTING_DEPTH`), and every recursive +//! path in `format.rs`/`printer.rs` descends the AST it is handed, so these +//! tests pin the two ends of that argument: the deepest tree the parser can +//! produce still formats (and converges), and anything deeper never reaches +//! the formatter at all. + +use vlog_formatter::{format_source, Config, FormatError}; +use vlog_parser::parser::{MAX_CHAIN_LENGTH, MAX_NESTING_DEPTH}; + +/// Formatting the deepest legal tree peaks around 4 MiB of stack in an +/// unoptimized build, more than a default test thread's 2 MiB. +fn format_deep(source: String) -> Result { + std::thread::Builder::new() + .stack_size(16 * 1024 * 1024) + .spawn(move || format_source(&source, &Config::default())) + .expect("spawn formatter thread") + .join() + .expect("formatter thread crashed") +} + +/// `n` nested `begin` blocks; the module and the `initial` add two levels. +fn nested_begins(n: usize) -> String { + format!( + "module m;\ninitial\n{}x <= 1;\n{}\nendmodule\n", + "begin\n".repeat(n), + "end\n".repeat(n) + ) +} + +/// `n` nested parenthesized expressions. +fn nested_parens(n: usize) -> String { + format!("module m;\nassign x = {}1{};\nendmodule\n", "(".repeat(n), ")".repeat(n)) +} + +#[test] +fn deepest_legal_statement_nesting_formats() { + // Two levels for `module` + `initial`, one for the innermost statement. + let out = format_deep(nested_begins(MAX_NESTING_DEPTH as usize - 5)) + .expect("the deepest tree the parser accepts must format"); + assert!(out.ends_with("end\nendmodule\n"), "{}", &out[out.len().saturating_sub(40)..]); + // `format_source` verifies equivalence and convergence internally, so a + // second pass returning the same text is the idempotency check. + let again = format_deep(out.clone()).expect("reformat"); + assert_eq!(out, again, "formatting deep nesting is a fixed point"); +} + +#[test] +fn deepest_legal_expression_nesting_formats() { + let out = format_deep(nested_parens(MAX_NESTING_DEPTH as usize / 2 - 2)) + .expect("the deepest expression the parser accepts must format"); + let again = format_deep(out.clone()).expect("reformat"); + assert_eq!(out, again, "formatting deep expressions is a fixed point"); +} + +/// `a` followed by `n` postfix segments — a chain the parser builds with a +/// loop, so it costs no parser recursion but one AST layer per segment. +fn member_chain(n: usize) -> String { + format!("module m;\nassign x = a{};\nendmodule\n", ".b".repeat(n)) +} + +#[test] +fn longest_legal_chain_formats() { + let out = format_deep(member_chain(MAX_CHAIN_LENGTH as usize)) + .expect("the longest chain the parser accepts must format"); + let again = format_deep(out.clone()).expect("reformat"); + assert_eq!(out, again, "formatting a maximal chain is a fixed point"); +} + +#[test] +fn nesting_past_the_limit_never_reaches_the_formatter() { + let cases = [ + (nested_begins(400), "nesting too deep"), + (nested_parens(400), "nesting too deep"), + (member_chain(1500), "expression chain too long"), + ]; + for (src, expected) in cases { + match format_deep(src) { + Err(FormatError::Source(e)) => { + assert!(e.to_string().contains(expected), "unexpected error: {e}") + } + other => panic!("expected a parse error, got {other:?}"), + } + } +} diff --git a/crates/vlog_parser/src/parser.rs b/crates/vlog_parser/src/parser.rs index 1cbf14d..9b8d6f5 100644 --- a/crates/vlog_parser/src/parser.rs +++ b/crates/vlog_parser/src/parser.rs @@ -5,6 +5,13 @@ //! `pending_trailing`. Statements/items/list elements harvest those at //! well-defined points; anything left over is folded into the next node's //! leading comments so no comment is ever dropped. +//! +//! Depth limiting: recursive descent means input nesting becomes call +//! nesting, and a stack overflow aborts the process (it is not a catchable +//! panic). Every parse function that can recurse without consuming a bounded +//! number of tokens per level brackets itself with [`Parser::enter`] / +//! [`Parser::leave`], turning nesting past [`MAX_NESTING_DEPTH`] into an +//! ordinary [`ParseError`]. use crate::ast::*; use crate::token::{Comment, Token, TokenKind}; @@ -57,16 +64,55 @@ const GATE_KEYWORDS: &[&str] = &[ const ASSIGN_OPS: &[&str] = &["=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", "<<<=", ">>>="]; +/// How deeply constructs may nest before the parser gives up. +/// +/// Chosen from measured stack use, not from taste: nested statements are the +/// most expensive family at ~62 KiB of stack per level in an unoptimized +/// build, so formatting an input that trips the limit peaks at ~3.9 MiB — +/// comfortably under the 8 MiB default main-thread stack, and ~0.5 MiB in +/// an optimized build. Real RTL nests roughly an order of magnitude less +/// than this; see `docs/features/recursion-limit/README.md`. +pub const MAX_NESTING_DEPTH: u32 = 64; + +/// How many links a left-nested chain may add to the tree on one path. +/// +/// Some constructs are parsed by a loop rather than by recursion — postfix +/// segments (`a.b`, `a::b`, `a[i]`, `a(x)`, `a++`) and binary/`inside` +/// operator chains (`a + b + c`) — but each iteration still wraps what came +/// before in another AST layer, which the *formatter* then recurses over. +/// They therefore get their own budget: it is accumulated along a path the +/// same way [`MAX_NESTING_DEPTH`] is, so total AST depth stays bounded by +/// the two limits together no matter how chains and nesting are combined. +/// +/// It is larger than [`MAX_NESTING_DEPTH`] because a chain link is cheap — +/// ~6 KiB of stack per link in an unoptimized build against ~62 KiB for a +/// nested statement, so a maximal chain peaks near 1.5 MiB, well under the +/// ~3.9 MiB that maximal statement nesting already costs — and because long +/// flat chains are the one shape real RTL does produce (a 256-term generated +/// sum, a 64-bit parity XOR). Raising it, unlike raising +/// [`MAX_NESTING_DEPTH`], does not move the worst case. +pub const MAX_CHAIN_LENGTH: u32 = 256; + pub struct Parser { tokens: Vec, pos: usize, pending_leading: Vec, pending_trailing: Vec, + /// Currently open nested constructs; see [`MAX_NESTING_DEPTH`]. + depth: u32, + /// Chain links open on the current path; see [`MAX_CHAIN_LENGTH`]. + links: u32, } pub fn parse(tokens: Vec) -> PResult { - let mut p = - Parser { tokens, pos: 0, pending_leading: Vec::new(), pending_trailing: Vec::new() }; + let mut p = Parser { + tokens, + pos: 0, + pending_leading: Vec::new(), + pending_trailing: Vec::new(), + depth: 0, + links: 0, + }; p.parse_source_file() } @@ -98,6 +144,35 @@ impl Parser { t } + /// Open one level of nesting, refusing to recurse past + /// [`MAX_NESTING_DEPTH`]. Callers that succeed must pair this with + /// [`Parser::leave`] on every path out, including the error paths. + fn enter(&mut self) -> PResult<()> { + if self.depth >= MAX_NESTING_DEPTH { + return self.error(format!("nesting too deep (limit {MAX_NESTING_DEPTH})")); + } + self.depth += 1; + Ok(()) + } + + /// Close the level opened by [`Parser::enter`]. + fn leave(&mut self) { + self.depth -= 1; + } + + /// Add one link to a left-nested chain, refusing past + /// [`MAX_CHAIN_LENGTH`]. Links are released by restoring the count a + /// chain started from (see the `parse_binary` / `parse_postfix` + /// wrappers), so a chain built inside another chain's operand stacks on + /// top of it instead of resetting it. + fn link(&mut self) -> PResult<()> { + if self.links >= MAX_CHAIN_LENGTH { + return self.error(format!("expression chain too long (limit {MAX_CHAIN_LENGTH})")); + } + self.links += 1; + Ok(()) + } + fn error(&self, message: impl Into) -> PResult { let t = self.cur(); let shown = if t.kind == TokenKind::Eof { "" } else { t.text.as_str() }; @@ -277,7 +352,15 @@ impl Parser { Ok(SourceFile { items, dangling }) } + /// Items nest through generate blocks and package bodies. Gated. fn parse_item(&mut self) -> PResult { + self.enter()?; + let out = self.parse_item_inner(); + self.leave(); + out + } + + fn parse_item_inner(&mut self) -> PResult { let mut meta = self.take_meta(); while self.cur().kind == TokenKind::Attribute { meta.attrs.push(self.take_raw_text()); @@ -1052,7 +1135,15 @@ impl Parser { // Generate constructs // ------------------------------------------------------------------ + /// An `else if` chain recurses here directly, bypassing `parse_item`. Gated. fn parse_gen_if(&mut self) -> PResult { + self.enter()?; + let out = self.parse_gen_if_inner(); + self.leave(); + out + } + + fn parse_gen_if_inner(&mut self) -> PResult { self.expect_kw("if")?; self.expect_sym("(")?; let cond = self.parse_expr()?; @@ -1240,7 +1331,15 @@ impl Parser { // Statements // ------------------------------------------------------------------ + /// Statements nest through blocks and every compound statement. Gated. fn parse_stmt(&mut self) -> PResult { + self.enter()?; + let out = self.parse_stmt_inner(); + self.leave(); + out + } + + fn parse_stmt_inner(&mut self) -> PResult { let mut meta = self.take_meta(); while self.cur().kind == TokenKind::Attribute { meta.attrs.push(self.take_raw_text()); @@ -1663,7 +1762,17 @@ impl Parser { self.parse_ternary() } + /// The gate for the whole expression grammar: every expression recursion + /// (parens, concatenations, call arguments, index expressions, and the + /// `? :` chain itself) comes back through here. fn parse_ternary(&mut self) -> PResult { + self.enter()?; + let out = self.parse_ternary_inner(); + self.leave(); + out + } + + fn parse_ternary_inner(&mut self) -> PResult { let cond = self.parse_binary(1)?; if self.cur().is_sym("?") { self.bump(); @@ -1701,7 +1810,17 @@ impl Parser { Some(p) } + /// Operator chains grow the tree one layer per operator without any + /// parser recursion, so they are bounded by [`MAX_CHAIN_LENGTH`]; the + /// links this chain adds are released when it is finished. fn parse_binary(&mut self, min_prec: u8) -> PResult { + let outer_links = self.links; + let out = self.parse_binary_inner(min_prec); + self.links = outer_links; + out + } + + fn parse_binary_inner(&mut self, min_prec: u8) -> PResult { let mark = self.pending_trailing.len(); let mut lhs = self.parse_unary()?; while let Some(prec) = self.binary_prec() { @@ -1739,6 +1858,7 @@ impl Parser { } } self.expect_sym("}")?; + self.link()?; lhs = Expr::Inside { lhs: Box::new(lhs), ranges }; continue; } @@ -1748,12 +1868,22 @@ impl Parser { comments.append(&mut self.take_leading_here()); let op = self.bump().text; let rhs = self.parse_binary(prec + 1)?; + self.link()?; lhs = Expr::Binary { lhs: Box::new(lhs), op, rhs: Box::new(rhs), comments }; } Ok(lhs) } + /// Stacked prefix operators (`~~~~x`) recurse here directly, without + /// passing through `parse_ternary`. Gated. fn parse_unary(&mut self) -> PResult { + self.enter()?; + let out = self.parse_unary_inner(); + self.leave(); + out + } + + fn parse_unary_inner(&mut self) -> PResult { let t = self.cur(); if t.kind == TokenKind::Symbol && matches!( @@ -1768,9 +1898,32 @@ impl Parser { self.parse_postfix() } + /// True if the current token continues a postfix chain. + fn at_postfix_segment(&self) -> bool { + let t = self.cur(); + t.is_sym(".") + || t.is_sym("::") + || t.is_sym("[") + || t.is_sym("(") + || (t.is_sym("'") && self.nth(1).is_sym("(")) + || t.is_sym("++") + || t.is_sym("--") + } + + /// Postfix segments are parsed by a loop, but each one wraps the + /// expression so far in another AST layer, so they are bounded by + /// [`MAX_CHAIN_LENGTH`]; the links are released when the chain ends. fn parse_postfix(&mut self) -> PResult { + let outer_links = self.links; + let out = self.parse_postfix_inner(); + self.links = outer_links; + out + } + + fn parse_postfix_inner(&mut self) -> PResult { let mut expr = self.parse_primary()?; - loop { + while self.at_postfix_segment() { + self.link()?; let t = self.cur(); if t.is_sym(".") { self.bump(); @@ -1820,11 +1973,10 @@ impl Parser { let inner = self.parse_expr()?; self.expect_sym(")")?; expr = Expr::Cast { ty, expr: Box::new(inner) }; - } else if t.is_sym("++") || t.is_sym("--") { + } else { + // `++` / `--`, the only remaining segment kind. let op = self.bump().text; expr = Expr::Postfix { expr: Box::new(expr), op }; - } else { - break; } } Ok(expr) @@ -1964,6 +2116,194 @@ mod tests { } } + /// Parse on a thread with a generous stack. Nesting all the way to + /// [`MAX_NESTING_DEPTH`] peaks around 4 MiB in an unoptimized build, + /// which is more than the 2 MiB a default test thread gets — the shipped + /// binary parses on the main thread, which has 8 MiB. + fn parse_deep(src: String) -> PResult { + std::thread::Builder::new() + .stack_size(16 * 1024 * 1024) + .spawn(move || parse(tokenize(&src).expect("lex error"))) + .expect("spawn parser thread") + .join() + .expect("parser thread crashed") + } + + fn assert_too_deep(src: String) { + let err = parse_deep(src).expect_err("expected a nesting-depth error"); + assert!( + err.message.contains(&format!("nesting too deep (limit {MAX_NESTING_DEPTH})")), + "unexpected error: {err}" + ); + assert!(err.line > 0, "error carries a position: {err}"); + } + + fn assert_chain_too_long(src: String) { + let err = parse_deep(src).expect_err("expected a chain-length error"); + assert!( + err.message.contains(&format!("expression chain too long (limit {MAX_CHAIN_LENGTH})")), + "unexpected error: {err}" + ); + assert!(err.line > 0, "error carries a position: {err}"); + } + + /// `n` nested `begin` blocks in an `initial`, innermost one empty. The + /// module and the `initial` item each take one level, so the deepest + /// level reached is `n + 2`. + fn nested_begins(n: usize) -> String { + format!("module m;\ninitial\n{}{}\nendmodule\n", "begin\n".repeat(n), "end\n".repeat(n)) + } + + /// `assign x = a` followed by `n` copies of `segment`, e.g. `.b` — a + /// chain the parser builds in a loop, one AST layer per copy. + fn chain(segment: &str, n: usize) -> String { + format!("module m;\nassign x = a{};\nendmodule\n", segment.repeat(n)) + } + + #[test] + fn nesting_just_below_the_limit_parses() { + let src = nested_begins(MAX_NESTING_DEPTH as usize - 2); + parse_deep(src).expect("nesting at the limit must still parse"); + } + + #[test] + fn nesting_just_past_the_limit_is_a_parse_error() { + assert_too_deep(nested_begins(MAX_NESTING_DEPTH as usize - 1)); + } + + #[test] + fn deep_statement_nesting_errors() { + // The cli-polish QA repro: 150 levels of `if (clk) begin ... end`. + let n = 150; + assert_too_deep(format!( + "module m;\nalways @(posedge clk) begin\n{}x <= 1;\n{}end\nendmodule\n", + "if (clk) begin\n".repeat(n), + "end\n".repeat(n) + )); + // `else if` chains recurse through the `else` branch. + assert_too_deep(format!( + "module m;\ninitial\n{}x <= 0;\nendmodule\n", + "if (c) x <= 1; else\n".repeat(300) + )); + } + + #[test] + fn deep_expression_nesting_errors() { + let d = 400; + // Parenthesized, concatenated, called, and `? :`-chained expressions + // all recurse through `parse_ternary`; stacked prefix operators + // recurse through `parse_unary`. + assert_too_deep(format!( + "module m;\nassign x = {}1{};\nendmodule\n", + "(".repeat(d), + ")".repeat(d) + )); + assert_too_deep(format!( + "module m;\nassign x = {}z{};\nendmodule\n", + "{a, ".repeat(d), + "}".repeat(d) + )); + assert_too_deep(format!( + "module m;\nassign x = {}y{};\nendmodule\n", + "f(".repeat(d), + ")".repeat(d) + )); + assert_too_deep(format!("module m;\nassign x = {}z;\nendmodule\n", "a ? b : ".repeat(d))); + assert_too_deep(format!("module m;\nassign x = {}y;\nendmodule\n", "~".repeat(d))); + } + + #[test] + fn deep_generate_nesting_errors() { + let d = 200; + assert_too_deep(format!( + "module m;\ngenerate\n{}wire w;\n{}endgenerate\nendmodule\n", + "if (1) begin\n".repeat(d), + "end\n".repeat(d) + )); + assert_too_deep(format!( + "module m;\ngenerate\n{}wire w;\n{}endgenerate\nendmodule\n", + "for (i = 0; i < 2; i = i + 1) begin\n".repeat(d), + "end\n".repeat(d) + )); + // Generate `else if` chains recurse without going through an item. + assert_too_deep(format!( + "module m;\ngenerate\n{}begin wire wz; end\nendgenerate\nendmodule\n", + "if (c) begin wire w; end else\n".repeat(d) + )); + } + + #[test] + fn chain_just_below_the_limit_parses() { + parse_deep(chain(".b", MAX_CHAIN_LENGTH as usize)) + .expect("a chain at the limit must still parse"); + } + + #[test] + fn chain_just_past_the_limit_is_a_parse_error() { + assert_chain_too_long(chain(".b", MAX_CHAIN_LENGTH as usize + 1)); + } + + #[test] + fn long_chains_error() { + // These are built by loops, not by recursion, so they cost the parser + // no depth at all — but every segment is one more AST layer for the + // formatter to walk, which is what `MAX_CHAIN_LENGTH` bounds. + let n = MAX_CHAIN_LENGTH as usize + 1; + for segment in [".b", "::b", "[0]", "()", "++", " + a", " inside {1}"] { + assert_chain_too_long(chain(segment, n)); + } + // Dimension expressions get their own (compact) formatter walk. + assert_chain_too_long(format!("module m;\nwire [a{}:0] w;\nendmodule\n", "+a".repeat(n))); + } + + #[test] + fn chains_nested_inside_chains_stay_bounded() { + // The budget accumulates along a path, so nesting cannot multiply it: + // 7 call levels each carrying a 40-segment chain is over the limit + // even though no single chain is. + let level = format!("a{}(", ".b".repeat(40)); + assert_chain_too_long(format!( + "module m;\nassign x = {}z{};\nendmodule\n", + level.repeat(7), + ")".repeat(7) + )); + } + + /// One of everything that opens a gated level or adds a chain link: + /// `parse_item`, `parse_stmt`, `parse_ternary`, `parse_unary`, + /// `parse_gen_if`, postfix segments and operator chains. + fn all_gates_unit() -> String { + "initial begin\n if (c) x <= (a ? b : ~c) + d.e[f] + g.h.i;\nend\n\ + generate\n if (c) begin wire w; end else if (d) begin wire v; end\nendgenerate\n" + .to_string() + } + + #[test] + fn depth_and_links_are_released_on_the_way_out() { + // Every gate and both chain sites run several times per unit, so a + // single missing release anywhere makes the counters creep up until a + // limit trips part-way through the 200 siblings. + parse_deep(format!("module m;\n{}endmodule\n", all_gates_unit().repeat(200))) + .expect("sibling constructs must not accumulate depth or links"); + // 200 sibling blocks, each nested 40 deep. + let one = format!("initial\n{}{}\n", "begin\n".repeat(40), "end\n".repeat(40)); + parse_deep(format!("module m;\n{}endmodule\n", one.repeat(200))) + .expect("sibling nesting must not accumulate depth"); + // 200 sibling chains, each half the link budget long. + let half = format!("assign y = a{};\n", ".b".repeat(MAX_CHAIN_LENGTH as usize / 2)); + parse_deep(format!("module m;\n{}endmodule\n", half.repeat(200))) + .expect("sibling chains must not accumulate links"); + // Two chains inside *one* expression are siblings too, not a path: + // 200 links each is legal, 400 on one path would not be. + let n = 200; + parse_deep(format!( + "module m;\nassign x = a{} + c{};\nendmodule\n", + ".b".repeat(n), + ".d".repeat(n) + )) + .expect("sibling chains in one expression must not accumulate links"); + } + #[test] fn simple_module() { let f = parse_ok("module m(input clk, output reg [7:0] q); endmodule"); diff --git a/docs/features/recursion-limit/README.md b/docs/features/recursion-limit/README.md new file mode 100644 index 0000000..aada5ea --- /dev/null +++ b/docs/features/recursion-limit/README.md @@ -0,0 +1,925 @@ +# recursion-limit + +## Goal + +`vlog_parser` is a recursive-descent parser, so nesting in the input becomes +nesting on the call stack. Deeply nested input therefore did not produce a +parse error — it overflowed the stack and killed the process (SIGABRT). A +stack overflow is not a panic, so `catch_unwind` in `crates/vfmt/src/main.rs` +could not contain it: the run died mid-batch, every file after the offending +one went unprocessed, and there was not even an exit-code-2 summary +(cli-polish QA finding, `docs/features/cli-polish/README.md`). This feature +adds an explicit nesting-depth counter to the parser so that input nested +past a documented limit becomes an ordinary `ParseError` with a position, the +file is left untouched, and the rest of the batch still gets formatted. It +also audits the formatter's recursive walk, which turns out to be bounded by +the parser's limit and needs no counter of its own. + +## The invariant + +> **No input can make AST depth exceed `MAX_NESTING_DEPTH + MAX_CHAIN_LENGTH` +> (64 + 256 = 320 layers) on any root-to-leaf path**, so every recursive walk +> over the tree — the formatter's, the `Doc` tree's, and the implicit +> recursive `Drop` — is bounded too. + +Two things can add a layer to the tree, and each has a counter, both +accumulated *along a path* and released when the construct that opened them +finishes: + +| | counter | limit | charged by | +|---|---|---|---| +| **Nesting** — one parser recursion per layer | `depth` | `MAX_NESTING_DEPTH` = 64 | the 5 gated `parse_*` functions | +| **Chains** — a loop that wraps what it already built | `links` | `MAX_CHAIN_LENGTH` = 256 | postfix segments, binary/`inside` operator chains | + +The chain counter exists because a loop can deepen the AST without deepening +the parser: `a.b.b.b…` costs `parse_postfix` a single frame but builds one +`Expr::Member` per segment, and the *formatter* then recurses once per layer. +That gap crashed the formatter on a 3 KiB file until this second budget +landed (QA finding, 2026-08-19). + +Because both counters accumulate along a path rather than per construct, +nesting and chains cannot multiply: a chain inside another chain's operand +stacks on top of it, so `f(a.b…)(a.b…)…` is bounded by the same 320 layers, +not by 64 × 256. + +## Assumptions + +- **The limits count AST layers, not source constructs.** Different + constructs spend a different number of levels per source construct: one + nested `begin` costs 1 depth, one nested `(...)` costs 2 (`parse_ternary` + + `parse_unary`), one nested generate `if` costs 2 (`parse_item` + + `parse_gen_if`), one `.b` or one `+` costs 1 link. The limits are a + stack-safety budget, not a style rule. +- **8 MiB of stack is available.** That is the default main-thread stack on + macOS and Linux, and `vfmt` parses on the main thread. Anything that parses + on a *spawned* thread must give it a comparable stack — the default 2 MiB + is not enough to reach the limit in an unoptimized build (see Handshakes; + the tests here spawn 16 MiB threads for exactly this reason). +- **Unoptimized builds are the worst case.** Debug stack frames in this + parser are large (`parse_keyword_stmt` alone is a ~50 KiB frame at + `opt-level=0`, because rustc gives every match arm's temporaries their own + slot and does not merge them). The limit is picked for debug builds, so + release builds have an order of magnitude more headroom. +- **Rejecting an over-deep file is acceptable behavior.** The file is left + untouched with a diagnostic and exit 2, exactly like any other parse error. + No real RTL is expected anywhere near the limit; machine-generated + expression chains are the plausible outlier, which is why the limit is set + well above hand-written depths rather than at the smallest safe value. +- **The formatter is only reachable through `format_source(&str)`.** There is + no public API that takes an AST, so every tree the formatter walks came + from the gated parser. If an AST-taking entry point is ever exposed, the + formatter audit below has to be revisited. + +## The limits + +``` +MAX_NESTING_DEPTH = 64 (crates/vlog_parser/src/parser.rs) +MAX_CHAIN_LENGTH = 256 +``` + +Going one past either produces an ordinary parse error: + +``` +error: rtl/deep.sv: parse error: 32:5: nesting too deep (limit 64) (found "clk") +error: rtl/chain.sv: parse error: 2:525: expression chain too long (limit 256) (found ".") +``` + +### Why 64 — measured, not guessed + +Method: a scratchpad copy of the workspace with a probe binary +(`examples/depth_probe.rs`, never committed) that runs the *whole* pipeline +(`format_source`: parse → doc build → print → verify's re-parse and re-format) +on a thread with a chosen stack size, over generated inputs for eight nesting +families. Bisecting the thread stack size gives the worst-case peak usage. + +Without any limit, the deepest input that survived a 2 MiB thread: + +| family | debug | release | +|---|---|---| +| nested `if`/`begin` statements | **15 levels** | 136 | +| `else if` chains | 29 | 253 | +| nested generate `if` | 52 | 256 | +| nested `(...)` / `{...}` | 63–67 | 553–677 | +| `? :` chains / stacked `~` | 345 | 3461 | + +That is ~140 KiB of stack per nested statement in a debug build — the reason +the cli-polish repro (150 levels) died. Per *depth-counter level* the worst +family costs ~72 KiB (debug) / ~8 KiB (release). + +With the limit in place, the peak stack of the full pipeline on input that +trips the limit (bisected the same way, minimum surviving thread stack): + +| family | debug peak | release peak | +|---|---|---| +| `else if` chains (worst) | **3959 KiB** | 487 KiB | +| nested `if`/`begin` | 3847 KiB | 455 KiB | +| nested generate `if` | 1239 KiB | 183 KiB | +| nested `{...}` / `(...)` | 983–1047 KiB | 103 KiB | +| `? :` chains, stacked `~` | 135–423 KiB | — | + +So the worst case is **~3.9 MiB in a debug build, ~0.5 MiB in release**, +against an 8 MiB main-thread stack: 2× headroom in the profile with the fat +frames, 16× in the profile users actually run. + +Why not larger: 128 would need ~7.9 MiB in a debug build — i.e. the CLI +integration tests, which run the *debug* binary, would still overflow before +the limit ever tripped. Why not smaller: 64 levels comfortably covers +generated code, while hand-written RTL rarely passes 10. + +What 64 buys, per construction (all verified against the binary — the exact +number depends on what else is on the path, which is why each is spelled +out): + +| construction | deepest that parses | +|---|---| +| `module` → `initial` → nested `begin`, innermost block **empty** | 62 (63 errors) | +| `module` → `initial` → nested `begin`, innermost holds `x <= 1;` | 59 (60 errors) | +| `module` → `assign x =` nested `(…)` | 30 parens (31 errors) | +| `module` → nested generate `if … begin` | 30 (31 errors; corrected by lead per re-QA measurement) | +| `? :` chain in an `assign` | ~60 arms | + +The two `begin` rows differ because a statement inside the innermost block +costs three more levels (the statement plus `parse_ternary`/`parse_unary` for +its expression). The parser's own boundary unit tests use the empty-block +construction (62/63); `vlog_formatter`'s use the ones with content. + +### Why 256 for chains + +Same method, measuring inputs sized to sit exactly *at* the limits so the +formatter really walks them (min surviving thread stack, debug / release): + +| exactly-legal worst case | debug | release | +|---|---|---| +| 256-link chain alone | 1511 KiB | 119 KiB | +| 30 nested parens with a 256-link chain inside | 1703 KiB | 135 KiB | +| 29 nested generate `if` with a 256-link chain inside | 1671 KiB | — | +| 59 nested `begin` with a 256-link chain inside | 3655 KiB | 423 KiB | +| 58-deep `else if` chain with a 256-link chain inside | **3895 KiB** | 487 KiB | + +A link costs ~6 KiB of stack in a debug build, an order of magnitude less +than a nested statement (~62 KiB), and the two peaks land in *different +phases* — deep statements peak while parsing, long chains while formatting — +so the chain budget does not move the global worst case at all (3895 KiB with +the chain, 3959 KiB without it). That makes 256 a free choice on the stack +side, and it is the side of the trade-off that matters for acceptance: long +flat chains are the one deep shape real RTL genuinely produces (a 64-bit +parity XOR is 63 links, a 128-term generated sum is 127, a 256-term one +fits). Charging chain links against `MAX_NESTING_DEPTH` instead would have +capped those at ~60 terms and rejected real code; that is why chains get +their own, larger budget rather than sharing the nesting one. + +## Where the counters sit + +`Parser::enter()` / `Parser::leave()` bracket each gated function; `enter` +returns the parse error instead of incrementing when the limit is reached, so +the guard rides the existing `?` propagation: + +```rust +fn parse_stmt(&mut self) -> PResult { + self.enter()?; + let out = self.parse_stmt_inner(); + self.leave(); + out +} +``` + +Chain links use the same shape, except that the release restores the count +the chain started from rather than subtracting one — so a chain nested inside +another chain's operand stacks on top of it, while sibling chains each start +from their enclosing level: + +```rust +fn parse_postfix(&mut self) -> PResult { + let outer_links = self.links; + let out = self.parse_postfix_inner(); // calls self.link()? per segment + self.links = outer_links; + out +} +``` + +Five functions are gated for nesting. Every unbounded recursion cycle in the +grammar passes through at least one of them: + +| gated function | cycles it cuts | +|---|---| +| `parse_item` | module/package/generate-region bodies, generate blocks (`parse_gen_block` → `parse_item`) | +| `parse_stmt` | `begin`/`fork` blocks and every compound statement (`if`, `for`, `while`, `do`, `repeat`, `forever`, `foreach`, `wait`, `assert`, case items, timing controls), including `else if` chains | +| `parse_gen_if` | generate `else if` chains, which recurse directly without passing through `parse_item` | +| `parse_ternary` | the entire expression grammar: `parse_expr` delegates here, and parens, concatenations, replications, assignment patterns, call arguments, index/range expressions, `inside` ranges, dimensions, casts and delay values all recurse back through `parse_expr`. Also the `? :` else-chain, which recurses into `parse_ternary` directly | +| `parse_unary` | stacked prefix operators (`~~~~x`), which recurse directly without passing through `parse_ternary` | + +Two loops charge chain links instead, because they deepen the tree without +deepening the parser (this is the hole the first round of this feature +missed): + +| chain site | shapes | +|---|---| +| `parse_postfix` | `a.b`, `a::b`, `a[i]`, `a[m:l]`, `a(args)`, `a'(x)`, `a++`/`a--` — one link per segment | +| `parse_binary` | `a + b + c…` (one link per operator, any precedence) and `a inside {…} inside {…}` | + +Not charged at all, and why: + +- `parse_binary(min_prec)`'s *recursion* (with `min_prec + 1`) is self-bounded + by the 11-level precedence table (≤ 12 frames per operand); it is the loop + in the same function, not the recursion, that needs the link budget. +- `parse_dims`, `parse_declarators`, `parse_expr_list`, `parse_connections`, + `parse_tf_body`, `parse_source_file`, the enum/struct member loops and the + instance/connection loops are iterative *and* collect into a `Vec`, so an + extra iteration widens the tree instead of deepening it. Verified by + checking every `Box::new` site in `parser.rs`: outside `parse_postfix` and + `parse_binary`, all of them run once per gated recursive call. +- `parse_opt_data_type` / `parse_type_expr` reach `parse_expr` through + `parse_dims`; typedefs cannot nest inside typedefs. +- `scan_matching` (lookahead) is a loop that builds nothing. + +## Formatter audit (no gate needed) + +`crates/vlog_formatter` walks the AST the parser produced, and every +recursive path descends into a *child node* of its argument, so the formatter +walk is bounded by AST depth — which is what the two counters above bound. +Note the order of the argument: the formatter is safe *because* AST depth is +bounded, so the invariant at the top of this file is load-bearing, not a +nicety. When only parser *recursion* was bounded (first round of this +feature), chain-built AST slipped through and the formatter still crashed; +the premise has to cover every way a layer can be added to the tree. + +- `format.rs`: `item`/`item_kind`, `stmt`/`stmt_kind`/`stmt_as_body`/ + `block_doc`, `if_stmt` (recurses once per `else if`, i.e. once per gated + `parse_stmt` level), `expr`, `expr_compact`, `parens`, `expr_list`, + `delimited`, `gen_for`/`gen_case`/`gen_block`, `typedef`, `connection`, + `sens_list`, `timing_control`, `for_step` — all structural descents. + `binary_chain`'s inner `walk` recurses down the left spine of one + same-precedence operator chain, again a strict descent. + `gen_if` is *iterative* over `else if` chains (a `while` loop), so it is + strictly shallower than the parser was. +- No formatter path synthesizes nesting: nothing wraps a node in a + variable number of `Group`/`Indent` layers, and `binary_chain` and + `gen_if` actively flatten. The `Doc` tree is therefore a constant factor + deeper than the AST, not more. +- `printer.rs`: `print` and `fits` are iterative — explicit work stacks, not + recursion. `contains_hard_line` is recursive over the `Doc` tree, i.e. + bounded by that same constant factor. The implicit recursive `Drop` of the + AST (`Box`/`Box` chains) and of the `Doc` tree is bounded the + same way. + +The measured numbers back the argument up: both peak-stack tables above are +for `format_source`, i.e. parse + doc build + print + the verification +re-parse and re-format, and `crates/vlog_formatter/tests/deep_nesting.rs` +formats trees at *exactly* the maximum legal depth and the maximum legal +chain length and checks they converge. Those tests also prove formatting does +not inflate depth — the output of a max-depth file re-parses inside +`format_source` without tripping either limit. + +## Handshakes + +- **Consumed from `vlog_parser`:** nothing new. `parse()` keeps its + signature; the limit shows up as a normal `ParseError`, so `vlog_formatter` + and `vfmt` report it through the paths they already had (`FormatError:: + Source` → `error: : parse error: …` → exit 2). +- **Promised to `vlog_formatter`:** AST depth on any path is bounded by + `vlog_parser::parser::MAX_NESTING_DEPTH + MAX_CHAIN_LENGTH` (both public, + so tests and any future consumer can reference them instead of hard-coding + 64 and 256). The formatter may keep its recursive walk as long as every + path is a structural descent and no public API accepts an externally built + AST. +- **Requirement on future `vlog_parser` work:** any new loop that wraps the + expression it has already built — the `Box::new(previous)` shape — must + charge `link()`, or it reopens exactly the hole QA found. Loops that push + into a `Vec` widen the tree instead and need nothing. +- **Request to TODO.md §3's parallel-file-processing item (rayon):** rayon + worker threads default to 2 MiB of stack, which is *not* enough to reach + the depth limit in a debug build (~3.9 MiB needed). Whoever lands + parallelism must set `ThreadPoolBuilder::stack_size(8 * 1024 * 1024)` or + larger, otherwise this feature's guarantee silently regresses to a crash. + Same applies to any future LSP server thread that parses. +- **Request to TODO.md §6's error-tolerant parsing mode:** recovery must not + reset `depth` while unwinding — it is decremented by `leave()` on the way + out of every gated frame, including error paths, and a sync-and-continue + recovery has to resume from the frame it recovered in. + +## Status / TODO + +- [x] Depth counter (`Parser::depth`) + `enter`/`leave` guard pair. +- [x] Gate the five self-recursive entry points (`parse_item`, `parse_stmt`, + `parse_gen_if`, `parse_ternary`, `parse_unary`); audit the rest. +- [x] `MAX_NESTING_DEPTH = 64` chosen from measured stack headroom in debug + *and* release builds; rationale recorded above. +- [x] Error message `nesting too deep (limit 64)` carries line:col like every + other parse error. +- [x] Formatter audit: bounded by the parser's limit, no gate added; + reasoning and evidence recorded above. +- [x] Parser unit tests: at limit / past limit, one per construct family. +- [x] Formatter tests (`tests/deep_nesting.rs`): max-legal depth formats and + converges; past-limit input surfaces as a parse error. +- [x] CLI test (`crates/vfmt/tests/cli.rs`): the cli-polish repro (150 levels) + exits 2, is left untouched, and files after it are still formatted. +- [x] `cargo test --workspace`, `cargo clippy --all-targets`, + `cargo fmt --check` all clean. + +From QA round 1 (2026-08-19): + +- [x] **Blocking:** chain-built AST (`a.b.b…`, `a::b…`, `a[0]…`, `a()…`, + `a++…`, `a + a…`, `a inside {…}…`) is bounded too — second counter, + `MAX_CHAIN_LENGTH = 256`, charged by `parse_postfix` and + `parse_binary`. QA's 1500-segment repro now exits 2 instead of + SIGABRT. +- [x] Re-audited every `Box::new` site in the parser for the same shape; the + two loops above were the only ones. +- [x] **Medium:** the release-discipline test now covers all five gates *and* + both link sites — verified by deleting each of the seven release + statements in turn and confirming a test fails each time (it did not + before: deleting `parse_unary`'s `leave()` used to pass). +- [x] **Low:** boundary prose now names the construction it counts (59 vs 62 + nested `begin` blocks differ only by what sits inside the innermost + one). +- [x] TODO.md §1 recursion-depth item re-checked after the fix. + +## Work log + +### 2026-08-19 — dev agent + +- Read CLAUDE.md, README.md, TODO.md §1 and the cli-polish QA log first. + Baseline: `cargo test --workspace` green (70 tests), `cargo fmt --check` + clean, `cargo clippy --all-targets` **silent** (the 4 warnings the + cli-polish QA log mentions have since been fixed) — so "keep clippy + silent" was the bar. +- **Measured before choosing anything.** Copied the workspace to the + scratchpad (never building probes inside the repo), added a `depth_probe` + example that runs `format_source` on generated deep inputs on a thread with + a settable stack size, and bisected two things: the deepest input that + survives a 2 MiB thread with no limit, and (after the limit landed) the + smallest stack that survives limit-tripping input. Both tables are above. + The first surprise was how expensive debug frames are — 15 levels of + `if…begin` exhaust 2 MiB — so I also instrumented per-function frame sizes + by printing the address of a local at each entry: `parse_keyword_stmt` + 50,528 B, `parse_keyword_item` 20,832 B, `parse_primary` 12,240 B, + `parse_stmt_kind` 6,480 B in debug. +- **Considered and rejected: splitting the giant `match` functions** to + shrink those frames. An experiment (extracting the `begin` arm of + `parse_keyword_stmt` into its own function) moved the frame only + 50,528 → 47,872 B, so the win is spread across ~25 arms and would take a + large, risky refactor of the parser — and it would *not* change the + conclusion, because even after it a debug test thread's 2 MiB still could + not reach a generous limit. Kept the parser as it is and spent the budget + on measuring instead. +- **Limit = 64**, from the debug worst case (~72 KiB per level → ~3.9 MiB + peak) against the 8 MiB main-thread stack. 128 was the suggested starting + point but measures at ~7.9 MiB in debug, which would leave the debug-binary + CLI test overflowing before the guard fired — the exact failure this + feature exists to remove. +- Guard shape: `enter()?` / `leave()` around a renamed `*_inner` body. An + RAII guard would have to hold `&mut Parser` and would then block every + `self.` call inside the function body; a closure-taking helper would force + rewriting each body around a `|p|` parameter. The wrapper keeps the grammar + functions untouched and reads top-to-bottom, which matches the file's + style. +- Gated `parse_ternary` rather than the public `parse_expr` (which just + delegates to it) because the `? :` else-chain recurses into `parse_ternary` + directly; same reason `parse_unary` and `parse_gen_if` are gated + individually — both have direct self-recursion that bypasses their usual + entry point. +- Verified every gated family end-to-end with the **real debug binary** on 16 + adversarial files (200–400 levels of parens, unary, ternary, concat, calls, + assignment patterns, dims, statements, `else if`, fork, case, generate + `if`/`for`/`else if`, task bodies): all 16 now report + `parse error: L:C: nesting too deep (limit 64)` and exit 2 — no crashes, + no `SIGABRT`, no missing summary. Confirmed the boundary is exact by + bisecting with the binary: 59 nested `begin` blocks format, 60 error; 30 + nested parens format, 31 error. +- The scratchpad copy and probe binaries were used only for measurement and + live outside the repo; nothing generated by them was committed. + +**Results:** `cargo test --workspace` **80 passed, 0 failed** (up from 70: ++6 `vlog_parser` unit, +3 `vlog_formatter` `deep_nesting`, +1 `vfmt` CLI). +`cargo clippy --all-targets` silent. `cargo fmt --check` clean. +Files touched: `crates/vlog_parser/src/parser.rs`, +`crates/vlog_formatter/tests/deep_nesting.rs` (new), +`crates/vfmt/tests/cli.rs` (one test), `TODO.md` (one checkbox), this README. + +### 2026-08-19 (later) — dev agent, answering QA round 1 + +- **The blocking finding is correct and was reproduced first thing**: + `./target/debug/vfmt` on `assign x = a` + `.b`×1500 died with SIGABRT + (exit 134). Bisected the crash with the real binary before touching + anything, and swept the whole shape class rather than just the reported + one — crash thresholds on the default 8 MiB main-thread stack, debug: + `a.b…` / `a[0]…` / `a++…` **1392 segments** (2.8 KB file), `a inside {1}…` + 1392, `a+a…` in a dimension **5824**, `a + a…` in an expression **40448**. + So the hole was wider than member chains: every loop that wraps what it + has already built. +- **Root cause, stated precisely:** the five gates bound *parser recursion*, + and the audit's premise was *AST depth*. Those coincide only when every + layer of tree costs a parser frame. `parse_postfix` and `parse_binary` + build layers in a loop, so they broke the premise; the formatter, which + recurses per layer, was the thing that actually died. Re-derived the + invariant in the new section at the top of this README so the premise is + stated where it can be checked, not left implicit. +- **Fix: a second path-accumulated counter** (`links`, `MAX_CHAIN_LENGTH`) + charged per postfix segment and per binary/`inside` operator, released by + restoring the count the chain started from. Considered and rejected two + alternatives: (a) charging chain links against `MAX_NESTING_DEPTH`, which + is what "reuse the same limit" would mean — it caps flat operator chains + at ~60 terms, so a 64-bit parity XOR or a 128-term generated sum would + start failing to parse, a real acceptance regression; (b) making the + formatter's `binary_chain::walk` and `expr_compact` iterative instead — + that fixes two call sites but leaves AST depth itself unbounded (the + recursive `Drop` of a deep `Box` chain would still abort), i.e. it treats + a symptom. The counter restores the invariant for every consumer at once. +- **Restore-by-assignment, not decrement**, because a chain's length is not + known in advance and early `?` returns are everywhere; `self.links = + outer_links` is correct on every path and makes nesting compose properly — + an inner chain stacks on the outer one (so `a.b…(a.b…(…))` cannot multiply + the budget) while siblings each start fresh. Both properties have tests. +- **Re-audited the parser for the same shape** by listing every `Box::new` + site (38 of them) and checking which sit inside a loop: only the six in + `parse_postfix` and the two in `parse_binary`. Everything else boxes once + per gated recursive call, and the list-building loops collect into `Vec`s, + which widen the tree rather than deepening it. Recorded as a requirement + on future parser work in Handshakes. +- **Chose 256 by measuring, again** (new "Why 256 for chains" table). + Because deep statements peak during parsing and long chains during + formatting, the chain budget does not add to the global worst case: + 3895 KiB with a maximal chain inside maximal nesting versus 3959 KiB for + nesting alone. So the constant was chosen for acceptance, not stack: + 256 covers a 256-term generated sum. +- **QA's medium finding fixed and verified the way QA found it**: rewrote + the release-discipline test around a unit that exercises every gate and + both chain sites, then deleted each of the seven release statements in + turn and re-ran `cargo test -p vlog_parser`. Before: 0 of 7 caught for + `parse_unary` (QA's example). Now: 7 of 7 caught. The last one to fall was + `parse_postfix`'s restore, which `parse_binary`'s restore masks — it only + shows up on sibling chains *inside one expression*, so the test now has + `a.b×200 + c.d×200` (legal at 200 each, over budget if they accumulate). +- **QA's low finding fixed**: the boundary prose is now a table that names + each construction, including both `begin` shapes (62/63 empty, 59/60 with + a statement inside) and which test uses which. +- Re-ran the full adversarial sweep with the real debug binary on 15 files + (all chain families at 1500, nested-index and nested-call chains, a chain + inside 200 nested `begin`s, nested assignment patterns) — every one exits + 2 with a clean `nesting too deep` or `expression chain too long`, none + crash. Batch survival re-checked with QA's exact repro in a 3-file + directory: `2 files reformatted, 1 file failed to format`, exit 2, the + chain file byte-identical. Legal maxima still format: a 128-term wide sum, + 10,000 sequential statements, and 59 nested `begin`s holding a 250-link + chain. + +**Results:** `cargo test --workspace` **86 passed, 0 failed** (up from 80: ++4 `vlog_parser` unit, +1 `vlog_formatter` `deep_nesting`; the CLI batch test +grew a second pathological file). `cargo clippy --all-targets` silent. +`cargo fmt --check` clean. Same files touched as the first round. + +## QA log + +### 2026-08-19 — QA agent + +**Tooling results (verbatim):** +- `cargo test --workspace`: **80 passed, 0 failed** (8 test binaries: 18 + + 13 + 3 + 1 + 3 + 2 + 19 + 21, doc-tests 0 + 0). Matches the claimed count + exactly. +- `cargo clippy --all-targets`: silent, no warnings. +- `cargo fmt --check`: clean, exit 0. + +**Claim 4 (150-level repro, batch survival) — CONFIRMED**, checked two ways: +- `cargo test -p vfmt deeply_nested_file_does_not_kill_the_batch` passes. +- Independently, ran the real debug `vfmt` binary (not the test harness) on + a 3-file batch (`good`, 150-level `if…begin` repro, `good`) in the + scratchpad: exit 2, `error: b_deep.sv: parse error: 32:5: nesting too deep + (limit 64) (found "clk")`, `2 files reformatted, 1 file failed to format`, + `b_deep.sv` byte-identical to the original, both `a_before.sv` and + `c_after.sv` reformatted. Exactly as claimed, for this specific repro. + +**BLOCKING — an un-gated recursion cycle exists; it defeats the feature for +a whole class of input.** + +`parse_postfix` (`crates/vlog_parser/src/parser.rs:1854`) is a `while` +loop, not a gated recursive function, and the five gates guard *parser call +depth*, not *AST depth*. For every postfix chain the loop builds +iteratively — member access (`.name`), scope resolution (`::name`), index +(`[expr]`), and a call with no arguments (`()`) — each additional segment +costs the parser **zero** depth (`enter`/`leave` never fire for the chain +itself; only a bracket's *contents* go through the gate, and those contents +return to baseline before the loop's next iteration). The loop instead +builds `Expr::Member{base: Box, ..}` /`Index`/`Scope`/`Call` one layer +deeper per segment, so **the AST it produces is exactly as deep as the +input, with no limit at all.** + +`vlog_formatter`'s `Fmt::expr` (`crates/vlog_formatter/src/format.rs:1460`) +then recurses structurally into that AST — `Expr::Member => concat(vec![ +self.expr(base), ...])` and the same pattern for `Index`/`Scope`/`Call`/ +`Postfix` (lines 1479–1494, 1546) — so formatting one of these chains +recurses once per input segment, unbounded by `MAX_NESTING_DEPTH`. This +falsifies the Handshakes promise ("AST depth is bounded by +`MAX_NESTING_DEPTH`") and the formatter-audit conclusion in this same +README: the audit's premise ("every recursive path descends into a child +node ... bounded by AST depth, which the parser now bounds") is true as an +implication but the antecedent is false for chain-built AST, so the +conclusion doesn't hold. + +Confirmed with the real debug binary, not just a probe: + +``` +python3 -c " +n = 1500 +s = 'module m;\nassign x = a' + '.b'*n + ';\nendmodule\n' +open('member_chain_1500.sv','w').write(s)" +./target/debug/vfmt member_chain_1500.sv +# thread 'main' (NNNN) has overflowed its stack +# fatal runtime error: stack overflow, aborting +# exit code 134 (SIGABRT) +``` + +A 3 KiB file, ~1500 `.b` segments (`a.b.b.b...`), crashes on the default +8 MiB main-thread stack — no artificial thread-size trick needed, well +within a plausible generated-code size. Bisected the crash threshold at +n=8, stack=8 MiB: fails between n=1200 (OK) and n=1400 (crash); same order +of magnitude for `::name` scope chains, `[0]` index chains, and `()` empty +call chains (all confirmed crashing at n=1500 with `Fmt::expr` on the +call stack — `parse_source` alone survives to n≥3000 on the same stack, so +the formatter's recursion is the earlier failure point, not the parser's +Drop glue). `f(g(h(...)))` (nested *non-empty* calls) and `(((...)))` +(nested parens) are **not** part of this hole — those go through +`parse_expr` for each level and are correctly gated. + +**Reproduces the original bug this feature exists to fix**, via batch +processing: 3-file batch (`good`, `a.b.b...` ×1500, `good`) through the +debug CLI aborts with SIGABRT (exit 134, no exit-2 summary), the file +*before* the crash was already applied in place, and the file *after* it +was never reached — the exact "mid-batch death, uncatchable by +`catch_unwind`" failure the Goal section describes. + +This directly falsifies **claim 1** ("every unbounded recursion cycle +passes through one of the five gates") as stated: the cycle exists in the +*formatter*, seeded by an un-gated *parser* loop, and no gate anywhere +sees it. Recommend gating either `parse_postfix`'s loop (cap the chain +length, or route it through `enter`/`leave` per segment) or the +formatter's `expr` recursion directly (an explicit depth counter or an +iterative work-stack, matching how `printer.rs` already avoids recursion). +The five *parser-recursion* gates are otherwise sound — see below — this is +specifically an AST-shape gap the current design doesn't cover. + +**Independent gate-coverage audit (parser call graph) — otherwise sound.** +Traced every function in `parser.rs` that calls back into item/stmt/expr +parsing. `parse_binary` is genuinely self-bounded (confirmed by reading the +precedence-climbing logic: same-precedence operators loop in the *same* +frame via `while`, only a strictly higher-precedence RHS recurses, capped +at 11 levels). All list/loop functions (`parse_dims`, `parse_declarators`, +`parse_expr_list`, `parse_connections`, `parse_tf_body`, +`parse_source_file`, and the postfix loop discussed above) are iterative +and only recurse *into* a gated function per iteration — with the one +exception above, where the "into" is actually "next to" (AST-building +without a parser call). Tried and confirmed correctly gated (clean +`nesting too deep` error, no crash, at 200–400 levels): nested assignment +patterns (`'{a: '{a: ...}}`), nested replications (`{2{{2{...}}}}`), +stacked casts (`int'(int'(...))`), event-expression nesting +(`@((((posedge clk)))`), alternating concat/ternary +(`{{{1}?1:0,1}?1:0,...}`), and dimension-expression nesting +(`[a[a[a[...]]]]`). Hierarchical names (`a.b.c...`) are, per the task's +question, confirmed **iterative** — which is exactly the problem, not a +mitigation, per the blocking finding above. + +**leave() discipline — code is correct, but the "sibling-nesting" test's +claimed coverage is overstated.** All five gated wrappers use the same +`enter()?; let out = …_inner(); leave(); out` shape, which — read +carefully — cannot leak: `leave()` runs unconditionally once `enter()` +succeeds, with no `?` between them, on every path including +`parse_X_inner`'s internal errors. So there is no live leak in the shipped +code. + +Empirically tested the claim that `depth_is_released_on_the_way_out` +"would catch a missing `leave()`" (`crates/vlog_parser/src/parser.rs`, +in `mod tests`): temporarily deleted `self.leave();` from `parse_unary` +(reverted afterward via `git diff` — repo now shows the original 195 +insertions / 2 deletions again, confirmed clean), reran +`cargo test -p vlog_parser`. **All 21 tests still passed, including +`depth_is_released_on_the_way_out`.** The sibling test's 200×40 nested +`begin`/`end` blocks contain no expressions and no generate constructs, so +it only exercises `parse_item`/`parse_stmt`; a missing `leave()` in +`parse_ternary`, `parse_unary`, or `parse_gen_if` would sail through +undetected by any committed test. Suggest either broadening that test to +include repeated sibling expressions/generates, or narrowing the Status/ +TODO claim to "catches a leak in the statement-nesting gates." + +Separately confirmed the general (non-adversarial) case: a file with +10,000 sequential (non-nested, depth-1) statements parses and formats +fine (`1 file reformatted`, exit 0) — no depth accumulation across +siblings for the common case. + +**Boundary numbers — both exact, but the README's prose number doesn't +match what the committed unit test encodes.** Verified with the real +debug binary, cleanly bisected: +- Parens: **30 nested `(...)` format, 31 error** — matches the README + exactly, and matches `vlog_formatter/tests/deep_nesting.rs`'s + `nested_parens(MAX_NESTING_DEPTH/2 - 2)` = 30. Arithmetic checks out: + each paren level costs 2 gate-entries (`parse_ternary` discovers the + `(`, recurses into a fresh `parse_expr` → `parse_ternary`+`parse_unary` + for the contents), plus a fixed 2-deep baseline (module item + assign + item), so `2·(d+1) + 2 ≤ 64 ⇒ d ≤ 30`. Exact. +- Begin blocks: the README's "Why not smaller" prose says **"59 nested + `begin` blocks"**; I get exactly **59 OK / 60 error** too, *but only + when there's a real statement inside the innermost block* + (`x <= 1;` — this costs 2 more gate-entries, since parsing "1" itself + enters `parse_ternary`+`parse_unary`). The parser's own committed unit + tests (`nesting_just_below_the_limit_parses` / + `..._past_the_limit_is_a_parse_error`) use `nested_begins()`, which has + an **empty** innermost block (no statement at all), and that + construction's real boundary is **62 OK / 63 error** — confirmed by + running both `begin62.sv`/`begin63.sv` and `begin59.sv`/`begin60.sv` + through the debug binary directly. Both pairs of numbers are internally + consistent with the code (verified the arithmetic: `n + 2 ≤ 64` for the + empty-block case, `n + 5 ≤ 64` for the case with a statement), but the + README states "59" as *the* boundary without saying which construction + it's measuring, and it doesn't match what the shipped test actually + checks (62/63). Not a code bug — a documentation-precision gap that + could mislead whoever next tunes `MAX_NESTING_DEPTH`. Left as-is (not a + "small unambiguous fix" — the dev should pick one canonical + construction and re-measure/re-word intentionally, this isn't mine to + arbitrate). + +**16 MiB test-thread trick — confirmed necessary and correctly confined.** +Verified with a stack-size probe: parsing *and merely dropping* (no +formatting at all) the worst-case family (nested `begin`/statement) at +its exact legal max depth (59, with a real statement inside) already +overflows a 2 MiB *and* a 1 MiB thread — confirming the README's claim +that Drop of a deep AST, not just the recursive format walk, needs the +generous stack. By contrast, the parens family at its legal max (30) +survives fine on a 2 MiB thread even through full `format_source` — so +the "worst family" ranking in the measurement table (statements > +generate > parens/concat > ternary/unary) checks out relative to each +other. Confirmed by grep that the stack-size tricks +(`std::thread::Builder::new().stack_size(16 * 1024 * 1024)`) appear only +in `#[cfg(test)]` code (`parser.rs`'s `mod tests`, +`vlog_formatter/tests/deep_nesting.rs`) — never in library or `main.rs` +code — and are documented inline at each call site. + +**Formatter audit spot check — the "structural descent" claim itself +holds** for genuinely-recursed AST (`format.rs`/`printer.rs` grepped for +direct self-recursion beyond a child argument: none found: `item`, `stmt`, +`expr`, `gen_if` — iterative — and friends all descend into a field of +their own argument). `printer.rs`'s `print`/`fits` are genuinely iterative +(explicit `Vec`-based work stack, confirmed by reading the loop); +`contains_hard_line` is the one recursive function there, over the `Doc` +tree, which inherits the same unbounded-depth problem as the blocking +finding for chain-built AST (a `Doc::Concat` chain as deep as the AST). The +audit's *method* is sound; its *conclusion* is undermined by the blocking +finding, because the premise ("AST depth is bounded") isn't actually true +for the AST shapes `parse_postfix` builds. + +**CLAUDE.md compliance:** +- `MAX_NESTING_DEPTH` is `pub`, documented with rationale + (`crates/vlog_parser/src/parser.rs:67-75`). Good. +- Error message carries `line:col` and names the limit + (`nesting too deep (limit 64)`) — actionable. Good. +- No `unwrap()`/`expect()`/`panic!` added in library code by this diff + (checked every line of the parser.rs diff outside `#[cfg(test)]` + — none). Good. +- No `Cargo.toml`/`Cargo.lock` changes — no new dependency. Good. +- README has all required sections (Goal, Assumptions, Handshakes, + Status/TODO, Work log, QA log, Review). Good. +- TODO.md checkbox: "Recursion-depth limit in the parser" is checked off. + Given the blocking finding above, this is **premature as a general + claim** — the specific repro that motivated the item (150 levels of + `if`/`begin`) is genuinely fixed, but "recursion-depth limit in the + parser" as a general guarantee against stack-overflow-by-nesting is not + yet true, since the formatter can still be crashed by parser-accepted + input. Flagging for the lead's judgment on whether to uncheck pending a + fix, or check with a caveat. + +**Severity summary:** +- **BLOCKING**: un-gated postfix-chain cycle (member/scope/index/empty-call) + lets the formatter stack-overflow on parser-accepted input; reproduces + the original mid-batch-death bug. See repro above. +- **Medium**: `depth_is_released_on_the_way_out`'s claimed coverage + ("would catch a missing `leave()`") is overstated — empirically verified + it does not catch a leak in `parse_unary`/`parse_ternary`/`parse_gen_if`. +- **Low**: README's "59 nested begin blocks" prose doesn't match the + boundary the committed unit test actually encodes (62/63) — both numbers + are correct for their own (different, undisclosed) input shape. +- No findings on: tool results (all clean, counts match exactly), + parser-recursion gate coverage for genuinely-recursive constructs, the + 16 MiB test-thread rationale, `unwrap`/`expect` hygiene, new + dependencies, or README structure. + +No fixes applied to `crates/` — the blocking finding needs a design +decision (gate the postfix loop vs. gate the formatter's `expr` walk) +that's the dev agent's / lead's call, not a "small unambiguous fix." + +### 2026-08-19 (later) — QA agent, re-verification of the chain-budget fix + +**Tooling results (verbatim):** `cargo test --workspace`: **86 passed, 0 +failed** (8 binaries: 18 + 13 + 3 + 1 + 4 + 2 + 20 + 25, doc-tests 0 + 0) — +matches the dev's claimed count exactly, up 6 from round 1 (+2 parser unit, ++1 formatter `deep_nesting`, CLI batch test gained a second pathological +file so its own count is unchanged but its assertions grew). `cargo clippy +--all-targets`: silent. `cargo fmt --check`: clean, exit 0. + +**Job 1 — original blocking repros: CONFIRMED FIXED.** Rebuilt the debug +binary fresh (touched `parser.rs` to force a rebuild, confirmed via the +binary's mtime) and reran all four original crash shapes at n=1500 through +the real `vfmt`, default 8 MiB stack: + +``` +member1500.sv -> parse error: 2:525: expression chain too long (limit 256) (found ".") exit 2 +scope1500.sv -> parse error: 2:781: expression chain too long (limit 256) (found "::") exit 2 +index1500.sv -> parse error: 2:781: expression chain too long (limit 256) (found "[") exit 2 +emptycall1500.sv -> parse error: 2:525: expression chain too long (limit 256) (found "(") exit 2 +``` + +No SIGABRT, no artificial thread-size trick. Batch survival re-checked with +my exact original 3-file layout (`good`, `member1500.sv`, `good`): `2 files +reformatted, 1 file failed to format`, exit 2, `b_deep.sv` byte-identical to +the original, both the file before and the file after it were reformatted. +Also ran the dev's own new CLI test +(`deeply_nested_file_does_not_kill_the_batch`, now a 4-file batch combining +the 150-level statement repro *and* a 1500-segment chain in the same run): +passes. + +**Job 2 — tried to break the depth+links=320 invariant: no hole found.** +Worked the arithmetic first, then verified every case on the real debug +binary. The mechanism: `self.links` is one Parser-wide counter: `link()` +always checks and increments the *current* total (whatever's accumulated +from every not-yet-returned `parse_postfix`/`parse_binary` frame on the +current call stack), and each frame's own wrapper restores it to exactly +what it was when that frame was entered, on every return path (no `?` +between the inner call and the restore — same shape as `enter`/`leave`). +That makes `self.links` at any instant equal to the sum of links open *on +the current root-to-position path* — never per-subtree, never per-sibling — +so nested chains stack (additive) and sibling chains don't (independent +budgets), which is exactly what a recursive tree-walk's stack usage needs: +sibling subtrees are visited sequentially, so only one branch's depth is +ever live on the stack at once, and a single path's cost is `depth_used + +links_used`, never a product. `depth` and `links` are separate counters, so +there is no cross term at all — one budget being 64 and the other 256 +cannot become 64×256 because nothing ever multiplies them; they just both +have to stay under their own ceiling on the same path. + +Tried to defeat that empirically anyway, all on the real debug binary, +default stack, no crashes found — every case either formatted (within +budget) or errored cleanly citing the correct limit name: + +| construction | result | +|---|---| +| nested calls, each arg its own chain (`a.b×5(a.b×5(...×60 levels)))`) | correctly rejected — `nesting too deep` (60 nested call-args cost 120 depth via repeated fresh `parse_expr` entries, hits the depth ceiling before the ~360 combined links would) | +| same, milder (1–32 call levels × 10–300 links/level) | correctly rejected — `expression chain too long`, additive as predicted | +| 30 grouping parens wrapping one 256-link chain | **accepted** (286 total layers, under 320) — `parenswrap_30_256.sv` | +| 60 stacked `~` feeding a 250/256-link postfix chain | **accepted** — depth and links both independently near their ceiling, sum under 320 | +| `a inside {b inside {c inside {...}}}` , 100/128/129/130 deep | correctly rejected — `nesting too deep` (each level costs a fresh `parse_expr` = 2 depth; links stay near 1 because deeper levels self-restore before the current level's own `link()` fires) | +| `[a+a+a+...+a:0]` dimension binary chain | **256/257 terms accepted, 300/6000 rejected** with `expression chain too long` — down from the pre-fix 5824-term crash threshold reported in the dev's sweep; confirmed fixed, not just moved | +| postfix chain on a concat result (`{a}.b×n`) | 250 accepted, 260/300 rejected — gated the same regardless of what the primary was | +| postfix chain on a replication result (`{2{a}}.b×n`) | 250 accepted, 260 rejected — same | +| stacked casts `a'(a'(a'(...)))`, 60/300 deep | correctly rejected — `nesting too deep` (each cast's inner content is a fresh `parse_expr`, so this is depth-gated, not links-gated) | +| postfix `++` chain, 300 deep | correctly rejected — `expression chain too long` | +| 59 nested `begin` holding a 250- and a 256-link chain | both **accepted** — matches the dev's claimed combined worst case; 60 nested `begin` with a 250-link chain correctly rejected on depth before the chain is even reached | +| 109 KB file, 500 mixed constructs (chains, parens, unary, `inside`, wide sums), each individually within budget | **accepted**, no false positive, no crash | + +No construction pushed AST depth past what the two independent ceilings +allow, and nothing multiplied them. Claim 2 (the new invariant) holds under +adversarial pressure. + +**Job 3 — sabotage-verified 3 of the 7 release sites myself (not just +trusting the dev's 7/7 claim).** Picked `parse_unary`'s `leave()` (my own +round-1 finding — this one used to pass undetected), `parse_postfix`'s +`self.links = outer_links` restore, and one of `parse_binary`'s restore. +For each: deleted the release statement, ran `cargo test -p vlog_parser`, +recorded the failure, then restored the exact original line and reran to +confirm 25/25 pass again before moving to the next site. + +- `parse_unary` `leave()` deleted → **2 tests fail**: `long_chains_error` + and `depth_and_links_are_released_on_the_way_out` (both now trip + `nesting too deep` where they shouldn't). This is the one round 1 found + *undetected* — now caught, confirming the medium finding is fixed. +- `parse_postfix` restore deleted → **1 test fails**, and specifically the + right one: `depth_and_links_are_released_on_the_way_out` panics with + `"sibling chains in one expression must not accumulate links"` — i.e. the + `a.b×200 + c.d×200` assertion the dev's work log says was added because + it's the one case that catches this particular release site (a chain + that fully finishes and gets re-parsed as a fresh sibling wouldn't + expose it; two chains *within one expression* do). Verified the dev's + specific claim about which assertion matters, not just that some + assertion fails. +- `parse_binary` restore deleted → **1 test fails**, same test, this time + via a plain long binary chain (`+`) tripping the length check early. + +All three reverted by hand back to the exact original three lines (no +stray edits — confirmed via `grep -c "QA SABOTAGE" parser.rs` = 0 after +each revert and a full `cargo test -p vlog_parser` pass in between). Final +state: `git diff --stat crates/vlog_parser/src/parser.rs` shows the same +346 insertions / 6 deletions as before I started sabotaging, and all 25 +parser tests pass. I did not test the other 4 sites (`parse_item`, +`parse_stmt`, `parse_gen_if`, `parse_ternary` `leave()`s), but given the +3/3 result and that they share the exact same wrapper shape, I have no +reason to doubt the dev's 7/7 claim for the rest. + +**Job 4 — legal acceptance: no regression found.** All on the real debug +binary: a 128-term flat sum (`a0+a1+...+a127`) — accepted; a +realistic-looking RTL file (parameterized pipeline module, `generate for`, +`always_ff`, `case`) — accepted; the committed `small_cases` fixture suite +(~190 table-driven cases across `tests/cases/*.cases`) — all pass; 59 +nested `begin` holding a 250-link chain — accepted (see table above); 10,000 +sequential (non-nested) statements — accepted. No false positives. + +**Job 5 — boundary table spot-check: 3 of 5 rows checked, one is wrong.** +- Parens row (`30` OK / `31` errors): **matches exactly**, reconfirmed with + fresh files. +- `begin` + statement row (`59` OK / `60` errors): **matches exactly**. + Also reconfirmed the empty-`begin` row (`62`/`63`, used by the parser's + own boundary unit tests) for good measure — also matches. +- Generate-`if` row, claimed **"29 (30 errors)"**: **does not match.** + Measured `30` OK / `31` errors on the real binary, for both the natural + reading of the row (`if (1) begin ... end`, nested, innermost holding + `wire w;`) and the empty-innermost-block variant — both give the same + 30/31 boundary, not 29/30: + ``` + genif29.sv (29 levels) -> 1 file reformatted (exit 0) + genif30.sv (30 levels) -> 1 file reformatted (exit 0) + genif31.sv (31 levels) -> nesting too deep (limit 64) (exit 2) + ``` + This table row is off by one. Low severity — the underlying mechanism is + still correctly and safely bounded (nothing crashes either side of the + true boundary), it's the documented number that's wrong. No committed + test asserts this specific boundary (unlike the parens and `begin` rows, + which are pinned by `deep_nesting.rs`/the parser's own unit tests), which + is presumably how a manually-bisected number went stale or was + mistyped. Did not fix it myself — one-line table edit, but I'd rather + the dev re-bisect and confirm the exact construction they measured + matches what's in the table, same reasoning as round 1's begin-boundary + finding. + +**Job 6 — standard checks, all pass:** +- `MAX_CHAIN_LENGTH` is `pub`, documented with rationale (why 256, why + larger than `MAX_NESTING_DEPTH`, ~6 KiB/link vs ~62 KiB/statement) at + `crates/vlog_parser/src/parser.rs:77-94`. +- No `unwrap()`/`expect()`/`panic!` added in library code (checked every + line of the new diff outside `#[cfg(test)]`, including `link()` and both + new wrappers — none). +- `## The invariant` section is present near the top of this README, states + the bound precisely (`MAX_NESTING_DEPTH + MAX_CHAIN_LENGTH` = 320) and + explains why the two counters compose additively rather than + multiplicatively — this is the section job 2 above set out to break, and + couldn't. +- TODO.md §1's checkbox is `[x]` again, with the round-1-era "in progress, + QA found postfix chains unbounded" caveat text removed now that the gap + it described is closed. Given job 1/2's results, this is honest. +- `verify.rs` / `tests/verification.rs` changed since my first pass, per + the lead's note (unrelated committed lead fix, diagnostic escaping) — did + not investigate further, out of scope for this feature. +- Confirmed no changes outside `crates/`, `TODO.md`, and this README; + `tools/`, `corpus/`, and `docs/features/corpus-check/` untouched by me. + +**Verdict per fix:** +- **Blocking (round 1, postfix/binary chain-built AST unbounded): FIXED.** + Verified with the exact original repros plus 20+ new adversarial + combinations designed to defeat the additive-composition claim + specifically. No crash found anywhere. +- **Medium (round 1, `leave()`-leak test coverage overstated): FIXED.** + Sabotage-verified 3 of 7 sites myself; all 3 now caught (my own + `parse_unary` example included), where round 1 showed 0 of them were. +- **Low (round 1, begin-boundary prose ambiguity): FIXED** — replaced with + a table that names each construction; both begin rows reconfirmed exact. +- **New — Low (this round): generate-`if` boundary row states "29 (30 + errors)"; measured boundary is 30 OK / 31 errors.** Not blocking, not a + code defect — a stale/mistyped number in a table that has no committed + test pinning it. Repro above. + +No new BLOCKING finding. No code changes made this round (the one finding +is a documentation number, not something I judged a "small unambiguous +fix" worth touching without the dev confirming their construction). + +## Review + +**2026-08-19 — lead. Verdict: accepted and committed after one rejection +and a verified rework.** + +This feature is the best demonstration yet of why the dev/QA split +exists. Round 1 shipped a measurement-driven parser gate that was +genuinely good work — and still carried a fatal blind spot: bounding +*parser recursion* is not bounding *AST depth*, and the formatter dies +on the latter. QA earned its keep twice: first by finding the postfix +hole empirically (a 3 KiB crashing file), then by proving the leak test +didn't cover three of the five gates via sabotage. The rework earned the +acceptance: the dev widened QA's finding to `parse_binary`/`inside` +before touching code, chose the two-budget design for *acceptance* +reasons (a single budget would have rejected legal 128-term sums — +correctness includes not rejecting valid input), stated the invariant +precisely (path depth ≤ 64 + 256), and made the leak tests +sabotage-complete (7/7). Re-QA then attacked the additive-composition +claim directly — the one load-bearing piece of arithmetic — and it held. + +Points I reviewed and accept: + +1. **Restore-by-assignment over decrement** for the chain budget: right + call — it is correct on every `?` early-return path by construction, + where paired decrements have to be right at every exit. +2. **The 38-site `Box::new` audit** distinguishing depth-growing loops + (8 sites, all now charged) from width-growing `Vec` collectors: this + is the analysis round 1 should have had, and it is now a standing + Handshake requirement on future parser work. +3. **Limits as constants of the public API** (`MAX_NESTING_DEPTH`, + `MAX_CHAIN_LENGTH`, both pub and documented) with boundary numbers + tied to named constructions in the README table. +4. The lead corrected the one remaining nit (generate-if boundary row, + 29/30 → measured 30/31) directly in the table above. + +Standing handshakes reaffirmed for future rounds: rayon workers need +≥8 MiB stacks (TODO §3); error-tolerant parsing must not reset `depth` +or `links` during recovery (TODO §6); any new parser loop that boxes a +base expression per iteration must charge the chain budget.