Files
lucisv/crates/vlog_formatter/tests/deep_nesting.rs
T
lucioandClaude Fable 5 a49131fc5f Add recursion-limit: bounded parser depth and AST chain length
Two budgets, both measured rather than guessed: MAX_NESTING_DEPTH=64
gates the five recursion cycles in the parser (debug frames run to
~50KB; 64 peaks at ~3.9MiB against the 8MiB stack), and
MAX_CHAIN_LENGTH=256 charges postfix segments and binary/inside
operators, whose loops deepen the AST without parser recursion.
Restore-by-assignment makes the chain budget correct on every early
return. Invariant: AST depth on any root-to-leaf path <= 64+256,
so the formatter's structural recursion is bounded too.

Deep or chain-heavy inputs now get a clean "nesting too deep" /
"expression chain too long" parse error with position, exit 2, batch
unaffected -- replacing an uncatchable stack-overflow abort that
killed whole runs (3KiB of a.b.b... sufficed before).

Round 1 was rejected in review: QA found postfix chains ungated and
the leak test unable to detect missing releases (proven by sabotage).
The rework widened the finding to binary/inside chains, added the
second budget, and made leak tests sabotage-complete (7/7); re-QA
attacked the additive-composition invariant and found no hole, with
no acceptance regressions (128-term sums, 10k statements still fine).

Dev + rework: Opus agent; QA + re-QA: Sonnet agent; full history in
docs/features/recursion-limit/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-19 01:20:38 -07:00

87 lines
3.4 KiB
Rust

//! 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<String, FormatError> {
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:?}"),
}
}
}