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]>
297 lines
11 KiB
Rust
297 lines
11 KiB
Rust
//! End-to-end tests that drive the real `vfmt` binary.
|
|
//!
|
|
//! Fixtures use the most trivial Verilog possible so these tests stay
|
|
//! stable while the formatter's layout rules evolve.
|
|
|
|
use std::io::Write;
|
|
use std::path::PathBuf;
|
|
use std::process::{Command, Output, Stdio};
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
|
|
const VFMT: &str = env!("CARGO_BIN_EXE_vfmt");
|
|
/// Formats to `FORMATTED`: the only change is the newline before `endmodule`.
|
|
const UNFORMATTED: &str = "module m;endmodule\n";
|
|
const FORMATTED: &str = "module m;\nendmodule\n";
|
|
/// Truncated header — the parser cannot recover from this.
|
|
const UNPARSEABLE: &str = "module\n";
|
|
|
|
/// A throwaway directory under the system temp dir, removed on drop.
|
|
struct TempDir {
|
|
path: PathBuf,
|
|
}
|
|
|
|
impl TempDir {
|
|
fn new(tag: &str) -> TempDir {
|
|
static COUNTER: AtomicUsize = AtomicUsize::new(0);
|
|
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
|
|
let path = std::env::temp_dir().join(format!("vfmt-cli-{}-{tag}-{n}", std::process::id()));
|
|
let _ = std::fs::remove_dir_all(&path);
|
|
std::fs::create_dir_all(&path).expect("create temp dir");
|
|
TempDir { path }
|
|
}
|
|
|
|
fn write(&self, rel: &str, contents: &str) -> String {
|
|
let path = self.path.join(rel);
|
|
if let Some(parent) = path.parent() {
|
|
std::fs::create_dir_all(parent).expect("create parent dir");
|
|
}
|
|
std::fs::write(&path, contents).expect("write fixture");
|
|
path.to_string_lossy().into_owned()
|
|
}
|
|
|
|
fn read(&self, rel: &str) -> String {
|
|
std::fs::read_to_string(self.path.join(rel)).expect("read fixture")
|
|
}
|
|
|
|
fn root(&self) -> String {
|
|
self.path.to_string_lossy().into_owned()
|
|
}
|
|
}
|
|
|
|
impl Drop for TempDir {
|
|
fn drop(&mut self) {
|
|
let _ = std::fs::remove_dir_all(&self.path);
|
|
}
|
|
}
|
|
|
|
fn run(args: &[&str]) -> Output {
|
|
Command::new(VFMT).args(args).output().expect("run vfmt")
|
|
}
|
|
|
|
fn run_with_stdin(args: &[&str], input: &str) -> Output {
|
|
let mut child = Command::new(VFMT)
|
|
.args(args)
|
|
.stdin(Stdio::piped())
|
|
.stdout(Stdio::piped())
|
|
.stderr(Stdio::piped())
|
|
.spawn()
|
|
.expect("spawn vfmt");
|
|
child.stdin.as_mut().expect("stdin").write_all(input.as_bytes()).expect("write stdin");
|
|
child.wait_with_output().expect("run vfmt")
|
|
}
|
|
|
|
fn code(out: &Output) -> i32 {
|
|
out.status.code().expect("exit code")
|
|
}
|
|
|
|
fn stdout(out: &Output) -> String {
|
|
String::from_utf8_lossy(&out.stdout).into_owned()
|
|
}
|
|
|
|
fn stderr(out: &Output) -> String {
|
|
String::from_utf8_lossy(&out.stderr).into_owned()
|
|
}
|
|
|
|
#[test]
|
|
fn formats_files_in_place() {
|
|
let dir = TempDir::new("inplace");
|
|
dir.write("a.sv", UNFORMATTED);
|
|
dir.write("nested/b.v", UNFORMATTED);
|
|
dir.write("notes.txt", "not verilog\n");
|
|
|
|
let out = run(&[&dir.root()]);
|
|
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
|
assert_eq!(dir.read("a.sv"), FORMATTED);
|
|
assert_eq!(dir.read("nested/b.v"), FORMATTED);
|
|
assert_eq!(dir.read("notes.txt"), "not verilog\n", "non-Verilog files are not touched");
|
|
assert!(stderr(&out).contains("2 files reformatted"), "{}", stderr(&out));
|
|
|
|
// Second run is a no-op: nothing left to change.
|
|
let out = run(&[&dir.root()]);
|
|
assert_eq!(code(&out), 0);
|
|
assert!(stderr(&out).contains("2 files left unchanged"), "{}", stderr(&out));
|
|
}
|
|
|
|
#[test]
|
|
fn check_reports_without_writing() {
|
|
let dir = TempDir::new("check");
|
|
let path = dir.write("a.sv", UNFORMATTED);
|
|
|
|
let out = run(&["--check", &path]);
|
|
assert_eq!(code(&out), 1, "would-change must exit 1");
|
|
assert!(stdout(&out).contains("would reformat:"), "{}", stdout(&out));
|
|
assert_eq!(dir.read("a.sv"), UNFORMATTED, "--check must not write");
|
|
|
|
dir.write("a.sv", FORMATTED);
|
|
let out = run(&["--check", &path]);
|
|
assert_eq!(code(&out), 0, "nothing to change must exit 0");
|
|
assert_eq!(stdout(&out), "");
|
|
}
|
|
|
|
#[test]
|
|
fn diff_prints_a_unified_diff_without_writing() {
|
|
let dir = TempDir::new("diff");
|
|
let path = dir.write("a.sv", UNFORMATTED);
|
|
|
|
let out = run(&["--diff", &path]);
|
|
assert_eq!(code(&out), 1, "would-change must exit 1");
|
|
assert_eq!(dir.read("a.sv"), UNFORMATTED, "--diff must not write");
|
|
|
|
let text = stdout(&out);
|
|
let lines: Vec<&str> = text.lines().collect();
|
|
assert_eq!(lines[0], format!("--- {path}"), "{text}");
|
|
assert_eq!(lines[1], format!("+++ {path}"), "{text}");
|
|
assert!(lines[2].starts_with("@@ ") && lines[2].ends_with(" @@"), "{text}");
|
|
assert!(lines.contains(&"-module m;endmodule"), "{text}");
|
|
assert!(lines.contains(&"+module m;"), "{text}");
|
|
assert!(lines.contains(&"+endmodule"), "{text}");
|
|
// The summary goes to stderr so stdout is a clean patch.
|
|
assert!(stderr(&out).contains("would be reformatted"), "{}", stderr(&out));
|
|
|
|
dir.write("a.sv", FORMATTED);
|
|
let out = run(&["--diff", &path]);
|
|
assert_eq!(code(&out), 0);
|
|
assert_eq!(stdout(&out), "", "an unchanged file prints no diff");
|
|
}
|
|
|
|
#[test]
|
|
fn diff_conflicts_with_stdout() {
|
|
let dir = TempDir::new("diffconflict");
|
|
let path = dir.write("a.sv", UNFORMATTED);
|
|
let out = run(&["--diff", "--stdout", &path]);
|
|
assert_eq!(code(&out), 2);
|
|
assert!(stderr(&out).contains("--diff cannot be combined with --stdout"), "{}", stderr(&out));
|
|
}
|
|
|
|
#[test]
|
|
fn stdin_mode_uses_stdin_filename_in_errors() {
|
|
let out = run_with_stdin(&["-"], UNPARSEABLE);
|
|
assert_eq!(code(&out), 2);
|
|
assert!(stderr(&out).starts_with("error: <stdin>: "), "{}", stderr(&out));
|
|
|
|
let out = run_with_stdin(&["--stdin-filename", "rtl/top.sv", "-"], UNPARSEABLE);
|
|
assert_eq!(code(&out), 2);
|
|
assert!(stderr(&out).starts_with("error: rtl/top.sv: "), "{}", stderr(&out));
|
|
assert!(!stderr(&out).contains("<stdin>"), "{}", stderr(&out));
|
|
assert!(!std::path::Path::new("rtl/top.sv").exists(), "--stdin-filename must not touch disk");
|
|
|
|
// It also names the buffer in --diff and --check output.
|
|
let out = run_with_stdin(&["--diff", "--stdin-filename", "rtl/top.sv", "-"], UNFORMATTED);
|
|
assert_eq!(code(&out), 1);
|
|
assert!(stdout(&out).starts_with("--- rtl/top.sv\n+++ rtl/top.sv\n"), "{}", stdout(&out));
|
|
|
|
let out = run_with_stdin(&["--check", "--stdin-filename", "rtl/top.sv", "-"], UNFORMATTED);
|
|
assert_eq!(code(&out), 1);
|
|
assert_eq!(stdout(&out), "would reformat: rtl/top.sv\n");
|
|
}
|
|
|
|
#[test]
|
|
fn stdin_mode_formats_to_stdout() {
|
|
let out = run_with_stdin(&["-"], UNFORMATTED);
|
|
assert_eq!(code(&out), 0);
|
|
assert_eq!(stdout(&out), FORMATTED);
|
|
}
|
|
|
|
#[test]
|
|
fn exclude_skips_files_and_directories() {
|
|
let dir = TempDir::new("exclude");
|
|
dir.write("keep.sv", UNFORMATTED);
|
|
dir.write("skip_gen.sv", UNFORMATTED);
|
|
dir.write("build/inner.sv", UNFORMATTED);
|
|
dir.write("sub/keep.sv", UNFORMATTED);
|
|
|
|
let out = run(&["--exclude", "*_gen.sv", "--exclude", "build", &dir.root()]);
|
|
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
|
assert_eq!(dir.read("keep.sv"), FORMATTED);
|
|
assert_eq!(dir.read("sub/keep.sv"), FORMATTED);
|
|
assert_eq!(dir.read("skip_gen.sv"), UNFORMATTED, "name glob must be excluded");
|
|
assert_eq!(dir.read("build/inner.sv"), UNFORMATTED, "excluded dir is not descended into");
|
|
assert!(stderr(&out).contains("2 files reformatted"), "{}", stderr(&out));
|
|
}
|
|
|
|
#[test]
|
|
fn exclude_matches_a_path_suffix_when_it_contains_a_slash() {
|
|
let dir = TempDir::new("excludepath");
|
|
dir.write("gen/rtl/a.sv", UNFORMATTED);
|
|
dir.write("gen/hand/b.sv", UNFORMATTED);
|
|
|
|
let out = run(&["--exclude", "gen/rtl", &dir.root()]);
|
|
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
|
assert_eq!(dir.read("gen/rtl/a.sv"), UNFORMATTED);
|
|
assert_eq!(dir.read("gen/hand/b.sv"), FORMATTED);
|
|
}
|
|
|
|
#[test]
|
|
fn exclude_does_not_apply_to_explicitly_named_files() {
|
|
let dir = TempDir::new("excludeexplicit");
|
|
let path = dir.write("skip_gen.sv", UNFORMATTED);
|
|
|
|
let out = run(&["--exclude", "*_gen.sv", &path]);
|
|
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
|
assert_eq!(dir.read("skip_gen.sv"), FORMATTED);
|
|
}
|
|
|
|
#[test]
|
|
fn unformattable_file_exits_2_and_is_left_untouched() {
|
|
let dir = TempDir::new("badparse");
|
|
dir.write("bad.sv", UNPARSEABLE);
|
|
dir.write("good.sv", UNFORMATTED);
|
|
|
|
let out = run(&[&dir.root()]);
|
|
assert_eq!(code(&out), 2, "an error must exit 2");
|
|
assert_eq!(dir.read("bad.sv"), UNPARSEABLE, "a file that fails to format is not rewritten");
|
|
assert_eq!(dir.read("good.sv"), FORMATTED, "other files are still formatted");
|
|
let err = stderr(&out);
|
|
assert!(err.contains("bad.sv: parse error"), "{err}");
|
|
assert!(err.contains("1 file failed to format"), "{err}");
|
|
|
|
// An error outranks "would reformat" in --check and --diff too.
|
|
dir.write("good.sv", UNFORMATTED);
|
|
assert_eq!(code(&run(&["--check", &dir.root()])), 2);
|
|
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");
|
|
assert_eq!(code(&run(&["--nope", "x.sv"])), 2, "unknown option");
|
|
assert_eq!(code(&run(&["--exclude"])), 2, "missing option value");
|
|
assert_eq!(code(&run(&["/definitely/not/here.sv"])), 2, "missing input file");
|
|
}
|
|
|
|
#[test]
|
|
fn help_documents_the_exit_codes() {
|
|
let out = run(&["--help"]);
|
|
assert_eq!(code(&out), 0);
|
|
let text = stdout(&out);
|
|
assert!(text.contains("EXIT CODES:"), "{text}");
|
|
for flag in ["--check", "--diff", "--exclude", "--stdin-filename"] {
|
|
assert!(text.contains(flag), "help is missing {flag}");
|
|
}
|
|
}
|