Files
lucisv/crates/vlog_formatter/tests/verification.rs
T
lucioandClaude Fable 5 4e62a14af6 Fragment mode and define continuation: the three .svh shapes that did not parse, and the define that was blamed on its class body
TODO section 22, coverage_gaps H4 corrected. Class-body and module-item
include fragments already parsed - the file-scope item loop is the
class-item loop. The three shapes that did not - a bare statement list,
an enum-member list (riscv-dv's CUSTOM_1, file, included between enum
members), a covergroup-item list - become SourceFile::fragment, detected
by a whole-file rule that cannot misfire on a valid file: the first
structural item failed (directives, macros and null items do not count;
a tolerant Ok that recorded a diagnostic counts as failed - an existing
parity test caught if/else reading as a generate-if to one parser and a
statement to the other), the file does not open with a design-unit
keyword, and a shape consumes the file to EOF, tried narrowest-first.
Each shape re-lexes a fresh token stream - Rewind does not restore the
tokens' comment buckets and the first draft lost comments on
non-fragment files. A fragment formats at indent zero through the
existing printers; its declarations bind; its enum variants are not
exported (pkg::CUSTOM_1 must not resolve to a name that does not
exist). FACTS stays 12.

The other .svh was never a fragment problem: a define whose formal
argument list spans two lines with no backslash. The lexer continues
such a directive until the list closes - incrementally, after QA found
the first cut quadratic on an unclosed list (20000 lines: 2.5 s ->
0.56 ms), pinned by a byte-visit counter.

Opentitan 12 -> 10 failing files, exactly the two predicted; corpus
813 -> 814 of 820; every remaining comment-gap failure proven to fail
identically outside a fragment.

docs/features/fragment-mode/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 07:34:31 -07:00

2385 lines
102 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
/// `lucisv` 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}"),
}
}
/// Why `` `uvm_field_int (a, b) `` keeps its space instead of being tightened
/// to the canonical `` `uvm_field_int(a, b) ``: the two spellings are *one*
/// token each, of different text, so closing the gap is a token rewrite the
/// safety net refuses. Nothing in `verify.rs` forgives it, and this test is
/// here so nothing starts to.
#[test]
fn tightening_a_spaced_macro_call_is_rejected() {
let input = "module m;\n `A (x, y)\nendmodule\n";
let output = "module m;\n `A(x, y)\nendmodule\n";
match expect_divergence(input, output) {
VerificationError::Divergence { expected, got, .. } => {
assert_eq!(expected.expect("expected item").text, "`A");
assert_eq!(got.expect("got item").text, "`A(x, y)");
}
other => panic!("wrong error: {other}"),
}
}
/// Why `` 32'h`DM_ADDR `` is printed with no gap: the backtick has to touch
/// the base or the text does not lex as a number at all. Nothing in
/// `verify.rs` forgives the space, and this test is here so nothing starts to.
#[test]
fn spacing_out_a_macro_digit_number_is_rejected() {
let input = "module m;\n localparam int A = 32'h`W;\nendmodule\n";
let output = "module m;\n localparam int A = 32'h `W;\nendmodule\n";
match expect_divergence(input, output) {
VerificationError::Lex { .. } => {}
other => panic!("wrong error: {other}"),
}
// And the mirror image: a number that really does carry its own digits
// must not gain a macro.
let input = "module m;\n localparam int A = 32'h1;\nendmodule\n";
let output = "module m;\n localparam int A = 32'h`W;\nendmodule\n";
expect_divergence(input, output);
}
/// QA round-2 attack (mop-up-2 mandate): a based number joined with a macro
/// whose argument list carries a multi-line string. Re-lexing the *output*
/// still splits this back into a `Number` (`32'h`) and a macro `Ident`, so
/// the string-aware trim on that `Ident` is what has to hold here, exactly as
/// it does for a bare macro statement — nothing about gluing a base onto the
/// front should widen what gets forgiven inside the string.
#[test]
fn a_macro_digit_numbers_multiline_string_may_not_be_reindented() {
let input = "module m;\n localparam int A = 32'h`M(\"a\nb\", c);\nendmodule\n";
let output = "module m;\n localparam int A = 32'h`M(\"a\n b\", c);\nendmodule\n";
expect_divergence(input, output);
// The line break introduced by the argument list itself (not the string)
// is still free to be re-indented, same as any other multi-line macro.
let input = "module m;\n localparam int A = 32'h`M(\"ab\",\n c);\nendmodule\n";
let output = "module m;\n localparam int A = 32'h`M(\"ab\",\n c);\nendmodule\n";
verify_equivalence(input, output).expect("only the non-string line moved");
}
/// QA round-2 attack: the hoisted `at_macro_item` line rule reads
/// `Parser::macro_end_line`, which counts every `\n` byte in the invocation's
/// *text* — including ones inside a string argument — to find which source
/// line the macro ends on. A macro whose only newlines come from a multi-line
/// string, immediately followed by an unrelated symbol on the next line, must
/// still refuse a reindented string exactly like any other multi-line macro.
#[test]
fn a_macro_ending_its_line_still_rejects_a_reindented_multiline_string() {
let input =
"module m;\n initial begin\n `uvm_info(\"id\", \"a\nb\", UVM_LOW)\n x = 1;\n end\nendmodule\n";
let output =
"module m;\n initial begin\n `uvm_info(\"id\", \"a\n b\", UVM_LOW)\n x = 1;\n end\nendmodule\n";
expect_divergence(input, output);
}
/// `new src` (IEEE 1800 §8.12) prints with exactly one space. Closing it would
/// make one identifier out of two tokens — the net refuses that, in both
/// directions.
#[test]
fn gluing_a_shallow_copy_to_its_source_handle_is_rejected() {
let input = "class c;\n function void f();\n a = new src;\n endfunction\nendclass\n";
let output = "class c;\n function void f();\n a = newsrc;\n endfunction\nendclass\n";
match expect_divergence(input, output) {
VerificationError::Divergence { expected, got, .. } => {
assert_eq!(expected.expect("expected item").text, "new");
assert_eq!(got.expect("got item").text, "newsrc");
}
other => panic!("wrong error: {other}"),
}
}
/// The mirror image: re-spacing a *glued* invocation is rejected too, so the
/// formatter cannot drift between the two spellings in either direction.
#[test]
fn loosening_a_glued_macro_call_is_rejected() {
let input = "module m;\n `A(x, y)\nendmodule\n";
let output = "module m;\n `A (x, y)\nendmodule\n";
match expect_divergence(input, output) {
VerificationError::Divergence { expected, got, .. } => {
assert_eq!(expected.expect("expected item").text, "`A(x, y)");
assert_eq!(got.expect("got item").text, "`A");
}
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 { .. }));
}
/// QA round-1 (2026-08-21): `Doc::Inline` (the `with { ... }` constraint
/// block printer node, `dv-statements`) is meant to be reproduced byte for
/// byte — `Fmt::with_block` never re-indents it. This locks that in from the
/// safety-net side: even if a future change *did* try to re-indent a
/// multi-line string sitting inside a `with { ... }` block, the net must
/// still reject the corrupted result on token-stream grounds, exactly as it
/// does for the macro-argument and `` `define `` cases above.
#[test]
fn reindented_string_inside_a_with_block_is_rejected() {
let input = "module m;\n class C;\n task t();\n if (2) begin\n x.randomize() with {\n $display(\"line one\n line two\");\n };\n end\n endtask\n endclass\nendmodule\n";
let output = "module m;\n class C;\n task t();\n if (2) begin\n x.randomize() with {\n $display(\"line one\n line two\");\n };\n end\n endtask\n endclass\nendmodule\n";
expect_divergence(input, output);
}
#[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");
}
// ----------------------------------------------------------------------
// Class-scope blocks (`docs/features/classes/README.md`,
// `docs/features/constraint-bodies/README.md`).
//
// Both a `constraint` body and a `covergroup` body are laid out from a real
// tree since rounds 1 and 2 of this wave, and a body the grammar does not
// know still falls back to the byte-for-byte capture. Either way the net must
// see every token inside the block. `verify.rs` was **not** widened for
// either round — nothing in it knows constraints or covergroups exist — and
// these are the invariant-#4 tests that say so: each pair is a change a
// re-layout could plausibly be mistaken for, asserted refused.
// ----------------------------------------------------------------------
#[test]
fn a_constraint_block_may_be_relaid_out() {
// The whole point of the round: the body is re-spaced and re-indented,
// items move to lines of their own, and the net still calls it the same
// token stream.
let input = "class c;\nconstraint x {\n a == 0; b == 1;\n}\nendclass\n";
let output = "class c;\n constraint x {\n a == 0;\n b == 1;\n }\nendclass\n";
verify_equivalence(input, output).expect("only layout changed");
}
#[test]
fn a_dropped_soft_is_rejected() {
// `soft` is not a lexer keyword — it is an ordinary identifier token —
// so losing it is losing a token, which is exactly what the net counts.
let input = "class c;\n constraint x {\n soft 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_swapped_dist_weight_operator_is_rejected() {
// `:=` weights every value in the range, `:/` splits one weight across
// it. Two different tokens, and two different distributions.
let input = "class c;\n constraint x {\n a dist {[1:9] := 5};\n }\nendclass\n";
let output = "class c;\n constraint x {\n a dist {[1:9] :/ 5};\n }\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn a_reordered_solve_before_is_rejected() {
// The order is the whole meaning of a `solve ... before`, and it is
// carried entirely by the operand order in the token stream.
let input = "class c;\n constraint x {\n solve a before b;\n }\nendclass\n";
let output = "class c;\n constraint x {\n solve b before a;\n }\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn a_reordered_dist_weight_is_rejected() {
// Swapping which value gets which weight changes the distribution even
// though every token is still present — the net must see the pairing,
// not just the bag of tokens. QA gap noted in the constraint-bodies
// round: the operator swap (`:=` vs `:/`) had a pin, the value/weight
// reorder did not.
let input = "class c;\n constraint x {\n a dist {0 := 1, 1 := 9};\n }\nendclass\n";
let output = "class c;\n constraint x {\n a dist {1 := 9, 0 := 1};\n }\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn a_soft_moved_to_the_wrong_item_is_rejected() {
// `soft` qualifies exactly the item it prefixes; moving it to a
// different item changes which constraint may be relaxed by the solver.
// QA gap noted in the constraint-bodies round alongside the dist-weight
// reorder above.
let input = "class c;\n constraint x {\n soft a == 0;\n b == 1;\n }\nendclass\n";
let output = "class c;\n constraint x {\n a == 0;\n soft b == 1;\n }\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_else_set_is_rejected() {
let input = "class c;\n constraint x {\n if (m) a == 0;\n else a == 1;\n }\nendclass\n";
let output = "class c;\n constraint x {\n if (m) a == 0;\n }\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn an_implication_flattened_into_a_plain_expression_is_rejected() {
let input = "class c;\n constraint x {\n m -> a == 0;\n }\nendclass\n";
let output = "class c;\n constraint x {\n m;\n a == 0;\n }\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn a_comment_moved_across_a_constraint_brace_is_rejected() {
// The one shape the new nested-set layout could plausibly get wrong: a
// comment written inside the braces, printed after them.
let input = "class c;\n constraint x {\n m -> {\n a == 0;\n // why\n }\n }\nendclass\n";
let output =
"class c;\n constraint x {\n m -> {\n a == 0;\n }\n // why\n }\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_unique_or_disable_soft_word_is_rejected() {
let input =
"class c;\n constraint x {\n unique {a, b};\n disable soft c;\n }\nendclass\n";
let dropped_unique =
"class c;\n constraint x {\n {a, b};\n disable soft c;\n }\nendclass\n";
expect_divergence(input, dropped_unique);
let dropped_soft =
"class c;\n constraint x {\n unique {a, b};\n disable c;\n }\nendclass\n";
expect_divergence(input, dropped_soft);
}
#[test]
fn a_real_constraint_body_survives_its_own_relayout() {
// End to end: the formatter's own output for a body using most of the
// sub-grammar must verify against the input, and be a fixed point.
let input = "class c;\n constraint x {\n soft n dist { 0 := 5, [1:20] :/ 20 };\n solve k, m before n;\n (k != 0) -> { n < 4; }\n if (m) n == 1; else n == 2;\n foreach (q[i]) q[i] inside {[0:3]};\n unique {a, b};\n disable soft n;\n }\nendclass\n";
let once = format_source(input, &Config::default()).expect("must format");
verify_equivalence(input, &once).expect("the layout kept every token");
let twice = format_source(&once, &Config::default()).expect("must format again");
assert_eq!(once, twice, "the layout is a fixed point");
}
#[test]
fn a_constraint_body_the_grammar_does_not_know_is_left_alone_end_to_end() {
// The fallback: a macro standing where a constraint item belongs. The
// bytes must come back exactly, double spaces included.
let input = "class c;\n constraint x {\n `MY_HALF\n a == 0;\n }\nendclass\n";
let once = format_source(input, &Config::default()).expect("must format");
assert!(once.contains("`MY_HALF\n a == 0;"), "the capture was re-laid out:\n{once}");
}
#[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);
}
/// A covergroup body wrapped in the class the corpus always writes it in.
fn covergroup_pair(before: &str, after: &str) -> (String, String) {
let wrap = |body: &str| format!("class c;\n covergroup g;\n{body}\n endgroup\nendclass\n");
(wrap(before), wrap(after))
}
#[test]
fn a_covergroup_may_be_relaid_out() {
// The point of round 2: the body is re-spaced and re-indented, cover
// items and bins move to lines of their own, and the net still calls it
// the same token stream.
let input = "class c;\n covergroup g;cp:coverpoint a{bins z={0,1};bins w=default;}\n endgroup : g\nendclass\n";
let output = format_source(input, &Config::default()).expect("must format");
verify_equivalence(input, &output).expect("a re-layout is not a change");
let again = format_source(&output, &Config::default()).expect("must format again");
verify_convergence(&output, &again).expect("and it is a fixed point");
}
#[test]
fn a_dropped_bins_qualifier_is_rejected() {
// `ignore_bins` and `illegal_bins` mean different things from `bins`, and
// `wildcard` changes which values a bin matches. None may be normalized.
let (input, output) = covergroup_pair(
" cp: coverpoint a { ignore_bins z = {0}; }",
" cp: coverpoint a { bins z = {0}; }",
);
expect_divergence(&input, &output);
let (input, output) = covergroup_pair(
" cp: coverpoint a { wildcard bins z = {4'b1??1}; }",
" cp: coverpoint a { bins z = {4'b1??1}; }",
);
expect_divergence(&input, &output);
}
#[test]
fn a_dropped_bin_array_marker_is_rejected() {
// `bins b[] = {0, 1};` declares one auto-sized bin *per value*; `bins b =
// {0, 1};` declares one bin covering both values. Dropping the `[]`
// changes what the covergroup counts, so it may not be normalized away.
let (input, output) = covergroup_pair(
" cp: coverpoint a { bins z[] = {0, 1}; }",
" cp: coverpoint a { bins z = {0, 1}; }",
);
expect_divergence(&input, &output);
// And a fixed array size silently widened is the same class of change.
let (input, output) = covergroup_pair(
" cp: coverpoint a { bins z[2] = {0, 1}; }",
" cp: coverpoint a { bins z[4] = {0, 1}; }",
);
expect_divergence(&input, &output);
}
#[test]
fn a_reversed_transition_arrow_is_rejected() {
let (input, output) = covergroup_pair(
" cp: coverpoint a { bins t = (0 => 1); }",
" cp: coverpoint a { bins t = (1 => 0); }",
);
expect_divergence(&input, &output);
}
#[test]
fn a_changed_transition_repetition_is_rejected() {
// `[*3]`, `[->3]` and `[=3]` are three different bins.
let (input, output) = covergroup_pair(
" cp: coverpoint a { bins t = (1'b0[*3] => 1'b1); }",
" cp: coverpoint a { bins t = (1'b0[->3] => 1'b1); }",
);
expect_divergence(&input, &output);
}
#[test]
fn a_dropped_binsof_negation_is_rejected() {
let (input, output) = covergroup_pair(
" cr: cross a, b { bins s = binsof(a) && !binsof(b); }",
" cr: cross a, b { bins s = binsof(a) && binsof(b); }",
);
expect_divergence(&input, &output);
// And a dropped `intersect` set.
let (input, output) = covergroup_pair(
" cr: cross a, b { bins s = binsof(a) intersect {0}; }",
" cr: cross a, b { bins s = binsof(a); }",
);
expect_divergence(&input, &output);
}
#[test]
fn a_dropped_covergroup_iff_is_rejected() {
let (input, output) =
covergroup_pair(" cp: coverpoint a iff (en);", " cp: coverpoint a;");
expect_divergence(&input, &output);
let (input, output) = covergroup_pair(
" cp: coverpoint a { bins z = {0} iff (en); }",
" cp: coverpoint a { bins z = {0}; }",
);
expect_divergence(&input, &output);
}
#[test]
fn a_moved_coverpoint_label_is_rejected() {
let (input, output) = covergroup_pair(
" cp_a: coverpoint a;\n cp_b: coverpoint b;",
" cp_b: coverpoint a;\n cp_a: coverpoint b;",
);
expect_divergence(&input, &output);
}
#[test]
fn a_comment_moved_across_a_covergroup_brace_is_rejected() {
let (input, output) = covergroup_pair(
" cp: coverpoint a {\n bins z = {0};\n // why\n }",
" cp: coverpoint a {\n bins z = {0};\n }\n // why",
);
expect_divergence(&input, &output);
}
#[test]
fn a_dropped_option_assignment_is_rejected() {
let (input, output) =
covergroup_pair(" option.per_instance = 1;\n coverpoint a;", " coverpoint a;");
expect_divergence(&input, &output);
// And `option` swapped for `type_option`, which is a different setting.
let (input, output) = covergroup_pair(" option.weight = 1;", " type_option.weight = 1;");
expect_divergence(&input, &output);
}
#[test]
fn a_default_sequence_flattened_to_a_default_is_rejected() {
let (input, output) = covergroup_pair(
" cp: coverpoint a { bins d = default sequence; }",
" cp: coverpoint a { bins d = default; }",
);
expect_divergence(&input, &output);
}
#[test]
fn a_dropped_covergroup_sample_argument_is_rejected() {
let input = "class c;\n covergroup g with function sample (int a, int b);\n coverpoint a;\n endgroup\nendclass\n";
let output = "class c;\n covergroup g with function sample (int a);\n coverpoint a;\n endgroup\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn a_reordered_cross_operand_list_is_rejected() {
let (input, output) = covergroup_pair(" cr: cross a, b, c;", " cr: cross a, c, b;");
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);
}
// ------------------------------------------------------------------
// Dynamic types: attack pairs for the shapes this round made reachable.
// Nothing new is verbatim and `verify.rs` is untouched, but these pin the
// net's strictness against the corruptions this plumbing could plausibly
// produce (CLAUDE.md invariant #4 discipline, applied voluntarily).
// ------------------------------------------------------------------
#[test]
fn a_dropped_queue_dollar_is_rejected() {
let input = "class c;\n string q[$];\nendclass\n";
let output = "class c;\n string q[];\nendclass\n";
expect_divergence(input, output);
}
#[test]
fn a_dynamic_dim_widened_to_a_wildcard_is_rejected() {
let input = "module m;\n int a[];\nendmodule\n";
let output = "module m;\n int a[*];\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_named_argument_name_is_rejected() {
let input = "module m;\n initial csr_wr(.ptr(p), .value(v));\nendmodule\n";
let output = "module m;\n initial csr_wr(p, v);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_case_inside_keyword_is_rejected() {
let input = "module m;\n initial case (x) inside\n [1:2]: y = 1;\n endcase\nendmodule\n";
let output = "module m;\n initial case (x)\n [1:2]: y = 1;\n endcase\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn parens_invented_around_a_bare_event_are_rejected() {
let input = "module m;\n task t;\n @ev;\n endtask\nendmodule\n";
let output = "module m;\n task t;\n @(ev);\n endtask\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn an_emptied_queue_initializer_is_rejected() {
let input = "module m;\n bit q[$] = {A, B};\nendmodule\n";
let output = "module m;\n bit q[$] = {};\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_reindented_dynamic_type_declaration_is_accepted() {
// The legitimate transformation — whitespace only — still passes, so the
// six rejections above are not vacuous.
let input = "class c;\nstring q[$]={};\nrand int offset[];\nendclass\n";
let output = "class c;\n string q [$] = {};\n rand int offset [];\nendclass\n";
verify_equivalence(input, output).expect("whitespace is not part of the token stream");
}
// ----------------------------------------------------------------------
// Verbatim concurrent assertions (`docs/features/assertions/README.md`).
//
// Assertions reuse the class round's verbatim capture: no normalization was
// added to `verify.rs` for them, so these are the invariant-#4 pairs proving
// the net refuses a real change inside an assertion rather than forgiving it
// as "just re-indentation".
// ----------------------------------------------------------------------
#[test]
fn a_concurrent_assertion_may_be_reindented() {
let input =
"module m;\nassert property (@(posedge clk)\ndisable iff (!rst_n)\na |-> b);\nendmodule\n";
let output = "module m;\n assert property (@(posedge clk)\n disable iff (!rst_n)\n a |-> b);\nendmodule\n";
verify_equivalence(input, output).expect("only per-line indentation changed");
}
#[test]
fn a_changed_assertion_operator_is_rejected() {
let input = "module m;\n assert property (@(posedge clk) a |-> b);\nendmodule\n";
let output = "module m;\n assert property (@(posedge clk) a |=> b);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_changed_assertion_delay_range_is_rejected() {
let input = "module m;\n assert property (@(posedge clk) a |-> ##[1:3] b);\nendmodule\n";
let output = "module m;\n assert property (@(posedge clk) a |-> ##[1:4] b);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_disable_iff_clause_is_rejected() {
let input =
"module m;\n assert property (@(posedge clk) disable iff (!rst_n) a |-> b);\nendmodule\n";
let output = "module m;\n assert property (@(posedge clk) a |-> b);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_assertion_action_block_is_rejected() {
let input = "module m;\n assert property (@(posedge clk) a) else $error(\"no\");\nendmodule\n";
let output = "module m;\n assert property (@(posedge clk) a);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_assertion_label_is_rejected() {
let input = "module m;\n NoNMI: assume property (~irq_nm_i);\nendmodule\n";
let output = "module m;\n assume property (~irq_nm_i);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_comment_inside_an_assertion_is_rejected() {
let input = "module m;\n assert property (@(posedge clk)\n // only while enabled\n en |-> ready);\nendmodule\n";
let output = "module m;\n assert property (@(posedge clk)\n en |-> ready);\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_reindented_string_inside_an_assertion_action_is_rejected() {
let input = "module m;\n assert property (a) else $error(\"one\n two\");\nendmodule\n";
let output = "module m;\n assert property (a) else $error(\"one\n two\");\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn an_assertion_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 = "module m;\nassert property (@(posedge clk) a |-> b)\nelse $error(\"line one\n line two indented\");\nendmodule\n";
let output = format_source(input, &Config::default()).expect("must format");
assert!(
output.contains("\"line one\n line two indented\""),
"the string's bytes changed:\n{output}"
);
}
#[test]
fn a_changed_sequence_body_is_rejected() {
let input = "module m;\n sequence s;\n a ##1 b;\n endsequence\nendmodule\n";
let output = "module m;\n sequence s;\n a ##2 b;\n endsequence\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_dropped_endproperty_label_is_rejected() {
let input = "module m;\n property p;\n a |-> b;\n endproperty : p\nendmodule\n";
let output = "module m;\n property p;\n a |-> b;\n endproperty\nendmodule\n";
expect_divergence(input, output);
}
#[test]
fn a_property_declarations_local_variable_may_not_be_dropped() {
let input =
"module m;\n property p;\n realtime t;\n a |-> b;\n endproperty\nendmodule\n";
let output = "module m;\n property p;\n a |-> b;\n endproperty\nendmodule\n";
expect_divergence(input, output);
}
// ----------------------------------------------------------------------
// Split conditional regions (`docs/features/directive-split/README.md`)
//
// The recovery adds no forgiveness to the safety net -- verbatim bytes need
// none -- but the capture is forgiveness-*adjacent* in exactly the way the
// assertions above are: the block is re-lexed as ordinary tokens on both
// sides, so every token inside it must still match. These are the crafted
// (input, corrupted output) pairs CLAUDE.md's invariant #4 asks for, plus the
// legitimate transformation that keeps the rejections from being vacuous.
// ----------------------------------------------------------------------
/// The one shape all of these attack: alternative declaration heads sharing a
/// body (`riscv_core_setting.sv:98`).
fn split_region() -> String {
"`ifdef DSIM\nprivileged_reg_t csr[] = {\n`else\nconst privileged_reg_t csr[] = {\n\
`endif\n // vendor\n MVENDORID\n};\n"
.to_string()
}
#[test]
fn a_split_conditional_region_may_be_reindented() {
let input = format!("module m;\n{}endmodule\n", split_region());
let output = format_source(&input, &Config::default()).expect("must format");
verify_equivalence(&input, &output).expect("only indentation changed");
// ... and the second pass is a fixed point, which is what makes a
// verbatim block safe to re-indent at all.
let twice = format_source(&output, &Config::default()).expect("must format again");
verify_convergence(&output, &twice).expect("idempotent");
}
#[test]
fn a_dropped_arm_of_a_split_region_is_rejected() {
let input = split_region();
let output = "`ifdef DSIM\nprivileged_reg_t csr[] = {\n`endif\n // vendor\n MVENDORID\n};\n";
expect_divergence(&input, output);
}
#[test]
fn a_dropped_endif_of_a_split_region_is_rejected() {
let input = split_region();
let output = "`ifdef DSIM\nprivileged_reg_t csr[] = {\n`else\nconst privileged_reg_t csr[] = {\n // vendor\n MVENDORID\n};\n";
expect_divergence(&input, output);
}
#[test]
fn a_dropped_comment_inside_a_split_region_is_rejected() {
let input = split_region();
let output = "`ifdef DSIM\nprivileged_reg_t csr[] = {\n`else\nconst privileged_reg_t csr[] = {\n`endif\n MVENDORID\n};\n";
expect_divergence(&input, output);
}
#[test]
fn a_split_regions_arms_may_not_be_swapped() {
// Both arms are still there and the bytes still balance -- only which
// one the `else selects has changed, which is a semantic rewrite.
let input = split_region();
let output = "`ifdef DSIM\nconst privileged_reg_t csr[] = {\n`else\nprivileged_reg_t csr[] = {\n`endif\n // vendor\n MVENDORID\n};\n";
expect_divergence(&input, output);
}
#[test]
fn a_changed_ifdef_condition_is_rejected() {
let input = split_region();
let output = "`ifdef VCS\nprivileged_reg_t csr[] = {\n`else\nconst privileged_reg_t csr[] = {\n`endif\n // vendor\n MVENDORID\n};\n";
expect_divergence(&input, output);
}
#[test]
fn a_dropped_element_of_a_split_regions_shared_body_is_rejected() {
let input = "`ifdef DSIM\nint x[] = {\n`else\nconst int x[] = {\n`endif\n 1,\n 2\n};\n";
let output = "`ifdef DSIM\nint x[] = {\n`else\nconst int x[] = {\n`endif\n 1\n};\n";
expect_divergence(input, output);
}
#[test]
fn a_split_region_keeps_a_multiline_string_byte_for_byte() {
let input = "`ifdef DSIM\nstring x[] = {\n`else\nconst string x[] = {\n`endif\n \"line one\n line two indented\"\n};\n";
let output = format_source(input, &Config::default()).expect("must format");
assert!(
output.contains("\"line one\n line two indented\""),
"the string's bytes changed:\n{output}"
);
verify_equivalence(input, &output).expect("nothing but indentation moved");
}
/// QA repro (2026-08-26): a `` `endif `` with no region open is broken input,
/// not a split. Recovering it would have `format_source` accept and rewrite
/// invalid Verilog that a real toolchain rejects at preprocessing.
#[test]
fn a_stray_endif_next_to_an_open_bracket_is_refused_not_reformatted() {
for input in [
"int x[] = {\n`endif\n1\n};\n",
"module m;\n int x[] = {\n`endif\n 1\n};\nendmodule\n",
"module m;\n`ifdef FOO\n wire a;\n`endif\n`endif\n int x[] = {\n`else\n const int x[] = {\n`endif\n 1\n};\nendmodule\n",
] {
match format_source(input, &Config::default()) {
Err(FormatError::Source(e)) => {
assert!(e.to_string().contains('`'), "the directive is named: {e}");
}
Ok(out) => panic!("invalid input was accepted and rewritten as:\n{out}"),
Err(e) => panic!("expected a parse refusal, got {e}"),
}
}
}
/// QA repro (2026-08-26, round 4): an unbalanced `` `ifdef `` written inside a
/// construct lucisv keeps as opaque bytes must not leak into the file's
/// item-scope conditional nesting, where it would launder an unrelated stray
/// `` `endif `` into a split and get invalid input reformatted with exit 0.
#[test]
fn an_opaque_body_cannot_launder_a_stray_endif_into_a_split() {
for input in [
// constraint, covergroup, property: all three walk their bodies token
// by token to find their closer.
"class c;\n constraint co {\n`ifdef FAKE\n x < 10;\n }\nendclass\nint y[] = {\n`endif\n1\n};\n",
"covergroup cg;\n`ifdef FAKE\n cp: coverpoint x;\nendgroup\nint y[] = {\n`endif\n1\n};\n",
"module m;\n property p;\n`ifdef FAKE\n a |-> b;\n endproperty\n int y[] = {\n`endif\n1\n};\nendmodule\n",
// Control: the inner directive balanced. The tail is still stray.
"class c;\n constraint co {\n`ifdef FAKE\n x < 10;\n`endif\n }\nendclass\nint y[] = {\n`endif\n1\n};\n",
] {
match format_source(input, &Config::default()) {
Err(FormatError::Source(_)) => {}
Ok(out) => panic!("invalid input was accepted and rewritten as:\n{out}"),
Err(e) => panic!("expected a parse refusal, got {e}"),
}
}
}
/// Assert `format_source` refuses `input` with a verification error, i.e. the
/// safety net caught the layout and the caller keeps the original bytes.
fn expect_refusal(input: &str) {
match format_source(input, &Config::default()) {
Err(FormatError::Verification(_)) => {}
Ok(out) => panic!("expected a refusal, got:\n{out}"),
Err(e) => panic!("expected a verification refusal, got {e}"),
}
}
/// The header shapes `header_parens` deliberately does *not* cover, pinned as
/// clean refusals so a future round sees them move rather than appear.
///
/// `for` and `foreach` do not end their header in a single condition
/// expression, and a `do ... while (c);` has no body after its parentheses to
/// take the comment back from. All three still leave the file untouched.
#[test]
fn a_comment_in_a_for_foreach_or_do_while_header_is_still_refused() {
for input in [
"module m;\n initial begin\n for (int i = 0; i < 4; i++ // why\n ) begin\n y = 1;\n end\n end\nendmodule\n",
"module m;\n initial begin\n foreach (arr[i] // why\n ) begin\n y = 1;\n end\n end\nendmodule\n",
"module m;\n initial begin\n do begin\n y = 1;\n end while (c // why\n );\n end\nendmodule\n",
] {
expect_refusal(input);
}
}
/// The three bucket-2 shapes, formatted for real: every comment comes back
/// with its own text, none merged into the code that follows it, and the
/// second pass is a fixed point.
#[test]
fn the_repaired_comment_shapes_keep_every_comment_intact() {
for (input, kept, banned) in [
(
"module m;\n always_comb begin\n if (a) begin\n x = 1;\n end // addr_phase_write\n else if (b) begin\n x = 2;\n end\n end\nendmodule\n",
"// addr_phase_write",
"// addr_phase_write else",
),
(
"module m;\n always_comb begin\n if (// why not\n a || b) begin\n x = 1;\n end\n end\nendmodule\n",
"// why not",
") // why not",
),
(
"module m;\n always_comb begin\n if (a /* and here */) begin\n x = 1;\n end\n end\nendmodule\n",
"/* and here */",
") /* and here */",
),
] {
let out = format_source(input, &Config::default()).expect("formats cleanly");
assert!(out.contains(kept), "comment lost:\n{out}");
assert!(!out.contains(banned), "comment merged or moved:\n{out}");
let again = format_source(&out, &Config::default()).expect("formats again");
assert_eq!(out, again, "not idempotent");
}
}
/// Standing rule (`topo.md` §2.1): `verify.rs` was not widened for any of
/// these fixes, and the corruptions they used to produce must still be
/// rejected if a future layout change reintroduces them.
#[test]
fn the_bucket_two_corruptions_are_still_rejected() {
// A trailing line comment swallowing the `else if` that followed it.
expect_divergence(
"module m;\n always_comb begin\n if (a) begin\n x = 1;\n end // note\n else if (b) begin\n x = 2;\n end\n end\nendmodule\n",
"module m;\n always_comb begin\n if (a) begin\n x = 1;\n end // note else if (b) begin\n x = 2;\n end\n end\nendmodule\n",
);
// A comment written inside the condition, printed after the `)`.
expect_divergence(
"module m;\n always_comb begin\n if (// note\n a) begin\n x = 1;\n end\n end\nendmodule\n",
"module m;\n always_comb begin\n if (a) // note\n begin\n x = 1;\n end\n end\nendmodule\n",
);
// The `:` a `default;` did not write, invented by the printer.
expect_divergence(
"module m;\n always_comb begin\n case (s)\n A: y = 1;\n default;\n endcase\n end\nendmodule\n",
"module m;\n always_comb begin\n case (s)\n A: y = 1;\n default: ;\n endcase\n end\nendmodule\n",
);
// And its mirror: a `default: ;` losing the colon it did write.
expect_divergence(
"module m;\n always_comb begin\n case (s)\n A: y = 1;\n default: ;\n endcase\n end\nendmodule\n",
"module m;\n always_comb begin\n case (s)\n A: y = 1;\n default;\n endcase\n end\nendmodule\n",
);
}
/// A comment written just after a statement header's `(` is queued by the
/// parser and drained onto the first bracket it meets — so when the condition
/// started with a call, `CallComments::before_open` swallowed it and the
/// comment printed between the callee and its `(`. This was pinned as a
/// refusal until the directive-in-statements round delivered the parser's
/// `take_gap` fix (2026-08-29); the pin flips exactly as the Handshake said
/// it should: the shape now formats, the comment keeps its place inside the
/// parens, and the round trip is a fixed point. The last of bucket 2's 12.
#[test]
fn a_comment_before_a_call_in_a_condition_now_formats() {
let input = "module m;\n function automatic int f();\n if (// why\n !en() || b\n ) begin\n return 1;\n end\n endfunction\nendmodule\n";
let expected = "module m;\n function automatic int f();\n if (\n // why\n !en() || b\n ) begin\n return 1;\n end\n endfunction\nendmodule\n";
let config = Config::default();
let once = format_source(input, &config).expect("the delivered handshake formats this");
assert_eq!(once, expected, "the comment stays inside the parens");
let twice = format_source(&once, &config).expect("and the result still formats");
assert_eq!(twice, once, "fixed point");
}
/// The standing template applied to directive-in-statements' verbatim
/// capture (the round could not add these itself — this file was Lane B's
/// during the wave): crafted (input, corrupted output) pairs the capture
/// could plausibly produce if its extent scan slipped, each asserted
/// rejected. An `` `else `` arm dropped, the arms swapped, and the
/// `` `endif `` lost — every one is a divergence the safety net must see.
#[test]
fn a_corrupted_directive_capture_is_rejected() {
// The `` `else `` arm dropped from the captured region.
expect_divergence(
"module m;\n assign x =\n`ifdef A\n a;\n`else\n b;\n`endif\nendmodule\n",
"module m;\n assign x =\n`ifdef A\n a;\n`endif\nendmodule\n",
);
// The two arms swapped.
expect_divergence(
"module m;\n assign x =\n`ifdef A\n a;\n`else\n b;\n`endif\nendmodule\n",
"module m;\n assign x =\n`ifdef A\n b;\n`else\n a;\n`endif\nendmodule\n",
);
// The `` `endif `` lost, leaking the region into the module tail.
expect_divergence(
"module m;\n assign x =\n`ifdef A\n a;\n`else\n b;\n`endif\nendmodule\n",
"module m;\n assign x =\n`ifdef A\n a;\n`else\n b;\nendmodule\n",
);
}
/// QA (2026-08-29, Lane B): `trailing_ends_line` decides whether `end`'s
/// trailing comments swallow a cuddled `else` by checking whether the
/// *merged* trailing text starts with `//` (`is_line_comment` is a prefix
/// test). A block comment followed by a line comment on the same trailing
/// group — `end /* a */ // b` — merges into one string that starts with
/// `/*`, so the check says "does not end in a line comment" and `else` still
/// tries to cuddle, which does produce the merge this whole fix exists to
/// prevent. The safety net catches it (the reparsed output has one big
/// comment where the input had two), so the file is refused rather than
/// corrupted — this pins that it stays a safe refusal, not a fix for the
/// gap. If a later round teaches `trailing_ends_line` to look at the last
/// merged comment instead of the first, this test should flip to a `.cases`
/// entry the same way the parser handshake above is meant to.
#[test]
fn a_block_comment_merged_with_a_trailing_line_comment_before_else_is_still_refused() {
expect_refusal(
"module m;\n always_comb begin\n if (a) begin\n x = 1;\n end /* a */ // b\n else if (c) begin\n x = 2;\n end\n end\nendmodule\n",
);
}
// ----------------------------------------------------------------------
// The clocking wave's new verbatim capture: `default disable iff expr;`
// (`docs/features/clocking-wave/README.md`).
//
// It is copied out of the source by span and re-indented, exactly like
// `constraint` and a concurrent assertion, so the net must still see every
// token inside it. Per CLAUDE.md hard invariant #4 these are the attack
// pairs for that capture: **no normalization was added or widened for it**,
// and each pair below is a real change inside the captured bytes that the
// existing forgiveness could plausibly have masked (indentation, a moved
// line break, a dropped comment) — asserted rejected.
// ----------------------------------------------------------------------
#[test]
fn a_default_disable_iff_may_be_reindented() {
let input = "module m;\n default disable iff !rst_ni;\nendmodule\n";
let output = "module m;\n default disable iff !rst_ni;\nendmodule\n";
verify_equivalence(input, output).expect("only per-line indentation changed");
}
#[test]
fn a_changed_default_disable_condition_is_rejected() {
// The polarity of a disable condition is the difference between an
// assertion that runs in reset and one that does not.
expect_divergence(
"module m;\n default disable iff !rst_ni;\nendmodule\n",
"module m;\n default disable iff rst_ni;\nendmodule\n",
);
expect_divergence(
"module m;\n default disable iff a || !b;\nendmodule\n",
"module m;\n default disable iff a && !b;\nendmodule\n",
);
}
#[test]
fn a_dropped_default_disable_operand_is_rejected() {
expect_divergence(
"module m;\n default disable iff disable_sva || !rst_ni;\nendmodule\n",
"module m;\n default disable iff !rst_ni;\nendmodule\n",
);
}
#[test]
fn a_dropped_default_disable_item_is_rejected() {
expect_divergence(
"module m;\n default disable iff !rst_ni;\n wire w;\nendmodule\n",
"module m;\n wire w;\nendmodule\n",
);
}
#[test]
fn a_comment_inside_a_default_disable_may_not_be_dropped() {
expect_divergence(
"module m;\n default disable iff /* why */ !rst_ni;\nendmodule\n",
"module m;\n default disable iff !rst_ni;\nendmodule\n",
);
}
#[test]
fn a_default_disable_split_over_lines_may_not_lose_a_token() {
// The capture spans several source lines, so the line-break normalization
// is exactly what a masked corruption here would ride on.
expect_divergence(
"module m;\n default disable iff\n !rst_ni ||\n !en;\nendmodule\n",
"module m;\n default disable iff !rst_ni || en;\nendmodule\n",
);
}
#[test]
fn a_default_disable_carrying_a_dist_set_keeps_every_byte() {
// A `;` inside the set does not end the item, so the whole set is in the
// captured bytes — and a changed weight there must still be refused.
let input = "module m;\n default disable iff x dist {1 := 1, 2 := 2};\nendmodule\n";
let output = format_source(input, &Config::default()).expect("must format");
assert!(output.contains("dist {1 := 1, 2 := 2}"), "the set's bytes changed:\n{output}");
expect_divergence(
input,
"module m;\n default disable iff x dist {1 := 1, 2 := 9};\nendmodule\n",
);
}
// ----------------------------------------------------------------------
// Null items (`;` where an item belongs) — `docs/features/null-items/README.md`
//
// `verify.rs` was not widened for null items and needs no new forgiveness:
// a `;` is an ordinary token and the net compares token streams. These pairs
// are the standing attack tests anyway (CLAUDE.md invariant 4), one per way
// the layout rule could plausibly go wrong.
// ----------------------------------------------------------------------
#[test]
fn a_dropped_null_item_is_rejected() {
// What the `empty-item` lint's fix does deliberately, the formatter must
// never do silently — in either direction.
expect_divergence(
"module m;\n generate\n endgenerate;\nendmodule\n",
"module m;\n generate\n endgenerate\nendmodule\n",
);
expect_divergence(
"module m;\n wire a;\n ;;\nendmodule\n",
"module m;\n wire a;\n ;\nendmodule\n",
);
// And a `;` invented where the source wrote none.
expect_divergence(
"module m;\n generate\n endgenerate\nendmodule\n",
"module m;\n generate\n endgenerate;\nendmodule\n",
);
}
#[test]
fn a_null_item_moved_across_a_comment_is_rejected() {
// The glue prints a null item onto the previous item's line. A one-line
// block comment is the only comment that can stand in that gap, and the
// `;` must stay on the far side of it.
expect_divergence(
"module m;\n generate\n endgenerate /* b */ ;\nendmodule\n",
"module m;\n generate\n endgenerate; /* b */\nendmodule\n",
);
expect_divergence(
"module m;\n wire a;\n // why\n ;\nendmodule\n",
"module m;\n wire a;\n ;\n // why\nendmodule\n",
);
}
#[test]
fn a_null_item_moved_into_a_procedural_block_is_rejected() {
// An item-level `;` and a procedural null statement print identically, so
// nothing but token order tells the net that one became the other.
expect_divergence(
"module m;\n initial begin\n x = 1;\n end\n ;\nendmodule\n",
"module m;\n initial begin\n x = 1;\n ;\n end\nendmodule\n",
);
expect_divergence(
"module m;\n generate\n ;\n endgenerate\nendmodule\n",
"module m;\n generate\n endgenerate;\nendmodule\n",
);
}
// QA addition (2026-09-01): the item list is flat across `` `ifdef ``/``
// `else ``/`` `endif `` — a null item inside one arm is a sibling of the
// `Directive` items, not nested under them — so a corruption that carries a
// null item from one arm to the other is a plain token-stream reorder around
// a `Directive` token rather than around an ordinary item. Confirmed rejected
// (checklist item 4's suggested gap; `verify.rs`'s comparison is positional
// and directive-token-agnostic, so this was expected to hold, not a bug).
#[test]
fn a_null_item_moved_from_one_ifdef_arm_to_the_other_is_rejected() {
expect_divergence(
"module m;\n`ifdef A\n ;\n`else\n wire x;\n`endif\nendmodule\n",
"module m;\n`ifdef A\n`else\n wire x;\n ;\n`endif\nendmodule\n",
);
}
// ----------------------------------------------------------------------
// Escaped identifiers (2026-09-02)
// ----------------------------------------------------------------------
//
// An escaped identifier is ended by whitespace and by nothing else (IEEE
// 1800-2017 §5.6.1), so dropping the space the formatter writes after one
// does not just move layout around: the next character is swallowed into the
// name and the token stream changes shape. These are the corruptions the
// choke point in `format.rs` exists to prevent, asserted rejected — the net
// is what stands behind it if a name emission is ever added without going
// through `named`.
#[test]
fn a_semicolon_glued_onto_an_escaped_name_is_rejected() {
// The original bug: `wire \my-signal ;` printed as `wire \my-signal;`,
// whose second token is the identifier `\my-signal;`.
expect_divergence(
"module m;\n wire \\my-signal ;\nendmodule\n",
"module m;\n wire \\my-signal;\nendmodule\n",
);
// The same glue one scope down, where a class body's declaration is laid
// out by a different path than a module item's.
expect_divergence("class c;\n int \\fld ;\nendclass\n", "class c;\n int \\fld;\nendclass\n");
}
#[test]
fn a_connection_that_loses_the_space_before_its_paren_is_rejected() {
// `.\my-port (x)` is three tokens; `.\my-port(x)` is two, the second one
// being the identifier `\my-port(x)` — the whole connection eaten.
expect_divergence(
"module m;\n sub u0 (.\\my-port (x));\nendmodule\n",
"module m;\n sub u0 (.\\my-port(x));\nendmodule\n",
);
}
#[test]
fn two_escaped_names_merged_into_one_are_rejected() {
// `\a \b` are two identifiers; `\a\b` is one.
expect_divergence(
"module m;\n wire \\a \\b ;\nendmodule\n",
"module m;\n wire \\a\\b ;\nendmodule\n",
);
// And the instance-name form of the same merge.
expect_divergence(
"module m;\n \\sub-mod \\u-0 ();\nendmodule\n",
"module m;\n \\sub-mod\\u-0 ();\nendmodule\n",
);
}
#[test]
fn an_escaped_label_glued_to_what_follows_it_is_rejected() {
// A block label shares its line with the first statement, so the
// terminator is the only thing between `\blk` and `x`.
expect_divergence(
"module m;\n initial begin : \\blk x = 1; end\nendmodule\n",
"module m;\n initial begin : \\blkx = 1; end\nendmodule\n",
);
// An end label is terminated by the line break; a layout that folds the
// next keyword onto its line without a space swallows the keyword.
expect_divergence(
"module m;\n initial begin : \\blk\n end : \\blk\nendmodule\n",
"module m;\n initial begin : \\blk\n end : \\blkendmodule\n",
);
}
#[test]
fn the_terminating_space_itself_is_only_whitespace() {
// The flip side: writing the space (or two, where the layout also writes
// one) is a whitespace-only difference, which is what lets the formatter
// add it at all.
verify_equivalence(
"module m;wire \\a ;assign \\a =\\b ;endmodule",
"module m;\n wire \\a ;\n assign \\a = \\b ;\nendmodule\n",
)
.expect("only whitespace between the same tokens");
}
#[test]
fn a_space_dropped_before_a_scope_operator_is_rejected() {
// `join_paths` writes `named(pkg) + "::" + named(item)`; if that first
// `named` call were ever lost, `\a-pkg ::\b-item` (three tokens) would
// print as `\a-pkg::\b-item` — one token, since `::` is not whitespace
// and so does not terminate the escaped name on its own. QA-added
// (2026-09-02): no existing pair attacked this specific position.
expect_divergence(
"package p;\n import \\a-pkg ::\\b-item ;\nendpackage\n",
"package p;\n import \\a-pkg::\\b-item ;\nendpackage\n",
);
}
#[test]
fn an_escaped_name_in_a_scoped_type_is_rejected_rather_than_corrupted() {
// `\my-pkg ::\state-t` is joined into one string by `parse_scoped_name`,
// so the formatter reprints it without the space it cannot know was
// there. The net catches it: an error, never a corrupted file. See the
// Handshakes section of docs/features/escaped-identifiers/README.md.
let src = "module m;\n \\my-pkg ::\\state-t \\st ;\nendmodule\n";
match format_source(src, &Config::default()) {
Err(FormatError::Verification(_)) => {}
other => panic!("expected the net to reject the scoped name, got {other:?}"),
}
}
#[test]
fn escaped_identifiers_survive_a_real_format_run() {
let src = "module \\my-mod (input logic \\a-in , output \\b-out );\n\
wire \\my-signal ;\n\
assign \\b-out = \\my-signal & \\a-in ;\n\
sub \\u-0 (.\\p-in (\\my-signal ), .b(1'b0));\n\
endmodule : \\my-mod\n";
let out = format_source(src, &Config::default()).expect("escaped identifiers format");
assert!(out.contains("wire \\my-signal ;"), "{out}");
assert!(out.contains(".\\p-in (\\my-signal )"), "{out}");
// A name that ends the line needs no space: the newline terminates it,
// and the printer trims the trailing space it was given.
assert!(out.ends_with("endmodule : \\my-mod\n"), "{out}");
assert!(!out.contains(" \n"), "no trailing whitespace: {out}");
}
// ----------------------------------------------------------------------
// The covergroup gap fuzzer
//
// A comment the AST does not keep is a comment the formatter cannot print,
// and `format_source`'s own token check then refuses the whole file — hard
// invariant #3 by way of #1. Guessing at a list of slots is how the seventh
// one ships, so `covergroup-bodies` asked the question exhaustively from day
// one, the way `constraint-bodies` learned to after its QA rework: put a
// `/*C*/` in **every** inter-token gap of every fixture and demand
// `format_source` succeed and be idempotent for each.
//
// See `docs/features/covergroup-bodies/README.md` for the classification of
// the gaps that still fail: every one of them is in shared name or expression
// machinery that fails identically outside a covergroup, filed as
// `docs/topo.md` §2.9-22.
// ----------------------------------------------------------------------
/// The covergroup sub-grammar, comment-free, one shape per fixture.
const COVERGROUP_FIXTURES: &[&str] = &[
"class c;\n covergroup cg;\n coverpoint a;\n endgroup\nendclass\n",
"class c;\n covergroup cg (bit [3:0] a, int n) with function sample (bit [31:0] addr);\n cp: coverpoint addr;\n endgroup : cg\nendclass\n",
"module m;\n covergroup cg @(posedge clk);\n coverpoint x;\n endgroup\nendmodule\n",
"class c;\n covergroup cg;\n cp: coverpoint a iff (en) {\n wildcard bins w[4] = {4'b1??1};\n ignore_bins ig = {2, 3};\n illegal_bins bad = default;\n }\n endgroup\nendclass\n",
"class c;\n covergroup cg;\n cp: coverpoint a {\n bins seq = default sequence;\n bins t = (0 => 1, 2 => 3), (4 => 5);\n }\n endgroup\nendclass\n",
"class c;\n covergroup cg;\n cp: coverpoint a {\n bins r = (1'b0[*1:10] => 1'b1[->2] => 1'b0[=1]);\n }\n endgroup\nendclass\n",
"class c;\n covergroup cg;\n cr: cross cp_a, cp_b {\n bins sel = binsof(cp_a) intersect {0, [1:2]} && !binsof(cp_b);\n }\n endgroup\nendclass\n",
"class c;\n covergroup cg;\n option.per_instance = 1;\n type_option.weight = 5;\n coverpoint x;\n endgroup\nendclass\n",
"class c;\n covergroup cg;\n cp: coverpoint a {\n bins e[] = cp_x with (item % 2 == 0);\n bins v = {[0:$]} iff (en);\n }\n endgroup\nendclass\n",
"class c;\n local covergroup cg;\n cp: coverpoint a;\n cr: cross a, b;\n ;\n endgroup : cg;\nendclass\n",
];
/// Every byte offset a comment may be written at: the start of each token,
/// plus the end of the last one.
fn gaps(src: &str) -> Vec<usize> {
let tokens = vlog_parser::tokenize(src).expect("the fixture lexes");
let mut out: Vec<usize> = Vec::new();
let mut last = 0usize;
for t in &tokens {
if t.text.is_empty() && t.span.start == t.span.end {
continue;
}
out.push(t.span.start as usize);
last = t.span.end as usize;
}
out.push(last);
out.sort_unstable();
out.dedup();
out
}
/// The fixtures with a `/*C*/` in one gap each, and whether that one formats
/// and round-trips.
fn failing_gaps() -> Vec<String> {
let mut failed = Vec::new();
for src in COVERGROUP_FIXTURES {
for at in gaps(src) {
let mut probed = String::with_capacity(src.len() + 8);
probed.push_str(&src[..at]);
probed.push_str(" /*C*/ ");
probed.push_str(&src[at..]);
let ok = match format_source(&probed, &Config::default()) {
Ok(out) => format_source(&out, &Config::default()).is_ok_and(|two| two == out),
Err(_) => false,
};
if !ok {
failed.push(format!("{:?} … {:?}", &probed[..at + 7], &probed[at + 7..]));
}
}
}
failed
}
#[test]
fn a_comment_in_every_covergroup_gap_still_formats() {
let total: usize = COVERGROUP_FIXTURES.iter().map(|s| gaps(s).len()).sum();
let failed = failing_gaps();
// The bar, stated out loud: of the fixtures' inter-token gaps, exactly
// these fail, every one of them in shared machinery that fails
// identically outside a covergroup (`docs/topo.md` §2.9-22) — the
// qualifier run, `[` index expressions, `class`/`package` headers,
// declarator dimensions and `parse_value_range`. A change that adds one
// fails here with the offending source printed.
assert_eq!(
(total, failed.len()),
(EXPECTED_GAPS, EXPECTED_FAILING_GAPS),
"the covergroup gap fuzzer moved:\n{}",
failed.join("\n")
);
}
/// Inter-token gaps across [`COVERGROUP_FIXTURES`].
const EXPECTED_GAPS: usize = 329;
/// How many of them a `/*C*/` still breaks. Every one is classified by
/// [`shared_machinery_analogues`], whose sources are the same slots written
/// **outside** a covergroup — and which fail identically there:
///
/// | shape | n | owner |
/// |---|---|---|
/// | `class /*C*/ c` / `class c /*C*/ ;` | 18 | the class header |
/// | `module /*C*/ m` / `module m /*C*/ ;` | 2 | the module header |
/// | a `tf_port_list` type, its dimensions and its name | 13 | `parse_tf_ports` |
/// | `endgroup /*C*/ : g` / `endgroup : /*C*/ g` | 4 | `parse_label` |
/// | `@ /*C*/ (` / `@(posedge /*C*/ clk)` | 2 | `parse_sens_list` |
/// | `[ /*C*/ 0 : 3 /*C*/ ]` | 8 | `parse_value_range` |
/// | `option /*C*/ . /*C*/ per_instance` | 4 | member expressions |
/// | `local /*C*/ covergroup` | 1 | `take_member_prefix` |
const EXPECTED_FAILING_GAPS: usize = 52;
/// The same slots, written outside any covergroup.
///
/// Every one of them is a *pre-existing* comment-drop in shared name,
/// declaration or expression machinery — `docs/topo.md` §2.9-22 — and none of
/// it is this round's to fix. This test is the classification, written down:
/// if one of these starts working, the fuzzer's count above moves in the same
/// commit, and both are updated together.
const SHARED_MACHINERY_ANALOGUES: &[(&str, &str)] = &[
(
"class /*C*/ c",
"class /*C*/ c;
endclass
",
),
(
"class c /*C*/ ;",
"class c /*C*/ ;
endclass
",
),
(
"module /*C*/ m",
"module /*C*/ m;
endmodule
",
),
(
"module m /*C*/ ;",
"module m /*C*/ ;
endmodule
",
),
(
"a tf port's type",
"class c;
function void f(bit /*C*/ [3:0] a);
endfunction
endclass
",
),
(
"a tf port's dimension",
"class c;
function void f(bit [ /*C*/ 3:0] a);
endfunction
endclass
",
),
(
"a tf port's name",
"class c;
function void f(bit [3:0] /*C*/ a);
endfunction
endclass
",
),
(
"an untyped tf port's name",
"class c;
function void f(int /*C*/ n);
endfunction
endclass
",
),
(
"endfunction /*C*/ : f",
"class c;
function void f();
endfunction /*C*/ : f
endclass
",
),
(
"endfunction : /*C*/ f",
"class c;
function void f();
endfunction : /*C*/ f
endclass
",
),
(
"always @ /*C*/ (",
"module m;
always @ /*C*/ (posedge clk) x <= 1;
endmodule
",
),
(
"always @(posedge /*C*/ clk)",
"module m;
always @(posedge /*C*/ clk) x <= 1;
endmodule
",
),
(
"a value range's open",
"module m;
assign y = a inside {[ /*C*/ 0:3]};
endmodule
",
),
(
"a value range's colon",
"module m;
assign y = a inside {[0 /*C*/ :3]};
endmodule
",
),
(
"a value range's close",
"module m;
assign y = a inside {[0:3 /*C*/ ]};
endmodule
",
),
(
"a member access's dot",
"module m;
assign y = a /*C*/ .b;
endmodule
",
),
(
"a member access's name",
"module m;
assign y = a. /*C*/ b;
endmodule
",
),
(
"a member qualifier run",
"class c;
local /*C*/ function void f();
endfunction
endclass
",
),
];
#[test]
fn the_gaps_the_fuzzer_still_fails_fail_outside_a_covergroup_too() {
let working: Vec<&str> = SHARED_MACHINERY_ANALOGUES
.iter()
.filter(|(_, src)| {
format_source(src, &Config::default())
.is_ok_and(|out| format_source(&out, &Config::default()).is_ok_and(|t| t == out))
})
.map(|(name, _)| *name)
.collect();
assert!(
working.is_empty(),
"these shared-machinery slots now keep their comment, so the covergroup \
fuzzer's expected count above is stale: {working:?}"
);
}
// ----------------------------------------------------------------------
// Fragment files — `docs/features/fragment-mode/README.md`
//
// `verify.rs` was not widened for fragments and needs no new forgiveness: a
// fragment's statements, enum members and cover items are ordinary tokens and
// the net compares token streams. These pairs are the standing attack tests
// anyway (CLAUDE.md invariant 4), one per way the new printing path could
// plausibly lose or move something — and the fragment path is the one place in
// the formatter where a whole *file* is laid out by a body printer, so a
// dropped element has no enclosing construct to make it obvious.
// ----------------------------------------------------------------------
#[test]
fn a_dropped_statement_in_a_fragment_is_rejected() {
expect_divergence("a = 1;\nb = 2;\nc = 3;\n", "a = 1;\nc = 3;\n");
// And a statement invented where the source wrote none.
expect_divergence("a = 1;\n", "a = 1;\nb = 2;\n");
}
#[test]
fn a_reordered_enum_member_is_rejected() {
expect_divergence("A,\nB,\nC\n", "A,\nC,\nB\n");
expect_divergence("A = 1,\nB = 2\n", "B = 2,\nA = 1\n");
}
#[test]
fn a_dropped_trailing_comma_in_an_enum_fragment_is_rejected() {
// The whole point of the riscv-dv fragment: the `,` is what splices it
// into the member list around it, so losing it changes the file's meaning
// at the include site even though the fragment still "looks right".
expect_divergence(
"// TODO: Add custom instruction name enum\nCUSTOM_1,\n",
"// TODO: Add custom instruction name enum\nCUSTOM_1\n",
);
// And one invented where the source wrote none.
expect_divergence("CUSTOM_1\n", "CUSTOM_1,\n");
}
#[test]
fn a_comment_moved_across_an_enum_fragments_members_is_rejected() {
expect_divergence("// about A\nA,\nB\n", "A,\n// about A\nB\n");
expect_divergence("A, // about A\nB\n", "A,\nB // about A\n");
// A comment dropped outright, which is what a fragment printer that
// forgot `SourceFile::dangling` would do.
expect_divergence("A,\nB\n// tail\n", "A,\nB\n");
}
#[test]
fn a_dropped_cover_item_in_a_fragment_is_rejected() {
expect_divergence(
"cp_a: coverpoint a;\ncp_b: coverpoint b;\nx: cross cp_a, cp_b;\n",
"cp_a: coverpoint a;\nx: cross cp_a, cp_b;\n",
);
// A coverpoint's label dropped: the one name the fragment declares.
expect_divergence("cp_a: coverpoint a;\n", "coverpoint a;\n");
}
#[test]
fn an_enum_member_turned_into_a_statement_is_rejected() {
// The three shapes print the same names with different punctuation, so
// the one corruption a mis-classified fragment could produce is a `,`
// becoming a `;` or the other way round.
expect_divergence("A,\nB\n", "A;\nB\n");
expect_divergence("a = 1;\nb = 2;\n", "a = 1,\nb = 2\n");
}
// ----------------------------------------------------------------------
// The fragment gap fuzzer
//
// The same exhaustive question `covergroup-bodies` asked of its sub-grammar,
// asked of the three fragment shapes: a `/*C*/` in **every** inter-token gap
// of every fixture, and `format_source` must succeed and be idempotent for
// each. A fragment is printed by a body printer with no construct around it,
// so a comment slot the enclosing construct used to absorb has nowhere to go
// here — which is exactly the failure this catches.
// ----------------------------------------------------------------------
/// One fixture per fragment shape and per feature inside it, comment-free.
const FRAGMENT_FIXTURES: &[&str] = &[
"// TODO: Add custom instruction name enum\nCUSTOM_1,\n",
"A,\nB = 2,\nC\n",
"ReqPeriResetIdx[0:1],\nOtbnDmem[16]\n",
"`ifdef ADD_CUSTOM\nCUSTOM_1,\n`endif\nLAST\n",
"a = 1;\nb <= 2;\nfoo(x, y);\n",
"if (a) begin\n x = 1;\nend else begin\n x = 2;\nend\n",
"foreach (q[i]) begin\n q[i] = i;\nend\n",
"@(posedge clk) x <= y;\n#10 z = 1;\n",
"cp_a: coverpoint a;\ncp_b: coverpoint b;\nx_ab: cross cp_a, cp_b;\n",
"cp_addr: coverpoint addr {\n bins lo = {[0:9]};\n bins hi = {[10:$]};\n}\n",
"option.per_instance = 1;\ncoverpoint x;\n",
];
/// The fragment fixtures with a `/*C*/` in one gap each, and whether that one
/// formats and round-trips.
fn failing_fragment_gaps() -> Vec<String> {
let mut failed = Vec::new();
for src in FRAGMENT_FIXTURES {
for at in gaps(src) {
let mut probed = String::with_capacity(src.len() + 8);
probed.push_str(&src[..at]);
probed.push_str(" /*C*/ ");
probed.push_str(&src[at..]);
let ok = match format_source(&probed, &Config::default()) {
Ok(out) => format_source(&out, &Config::default()).is_ok_and(|two| two == out),
Err(_) => false,
};
if !ok {
failed.push(format!("{:?} … {:?}", &probed[..at + 7], &probed[at + 7..]));
}
}
}
failed
}
#[test]
fn a_comment_in_every_fragment_gap_still_formats() {
let total: usize = FRAGMENT_FIXTURES.iter().map(|s| gaps(s).len()).sum();
let failed = failing_fragment_gaps();
assert_eq!(
(total, failed.len()),
(EXPECTED_FRAGMENT_GAPS, EXPECTED_FAILING_FRAGMENT_GAPS),
"the fragment gap fuzzer moved:\n{}",
failed.join("\n")
);
}
/// Inter-token gaps across [`FRAGMENT_FIXTURES`].
const EXPECTED_FRAGMENT_GAPS: usize = 153;
/// How many of them a `/*C*/` still breaks. Every one is in shared name,
/// expression or statement machinery that fails identically *inside* a module
/// or a package — [`FRAGMENT_ANALOGUES`] is the same slot written there, and
/// [`the_gaps_the_fragment_fuzzer_fails_fail_outside_a_fragment_too`] proves
/// it rather than asserting it. Nothing here is fragment-specific; the whole
/// set is `docs/topo.md` §2.9-22, which `covergroup-bodies` opened.
const EXPECTED_FAILING_FRAGMENT_GAPS: usize = 41;
/// One entry per class of gap [`failing_fragment_gaps`] still reports, written
/// where the same construct stands inside an ordinary file.
const FRAGMENT_ANALOGUES: &[(&str, &str)] = &[
("an enum member's `=`", "package p;\n typedef enum {A, B /*C*/ = 2} e_t;\nendpackage\n"),
("an enum member's value", "package p;\n typedef enum {A, B = /*C*/ 2} e_t;\nendpackage\n"),
("an enum name range's `[`", "package p;\n typedef enum {A /*C*/ [0:1]} e_t;\nendpackage\n"),
("inside an enum name range", "package p;\n typedef enum {A[ /*C*/ 0:1]} e_t;\nendpackage\n"),
("a name range's `:`", "package p;\n typedef enum {A[0 /*C*/ :1]} e_t;\nendpackage\n"),
("a name range's close", "package p;\n typedef enum {A[0:1 /*C*/ ]} e_t;\nendpackage\n"),
("the gap before a statement's `;`", "module m;\n initial x = 1 /*C*/ ;\nendmodule\n"),
("a statement keyword's `(`", "module m;\n initial if /*C*/ (a) x = 1;\nendmodule\n"),
("a `foreach` header's `(`", "module m;\n initial foreach /*C*/ (q[i]) x = 1;\nendmodule\n"),
("inside a `foreach` header", "module m;\n initial foreach ( /*C*/ q[i]) x = 1;\nendmodule\n"),
("an index expression's `[`", "module m;\n initial q /*C*/ [i] = 1;\nendmodule\n"),
("inside an index expression", "module m;\n initial q[ /*C*/ i] = 1;\nendmodule\n"),
("an event control's `@`", "module m;\n always @ /*C*/ (posedge clk) x <= y;\nendmodule\n"),
("an edge keyword", "module m;\n always @(posedge /*C*/ clk) x <= y;\nendmodule\n"),
("a delay control's `#`", "module m;\n initial # /*C*/ 10 x = 1;\nendmodule\n"),
("a member chain's `.`", "module m;\n initial a /*C*/ .b = 1;\nendmodule\n"),
("after a member chain's `.`", "module m;\n initial a. /*C*/ b = 1;\nendmodule\n"),
(
"a value range inside a bin",
"class c;\n covergroup cg;\n cp: coverpoint a {\n bins lo = {[ /*C*/ 0:9]};\n }\n endgroup\nendclass\n",
),
];
#[test]
fn the_gaps_the_fragment_fuzzer_fails_fail_outside_a_fragment_too() {
let working: Vec<&str> = FRAGMENT_ANALOGUES
.iter()
.filter(|(_, src)| {
format_source(src, &Config::default())
.is_ok_and(|out| format_source(&out, &Config::default()).is_ok_and(|t| t == out))
})
.map(|(name, _)| *name)
.collect();
assert!(
working.is_empty(),
"these shared-machinery slots now keep their comment, so the fragment \
fuzzer's expected count above is stale: {working:?}"
);
}