Files
lucisv/crates/vlog_formatter/tests/verification.rs
T
lucioandClaude Fable 5 003e0766e9 Add alignment inference and the format cache (round 17)
alignment: Verible-style alignment-intent inference for ANSI ports
(name column), named connections (paren column) and parameter items
(name and = columns). A group aligns iff the author asked: >=4
excess spaces somewhere, or the group already sits consistently at
one column -- single-space code keeps today's bytes exactly (zero
churn across all 397 pre-existing cases; corpus outcome TSV
byte-identical while 291/578 formattable files change content).
Fixed-point by construction: aligned output re-infers the same
targets, flush re-infers flush; the whole verdict is decided at
document-build time (a printer-side split diverged ibex_core.sv at
width 60 during development -- caught by a 2312-run config sweep and
redesigned). Groups break at comments/attributes/directives/blank
lines; a group that cannot fit falls back to flush whole, never
mixed. No lexer changes: name_span plus the source answers every
spacing question. QA's sabotage confirmed the runtime convergence
check catches the predicted flip-flop even with the unit test gone.

format-cache: warm runs skip verified-clean files. Key = (FNV-1a 64
content hash, resolved config values, vfmt version), path-keyed;
only the fixed-point verdict is ever cached, so --check/--diff can
never go stale and a hit can only skip work, never produce output.
One atomic text file in self-gitignoring .vfmt_cache/; --no-cache /
--cache-dir; 8-process concurrency clean. Warm corpus check: 2x at
default threads, 7.7x single-threaded.

655 workspace tests. Dev: 2 Opus agents (both isolated their gates
from the other's churn via HEAD-reverted scratchpad copies); QA: 2
Sonnet agents; reviews in docs/features/{alignment,format-cache}/
README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-19 14:42:07 -07:00

859 lines
37 KiB
Rust

//! Tests for the runtime safety net: token-stream equivalence, convergence,
//! and the failsafe behavior of `format_source`.
use vlog_formatter::{
format_source, verify_convergence, verify_equivalence, Config, FormatError, VerificationError,
};
fn expect_divergence(input: &str, output: &str) -> VerificationError {
match verify_equivalence(input, output) {
Ok(()) => panic!("expected a divergence between\n{input}\n---\n{output}"),
Err(e) => e,
}
}
#[test]
fn identical_streams_are_equivalent() {
let src = "module m;\n assign x = a & b;\nendmodule\n";
verify_equivalence(src, src).expect("a text is equivalent to itself");
}
#[test]
fn whitespace_only_differences_are_equivalent() {
let input = "module m(input a,output b);assign b=~a;endmodule";
let output = "module m (input a, output b);\n assign b = ~a;\nendmodule\n";
verify_equivalence(input, output).expect("whitespace is not part of the token stream");
}
#[test]
fn comments_are_part_of_the_stream_but_may_be_reindented() {
let input = "module m;\n// note\nwire x;/* block */\nendmodule\n";
let output = "module m;\n // note\n wire x; /* block */\nendmodule\n";
verify_equivalence(input, output).expect("comment text survived");
}
#[test]
fn multiline_block_comment_may_be_reindented() {
let input = "module m;\n/* one\n two\n three */\nwire x;\nendmodule\n";
let output = "module m;\n /* one\n two\n three */\n wire x;\nendmodule\n";
verify_equivalence(input, output).expect("only per-line indentation changed");
}
#[test]
fn multiline_macro_invocation_may_be_reindented() {
// A macro usage lexes as one identifier token holding the whole
// invocation, so re-indenting its continuation lines changes that token's
// text — exactly like a continued `define, and normalized the same way.
let input = "module m;\n`A(x,\n y)\nendmodule\n";
let output = "module m;\n `A(x,\n y)\nendmodule\n";
verify_equivalence(input, output).expect("only per-line indentation changed");
}
/// QA repro (2026-08-19): a string literal inside a macro argument that spans
/// physical lines. Its continuation line's leading whitespace is part of the
/// string's *value*, so re-indenting it corrupts the string — and a blind
/// per-line trim in `normalize` used to report the pair as equivalent, so
/// `vfmt` exited 0 and wrote the corrupted file. The net must reject this.
#[test]
fn reindented_string_inside_a_macro_argument_is_rejected() {
let input = "module m;\nif (X) begin : g\n`uvm_info(\"id\", \"line one\n line two\", UVM_LOW);\nend\nendmodule\n";
let output = "module m;\n if (X) begin : g\n `uvm_info(\"id\", \"line one\n line two\", UVM_LOW);\n end\nendmodule\n";
expect_divergence(input, output);
}
/// The same hole for a `` `define `` whose body carries a continued string,
/// and for an attribute — both are re-indented through the same path.
#[test]
fn reindented_string_inside_a_directive_or_attribute_is_rejected() {
let input =
"module m;\nif (X) begin : g\n`define MSG \"line one \\\n line two\"\nend\nendmodule\n";
let output = "module m;\n if (X) begin : g\n `define MSG \"line one \\\n line two\"\n end\nendmodule\n";
expect_divergence(input, output);
let input = "module m;\n(* note = \"line one\n line two\" *)\nwire w;\nendmodule\n";
let output = "module m;\n (* note = \"line one\n line two\" *)\n wire w;\nendmodule\n";
expect_divergence(input, output);
}
/// The whole point of the normalization survives the fix: a line break that is
/// *not* inside a string is still free to be re-indented.
#[test]
fn reindenting_outside_a_string_is_still_allowed() {
// The string ends on its own line, so the following break is layout.
let input = "module m;\n`A(\"msg\",\n x)\nendmodule\n";
let output = "module m;\n `A(\"msg\",\n x)\nendmodule\n";
verify_equivalence(input, output).expect("only per-line indentation changed");
// A quote written inside a comment must not be read as opening a string.
let input = "module m;\n`A(x, // it's a \"quote\n y)\nendmodule\n";
let output = "module m;\n `A(x, // it's a \"quote\n y)\nendmodule\n";
verify_equivalence(input, output).expect("a quote inside a comment opens nothing");
}
#[test]
fn a_changed_macro_argument_is_still_rejected() {
let input = "module m;\n `A(x,\n y)\nendmodule\n";
let output = "module m;\n `A(x,\n z)\nendmodule\n";
match expect_divergence(input, output) {
VerificationError::Divergence { expected, got, .. } => {
assert!(expected.expect("expected item").text.contains('y'));
assert!(got.expect("got item").text.contains('z'));
}
other => panic!("wrong error: {other}"),
}
}
#[test]
fn differing_token_is_rejected() {
let err = expect_divergence("assign x = a;\n", "assign x = b;\n");
match err {
VerificationError::Divergence { index, ref expected, ref got } => {
assert_eq!(index, 3);
assert_eq!(expected.as_ref().expect("expected item").text, "a");
assert_eq!(got.as_ref().expect("got item").text, "b");
}
other => panic!("wrong error: {other}"),
}
let rendered = err.to_string();
assert!(rendered.contains("index 3"), "{rendered}");
assert!(rendered.contains('a') && rendered.contains('b'), "{rendered}");
}
#[test]
fn dropped_comment_is_rejected() {
let input = "module m;\n // keep me\n wire x;\nendmodule\n";
let output = "module m;\n wire x;\nendmodule\n";
match expect_divergence(input, output) {
VerificationError::Divergence { expected, got, .. } => {
let expected = expected.expect("expected item");
assert_eq!(expected.text, "// keep me");
assert_eq!(got.expect("got item").text, "wire");
}
other => panic!("wrong error: {other}"),
}
}
#[test]
fn dropped_trailing_comment_is_rejected() {
let input = "module m;\n wire x; // trailing\nendmodule\n";
let output = "module m;\n wire x;\nendmodule\n";
assert!(matches!(expect_divergence(input, output), VerificationError::Divergence { .. }));
}
#[test]
fn comment_at_end_of_file_is_rejected_if_dropped() {
let input = "module m;\nendmodule\n// last word\n";
let output = "module m;\nendmodule\n";
assert!(matches!(expect_divergence(input, output), VerificationError::Divergence { .. }));
}
#[test]
fn truncated_output_is_rejected() {
let input = "module m;\n wire x;\nendmodule\n";
let output = "module m;\n wire x;\n";
match expect_divergence(input, output) {
VerificationError::Divergence { expected, got, .. } => {
assert_eq!(expected.expect("expected item").text, "endmodule");
assert!(got.is_none());
}
other => panic!("wrong error: {other}"),
}
}
#[test]
fn extra_token_in_output_is_rejected() {
let input = "module m;\nendmodule\n";
let output = "module m;\nendmodule\nmodule n;\nendmodule\n";
match expect_divergence(input, output) {
VerificationError::Divergence { expected, got, .. } => {
assert!(expected.is_none());
assert_eq!(got.expect("got item").text, "module");
}
other => panic!("wrong error: {other}"),
}
}
#[test]
fn same_text_different_kind_is_rejected() {
// `x` as an identifier vs. `"x"` as a string literal.
assert!(matches!(
expect_divergence("assign a = x;\n", "assign a = \"x\";\n"),
VerificationError::Divergence { .. }
));
}
#[test]
fn unlexable_output_is_reported() {
match verify_equivalence("module m;\nendmodule\n", "module m;\n\"unterminated\n") {
Err(VerificationError::Lex { side, .. }) => {
assert_eq!(side.to_string(), "output");
}
other => panic!("expected a lex error, got {other:?}"),
}
}
#[test]
fn implicit_sensitivity_spellings_are_equivalent() {
let input = "module m;\n always @* y = a;\nendmodule\n";
let output = "module m;\n always @(*) y = a;\nendmodule\n";
verify_equivalence(input, output).expect("`@*` and `@(*)` are the same construct");
verify_equivalence(output, input).expect("the canonicalization is symmetric");
}
#[test]
fn convergence_accepts_a_fixed_point() {
verify_convergence("module m;\nendmodule\n", "module m;\nendmodule\n").expect("fixed point");
}
#[test]
fn convergence_reports_the_first_differing_line() {
match verify_convergence(
"module m;\n wire x;\nendmodule\n",
"module m;\n wire x;\nendmodule\n",
) {
Err(VerificationError::NotConverged { line, first, second }) => {
assert_eq!(line, 2);
assert_eq!(first, " wire x;");
assert_eq!(second, " wire x;");
}
other => panic!("expected a convergence failure, got {other:?}"),
}
}
#[test]
fn convergence_reports_a_truncated_second_pass() {
match verify_convergence("module m;\nendmodule\n", "module m;\n") {
Err(VerificationError::NotConverged { line, second, .. }) => {
assert_eq!(line, 2);
assert_eq!(second, "<end of file>");
}
other => panic!("expected a convergence failure, got {other:?}"),
}
}
#[test]
fn format_source_runs_both_checks_and_succeeds_on_real_input() {
let src = "// header\n\
module m #(parameter W = 8) (input clk, output reg [W-1:0] q);\n\
always @(posedge clk) q <= q + 1; // count\n\
endmodule\n";
let out = format_source(src, &Config::default()).expect("formats cleanly");
verify_equivalence(src, &out).expect("equivalent");
verify_convergence(&out, &format_source(&out, &Config::default()).expect("second pass"))
.expect("converged");
}
#[test]
fn format_source_reports_source_errors_as_source_errors() {
match format_source("module m;\n", &Config::default()) {
Err(FormatError::Source(_)) => {}
other => panic!("expected a parse error, got {other:?}"),
}
}
#[test]
fn diagnostics_stay_on_one_physical_line() {
// Comment text can carry tabs and newlines; the rendered diagnostic
// must escape them, since CLI consumers (e.g. tools/corpus_check.sh)
// treat one stderr line as one diagnostic.
let input = "module m;\n /* a\tb\n c */\n wire x;\nendmodule\n";
let output = "module m;\n wire x;\nendmodule\n";
let rendered = expect_divergence(input, output).to_string();
assert!(!rendered.contains('\t'), "raw tab in: {rendered}");
assert!(!rendered.contains('\n'), "raw newline in: {rendered}");
assert!(rendered.contains("\\t") && rendered.contains("\\n"), "{rendered}");
}
#[test]
fn format_source_would_reject_a_non_equivalent_output() {
// The real formatter is expected never to produce such output, so the
// failsafe path is exercised through the checker with a crafted pair:
// this is exactly the call `format_source` makes before returning.
let src = "module m;\n wire x; // dropped by a hypothetical bug\nendmodule\n";
let bad_output = "module m;\n wire x;\nendmodule\n";
let err = FormatError::Verification(expect_divergence(src, bad_output));
assert!(err.to_string().starts_with("verification failed:"), "{err}");
}
// --------------------------------------------------------------------------
// corpus-bugs (2026-08-19): the four root causes the corpus check found were
// all fixed in the parser/formatter, with no new forgiveness in `normalize`.
// These pin that down: every shape the net used to catch is still caught, so a
// future regression in the fixes shows up as a refusal, not as a rewritten
// file. Per CLAUDE.md hard invariant #4 these are the attack tests that would
// have been mandatory had any of the fixes been made in `verify.rs` instead.
#[test]
fn an_event_list_comma_rewritten_as_or_is_still_rejected() {
// Root cause A. `,` and `or` mean the same thing to a simulator, so a
// normalization that collapsed them would have "fixed" the corpus files
// while letting the formatter rewrite tokens at will.
let input = "module m;\n always_ff @(posedge clk_i, negedge rst_ni) q <= d;\nendmodule\n";
let output = "module m;\n always_ff @(posedge clk_i or negedge rst_ni) q <= d;\nendmodule\n";
expect_divergence(input, output);
// ...and the reverse rewrite too.
expect_divergence(output, input);
}
#[test]
fn merged_header_imports_are_still_rejected() {
// Root cause C: two header `import` statements folded into one, turning a
// `;` into a `,`.
let input = "module m\n import a::*;\n import b::t;\n(input clk);\nendmodule\n";
let output = "module m\n import a::*, b::t;\n(input clk);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_empty_parameter_override_is_still_rejected() {
// Root cause D: `#()` is two tokens, and dropping them is token loss even
// though the instantiation means the same thing without them.
let input = "module tb;\n sub #() u0 (.a(x));\nendmodule\n";
let output = "module tb;\n sub u0 (.a(x));\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_comment_moved_out_of_a_bracketed_list_is_still_rejected() {
// Root cause B: the comment is not dropped here, only moved across the
// `)` — which changes which region a `verilator lint_on` pragma covers.
// Stream order is what makes that detectable, so it must stay compared.
let input = "module m #(\n parameter int W = 8\n /* verilator lint_on UNUSED */\n) (input a);\nendmodule\n";
let output = "module m #(\n parameter int W = 8\n)\n/* verilator lint_on UNUSED */\n(input a);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_comment_moved_across_a_binary_operator_is_still_rejected() {
// Root cause B in expressions: moving a comment from after the operator to
// before it keeps every token, so only the comment's position in the
// stream catches it.
let input = "module m;\n assign y = a && // note\n b;\nendmodule\n";
let output = "module m;\n assign y = a // note\n && b;\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_comment_moved_across_a_semicolon_is_still_rejected() {
// Root cause B on declarations: `/* verilator split_var */` printed after
// the `;` instead of before it applies to nothing.
let input = "module m;\n logic x /* verilator split_var */;\nendmodule\n";
let output = "module m;\n logic x; /* verilator split_var */\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn two_line_comments_merged_onto_one_line_are_still_rejected() {
// The failure mode the new comment placement has to avoid: printing two
// line comments on one physical line re-lexes as a single, longer comment.
let input = "module m;\n assign y = a && // one\n // two\n b;\nendmodule\n";
let output = "module m;\n assign y = a && // one // two\n b;\nendmodule\n";
expect_divergence(input, output);
}
// --------------------------------------------------------------------------
// comments-round (2026-08-19): the comment-attachment gaps closed this round
// were all fixed by giving the AST somewhere to keep the comment
// (`Meta::before_sep` and friends), not by teaching `verify.rs` to forgive
// the motion. These are the attack tests for that: every "corrupted" output
// below is what the fix would look like if it had been made in the safety net
// instead, and every one of them must still be rejected. Per CLAUDE.md hard
// invariant #4 — the normalizations are unchanged, so none of this is
// required, and it is here precisely so a future shortcut fails loudly.
#[test]
fn a_comment_moved_across_a_list_comma_is_still_rejected() {
// The bulk of this round: `a /* c */,` reprinted as `a, /* c */`. Every
// token survives and the comment survives; only its position in the
// stream changes, so nothing but stream order can catch it.
let input = "module m (input logic a /* first */, input logic b);\nendmodule\n";
let output = "module m (input logic a, /* first */ input logic b);\nendmodule\n";
expect_divergence(input, output);
// ...and a normalization forgiving one direction must not forgive the
// other either.
expect_divergence(output, input);
}
#[test]
fn a_comment_moved_out_of_a_connections_parens_is_still_rejected() {
// `.data_i (x /* verilator lint_off */)` printed with the comment after
// the `)` puts the pragma outside the region it names.
let input = "module m;\n sub u (.a(x /* lint_off */), .b(y));\nendmodule\n";
let output = "module m;\n sub u (.a(x) /* lint_off */, .b(y));\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_comment_moved_out_of_a_replication_is_still_rejected() {
// `Expr::Repl` printed its elements with a fixed `", "` join, so a comment
// inside it had nowhere to go and drifted past the closing braces.
let input = "module m;\n assign y = {2{a /* why */, b}};\nendmodule\n";
let output = "module m;\n assign y = {2{a, b}}; /* why */\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_comment_moved_across_an_event_list_separator_is_still_rejected() {
// The event-list twin of the comma case: `or` is the separator here, and
// the comment must stay on the side of it that the source wrote.
let input =
"module m;\n always @(posedge clk /* the clock */ or negedge rst_n) q <= d;\nendmodule\n";
let output =
"module m;\n always @(posedge clk or /* the clock */ negedge rst_n) q <= d;\nendmodule\n";
expect_divergence(input, output);
expect_divergence(output, input);
}
#[test]
fn a_comment_moved_between_two_header_imports_is_still_rejected() {
// Header imports had no `Meta` at all, so a comment between two of them
// fell through to the next construct.
let input = "module m\n import a::*;\n // then the other one\n import b::t;\n(input x);\nendmodule\n";
let output =
"module m\n import a::*;\n import b::t;\n// then the other one\n(input x);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_enum_dangling_comment_is_still_rejected() {
// `EnumType::dangling` was collected by the parser and never printed: a
// dropped comment, which is hard invariant #3 and must stay a refusal.
let input = "module m;\n typedef enum logic {A, B\n // that is all\n } e_t;\nendmodule\n";
let output = "module m;\n typedef enum logic {A, B} e_t;\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_line_comment_swallowing_a_list_comma_is_still_rejected() {
// `before_sep` prints the comma after the comment; a line comment runs to
// end of line, so putting the comma on the same line deletes it. The
// formatter emits a hard line for exactly this reason.
let input = "module m (input logic a // why\n , input logic b);\nendmodule\n";
let output = "module m (\n input logic a // why ,\n input logic b\n);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_comment_moved_past_a_module_headers_param_bracket_is_still_rejected() {
// The comment used to fall through to the first parameter port, which puts
// it *inside* the `#(...)` the source wrote it before.
let input = "module m\n// why these defaults\n#(parameter int P = 1) (input a);\nendmodule\n";
let output =
"module m #(\n // why these defaults\n parameter int P = 1\n) (input a);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_comment_moved_past_a_module_headers_port_bracket_is_still_rejected() {
// The port-list twin, which is what the corpus's `prim_lc_dec.sv` writes
// between its header `import` and the `(`.
let input = "module m\n import p::*;\n// the ports\n(input a);\nendmodule\n";
let output = "module m\n import p::*;\n(\n // the ports\n input a\n);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_comment_moved_past_an_instantiations_param_bracket_is_still_rejected() {
// Same shape one level down: between the module name and the `#(` of an
// instantiation's parameter override list.
let input = "module m;\n sub\n // override the width\n #(.WIDTH(8)) u (.a(b));\nendmodule\n";
let output = "module m;\n sub #(\n // override the width\n .WIDTH(8)\n ) u (.a(b));\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_comment_moved_past_an_instances_connection_bracket_is_still_rejected() {
let input = "module m;\n sub u\n // hook it up\n (.a(b));\nendmodule\n";
let output = "module m;\n sub u (\n // hook it up\n .a(b)\n );\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_comment_swapped_with_an_attribute_is_still_rejected() {
// `Meta` keeps attributes and leading comments in two lists; printing all
// comments and then all attributes swaps a pair the source interleaved.
// Both directions, because both spellings occur in the corpus.
let input =
"(* DONT_TOUCH = \"yes\" *)\n// keep the tool honest\nmodule m (input a);\nendmodule\n";
let output =
"// keep the tool honest\n(* DONT_TOUCH = \"yes\" *)\nmodule m (input a);\nendmodule\n";
expect_divergence(input, output);
expect_divergence(output, input);
}
#[test]
fn an_attribute_hoisted_past_a_comment_that_preceded_it_is_still_rejected() {
// Three-way interleave: only the middle attribute moves, which a
// "sort the comments, then append the attributes" printer would do.
let input = "module m;\n (* a *)\n // between\n (* b *)\n logic x;\nendmodule\n";
let output = "module m;\n (* a *)\n (* b *)\n // between\n logic x;\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_bracket_comment_is_still_rejected() {
// The failure mode the new `Vec<Comment>` fields must never regress into:
// harvesting the comment and then never printing it (hard invariant #3).
let input = "module m\n// why these defaults\n#(parameter int P = 1) (input a);\nendmodule\n";
let output = "module m #(parameter int P = 1) (input a);\nendmodule\n";
expect_divergence(input, output);
let input = "module m;\n sub u\n // hook it up\n (.a(b));\nendmodule\n";
let output = "module m;\n sub u (.a(b));\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_instance_name_comment_is_still_rejected() {
// The single-instance branch of `instantiation` printed the instance
// without its `Meta`, so a comment between the `#(...)` and the instance
// name was parsed and never emitted — hard invariant #3, caught only
// because the net refused the file.
let input = "module m;\n sub #(.W(1))\n // the instance\n u (.a(b));\nendmodule\n";
let output = "module m;\n sub #(.W(1)) u (.a(b));\nendmodule\n";
expect_divergence(input, output);
}
// ---------------------------------------------------------------------------
// `ifdef and friends between list elements (docs/features/directives-in-lists)
//
// This feature added no normalization — `verify.rs` is byte-identical to the
// commit before it — so hard invariant #4 does not bind. The tests below exist
// anyway, one per corruption the new list plumbing could plausibly produce, so
// that any future widening of the net has to survive them first.
// ---------------------------------------------------------------------------
#[test]
fn a_comma_swallowed_into_a_list_directive_is_rejected() {
// The sharpest hazard in this feature: a directive runs to end of line, so
// printing its comma on the *same* line fuses the two into one token. The
// formatter puts the comma on a fresh line; this pins what happens if it
// ever stops.
let input = "module m #(\n parameter int A = 1\n`ifdef S\n ,\n parameter int B = 2\n`endif\n) ();\nendmodule\n";
let output = "module m #(\n parameter int A = 1\n `ifdef S,\n parameter int B = 2\n `endif\n) ();\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_comma_moved_across_a_list_directive_is_rejected() {
// Deriving each element's comma from its index instead of from the source
// produces exactly this: the comma hops to the other side of the `ifdef.
let input = "module m #(\n parameter int A = 1\n`ifdef S\n ,\n parameter int B = 2\n`endif\n) ();\nendmodule\n";
let output = "module m #(\n parameter int A = 1,\n `ifdef S\n parameter int B = 2\n `endif\n) ();\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_comma_invented_between_two_ifdef_arms_is_rejected() {
// `ifdef X a `else b `endif — neither arm writes a comma, and a list that
// commas every element but the last would add one after `a`.
let input = "module m (\n`ifdef X\n input a\n`else\n input b\n`endif\n);\nendmodule\n";
let output =
"module m (\n `ifdef X\n input a,\n `else\n input b\n `endif\n);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_comma_dropped_before_a_list_directive_is_rejected() {
let input = "module m (\n input a,\n`ifdef X\n input b\n`endif\n);\nendmodule\n";
let output = "module m (\n input a\n `ifdef X\n input b\n `endif\n);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_list_directive_is_rejected() {
let input = "module m (\n input a,\n`ifdef X\n input b\n`endif\n);\nendmodule\n";
let output = "module m (\n input a,\n input b\n);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_list_directive_printed_out_of_order_is_rejected() {
// `before` is what puts the directives back among the elements; an
// off-by-one there emits `endif before the port it was written after.
let input = "module m (\n input a,\n`ifdef X\n input b,\n`endif\n input c\n);\nendmodule\n";
let output =
"module m (\n input a,\n `ifdef X\n `endif\n input b,\n input c\n);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_changed_list_directive_condition_is_rejected() {
let input = "module m (\n input a,\n`ifdef X\n input b\n`endif\n);\nendmodule\n";
let output = "module m (\n input a,\n `ifdef Y\n input b\n `endif\n);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_comment_on_a_list_directive_is_rejected() {
// The directive's own `Meta` is new plumbing, so it gets the same
// dropped-comment guard the bracket buckets have (hard invariant #3).
let input = "module m (\n input a,\n // only when X\n`ifdef X // why\n input b\n`endif\n);\nendmodule\n";
let output = "module m (\n input a,\n `ifdef X\n input b\n `endif\n);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_list_directive_may_still_be_reindented() {
// The other direction: moving the directive to the list's indent level is
// what the formatter legitimately does, and must stay accepted.
let input = "module m (\n input a,\n`ifdef X\n input b\n`endif\n);\nendmodule\n";
let output = "module m (\n input a,\n `ifdef X\n input b\n `endif\n);\nendmodule\n";
verify_equivalence(input, output).expect("only indentation changed");
}
// ---------------------------------------------------------------------------
// ... and between an instantiation's parameter overrides and connections
// (docs/features/directives-in-instances)
//
// Also no normalization: `verify.rs` is byte-identical to the commit before
// this feature, so hard invariant #4 does not bind here either. One test per
// corruption the two new parse loops could plausibly produce.
// ---------------------------------------------------------------------------
#[test]
fn a_comma_swallowed_into_a_connection_list_directive_is_rejected() {
// The same end-of-line hazard as in a header's lists: printing a
// directive's comma on its own line is what keeps the two separate tokens.
let input =
"module m;\n sub u (\n .a(x)\n`ifdef X\n ,\n .b(y)\n`endif\n );\nendmodule\n";
let output =
"module m;\n sub u (\n .a(x)\n `ifdef X,\n .b(y)\n `endif\n );\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_comma_moved_across_a_connection_list_directive_is_rejected() {
// Deriving a connection's comma from its index rather than from the source
// hops it to the other side of the `ifdef.
let input =
"module m;\n sub u (\n .a(x)\n`ifdef X\n ,\n .b(y)\n`endif\n );\nendmodule\n";
let output =
"module m;\n sub u (\n .a(x),\n `ifdef X\n .b(y)\n `endif\n );\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_comma_invented_between_two_connection_ifdef_arms_is_rejected() {
// Neither arm writes a comma; a list that commas every entry but the last
// would add one after the first `.a(x)`.
let input =
"module m;\n sub u (\n`ifdef X\n .a(x)\n`else\n .a(y)\n`endif\n );\nendmodule\n";
let output = "module m;\n sub u (\n `ifdef X\n .a(x),\n `else\n .a(y)\n `endif\n );\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_parameter_override_directive_is_rejected() {
// The `torture/testbench.v` shape: the `include is the *only* thing in the
// override list, so losing it would silently empty the `#()`.
let input = "module m;\n sub #(\n`include \"config.vh\"\n ) u (.a(x));\nendmodule\n";
let output = "module m;\n sub #() u (.a(x));\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_connection_list_directive_printed_out_of_order_is_rejected() {
// `before` is what interleaves the directives with the connections; an
// off-by-one there emits the `endif before the connection it wrapped.
let input = "module m;\n sub u (\n .a(x),\n`ifdef X\n .b(y),\n`endif\n .c(z)\n );\nendmodule\n";
let output = "module m;\n sub u (\n .a(x),\n `ifdef X\n `endif\n .b(y),\n .c(z)\n );\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_comment_before_a_directive_only_override_lists_paren_is_rejected() {
// The comment written after the list's one directive and before its `)`
// has no element to ride on; hard invariant #3 says it must still survive.
let input =
"module m;\n sub #(\n`include \"config.vh\"\n // nothing else\n ) u (.a(x));\nendmodule\n";
let output = "module m;\n sub #(\n `include \"config.vh\"\n ) u (.a(x));\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn an_instantiation_list_directive_may_still_be_reindented() {
// The other direction: re-indenting the directive to the list's level is
// what the formatter legitimately does, and must stay accepted.
let input = "module m;\n sub u (\n .a(x),\n`ifdef X\n .b(y)\n`endif\n );\nendmodule\n";
let output =
"module m;\n sub u (\n .a(x),\n `ifdef X\n .b(y)\n `endif\n );\nendmodule\n";
verify_equivalence(input, output).expect("only indentation changed");
}
// ----------------------------------------------------------------------
// Verbatim class-scope blocks (`docs/features/classes/README.md`).
//
// `constraint` and `covergroup` bodies are copied out of the source by span
// and re-indented, so the net must still see every token inside them. These
// are the invariant-#4 attack tests for that capture: no normalization was
// added for it, and each pair below proves a real change inside a verbatim
// block is refused rather than forgiven as "just re-indentation".
// ----------------------------------------------------------------------
#[test]
fn a_constraint_block_may_be_reindented() {
let input = "class c;\nconstraint x {\n a == 0;\n}\nendclass\n";
let output = "class c;\n constraint x {\n a == 0;\n }\nendclass\n";
verify_equivalence(input, output).expect("only per-line indentation changed");
}
#[test]
fn a_changed_constraint_expression_is_rejected() {
let input = "class c;\n constraint x {\n a == 0;\n }\nendclass\n";
let output = "class c;\n constraint x {\n a == 1;\n }\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_constraint_line_is_rejected() {
let input = "class c;\n constraint x {\n a == 0;\n b == 1;\n }\nendclass\n";
let output = "class c;\n constraint x {\n a == 0;\n }\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_comment_inside_a_constraint_is_rejected() {
let input = "class c;\n constraint x {\n // why\n a == 0;\n }\nendclass\n";
let output = "class c;\n constraint x {\n a == 0;\n }\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn a_reindented_string_inside_a_constraint_is_rejected() {
let input = "class c;\n constraint x {\n n == \"a\n b\";\n }\nendclass\n";
let output = "class c;\n constraint x {\n n == \"a\n b\";\n }\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn a_constraint_carrying_a_multiline_string_is_left_alone_end_to_end() {
// The formatter must not move those bytes at all: `raw_text` emits a
// token whose line break falls inside a string verbatim.
let input = "class c;\nconstraint x {\nn == \"a\n b\";\n}\nendclass\n";
let output = format_source(input, &Config::default()).expect("must format");
assert!(output.contains("\"a\n b\""), "the string's bytes changed:\n{output}");
}
#[test]
fn a_changed_covergroup_bin_is_rejected() {
let input = "class c;\n covergroup g;\n coverpoint a {\n bins z = { 0 };\n }\n endgroup\nendclass\n";
let output = "class c;\n covergroup g;\n coverpoint a {\n bins z = { 1 };\n }\n endgroup\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_covergroup_label_is_rejected() {
let input = "class c;\n covergroup g;\n coverpoint a;\n endgroup : g\nendclass\n";
let output = "class c;\n covergroup g;\n coverpoint a;\n endgroup\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn a_changed_parameterized_type_argument_is_rejected() {
let input = "class c;\n port_t #(bit [31:0]) p;\nendclass\n";
let output = "class c;\n port_t #(bit [30:0]) p;\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_class_end_label_is_rejected() {
let input = "class c;\n int a;\nendclass : c\n";
let output = "class c;\n int a;\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_method_qualifier_is_rejected() {
let input = "class c;\n virtual function void f();\n endfunction\nendclass\n";
let output = "class c;\n function void f();\n endfunction\nendclass\n";
expect_divergence(input, output);
}
// ----------------------------------------------------------------------
// Alignment inference: the layout it picks must be a fixed point at every
// configured width, not just at the default one. See
// `docs/features/alignment/README.md`.
// ----------------------------------------------------------------------
/// Format `src` at `width`, then format that again, and return both.
fn twice(src: &str, width: usize, indent: usize) -> (String, String) {
let config = Config { max_width: width, indent_width: indent };
let once = format_source(src, &config).expect("first pass");
let again = format_source(&once, &config).expect("second pass");
(once, again)
}
#[test]
fn an_aligned_group_is_a_fixed_point_at_every_width() {
let src = "\
module m (
input wire clk,
input wire [WIDTH-1:0] data,
output logic valid
);
sub u (
.clk (clk),
.reset_n (rst_n),
.data_valid (dv)
);
localparam int A = 1;
localparam int LONGER = 22;
endmodule
";
for width in [40, 60, 80, 100, 120, 200] {
for indent in [2, 4] {
let (once, again) = twice(src, width, indent);
assert_eq!(once, again, "not a fixed point at width {width}, indent {indent}");
}
}
}
#[test]
fn a_group_that_alignment_gives_up_on_still_converges() {
// Regression: the alignment verdict used to be split between building
// the document (which forced the list open) and printing it (which chose
// the padding). At a narrow width the printer backed out while the forced
// break stayed, and the `#( ... )` above the list broke differently on
// the next pass.
let src = "\
module m;
prim_buf #(
.Width(NumBusyBits)
) u_buf (
.in_i ({$bits(mubi_t){ctrl_busy, if_busy, lsu_busy}}),
.out_o(busy_bits_buf)
);
endmodule
";
for width in [40, 50, 60, 70, 80, 100] {
let (once, again) = twice(src, width, 2);
assert_eq!(once, again, "not a fixed point at width {width}");
}
}
#[test]
fn a_hint_converges_in_one_pass_and_then_holds() {
let src = "\
module m;
localparam int A = 1;
localparam int LONGER = 22;
endmodule
";
let (once, again) = twice(src, 100, 2);
assert!(once.contains("localparam int A = 1;"), "expected an aligned `=`:\n{once}");
assert_eq!(once, again);
}
#[test]
fn a_flush_group_stays_flush() {
let src = "\
module m;
localparam int A = 1;
localparam int LONGER = 22;
endmodule
";
let (once, again) = twice(src, 100, 2);
assert_eq!(once, src, "a group with no alignment hint must not gain one");
assert_eq!(once, again);
}