From 6b95d772f16083bed78025842d112e95967145ce Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Tue, 18 Aug 2026 23:38:58 -0700 Subject: [PATCH] Add case-tables: Verible-style text-in/text-out test suite MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 183 {input, expected} cases across 10 construct files under tests/cases/, driven by a ~180-line std-only harness (==== / ---- format). Each case asserts formatting and idempotency; #SKIP parks known formatter bugs and fails the suite once they start passing. Documents four real formatter bugs found while deriving expected output (block-comment re-indent non-idempotency, comment lifted out of expression groups, closing block labels dropped, multi-instance declaration layout) — parked as #SKIP, to be fixed in a follow-up feature. Also adds rustfmt.toml matching the codebase style. Dev: Opus agent; QA: Sonnet agent; review in docs/features/case-tables/README.md. Co-Authored-By: Claude Fable 5 --- crates/vlog_formatter/tests/cases.rs | 192 +++++++ .../tests/cases/assignments.cases | 178 +++++++ .../vlog_formatter/tests/cases/comments.cases | 312 ++++++++++++ .../tests/cases/declarations.cases | 197 ++++++++ .../tests/cases/expressions.cases | 271 ++++++++++ .../tests/cases/functions_tasks.cases | 227 +++++++++ .../vlog_formatter/tests/cases/generate.cases | 219 ++++++++ .../tests/cases/instantiation.cases | 181 +++++++ .../tests/cases/module_headers.cases | 139 +++++ .../tests/cases/statements.cases | 475 ++++++++++++++++++ .../vlog_formatter/tests/cases/typedef.cases | 176 +++++++ docs/features/case-tables/README.md | 448 +++++++++++++++++ rustfmt.toml | 1 + 13 files changed, 3016 insertions(+) create mode 100644 crates/vlog_formatter/tests/cases.rs create mode 100644 crates/vlog_formatter/tests/cases/assignments.cases create mode 100644 crates/vlog_formatter/tests/cases/comments.cases create mode 100644 crates/vlog_formatter/tests/cases/declarations.cases create mode 100644 crates/vlog_formatter/tests/cases/expressions.cases create mode 100644 crates/vlog_formatter/tests/cases/functions_tasks.cases create mode 100644 crates/vlog_formatter/tests/cases/generate.cases create mode 100644 crates/vlog_formatter/tests/cases/instantiation.cases create mode 100644 crates/vlog_formatter/tests/cases/module_headers.cases create mode 100644 crates/vlog_formatter/tests/cases/statements.cases create mode 100644 crates/vlog_formatter/tests/cases/typedef.cases create mode 100644 docs/features/case-tables/README.md create mode 100644 rustfmt.toml diff --git a/crates/vlog_formatter/tests/cases.rs b/crates/vlog_formatter/tests/cases.rs new file mode 100644 index 0000000..d420b3b --- /dev/null +++ b/crates/vlog_formatter/tests/cases.rs @@ -0,0 +1,192 @@ +//! Table tests: every `tests/cases/*.cases` file holds a list of small +//! `{input, expected}` pairs, in the spirit of Verible's `formatter_test.cc`. +//! Cases are separated by a `====` line, input from expected by a `----` line, +//! and `#` lines at the top of a case name it. A case named `#SKIP ...` is +//! parsed but not asserted, so known-bad behavior can be recorded without +//! breaking the suite. Full format spec: `docs/features/case-tables/README.md`. + +use std::path::{Path, PathBuf}; + +use vlog_formatter::{format_source, Config}; + +/// One `{input, expected}` pair with the source location it came from. +struct Case { + name: String, + line: usize, + input: String, + expected: String, + skip: bool, +} + +fn cases_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/cases") +} + +/// Splits one `.cases` file into cases; returns an error string on bad syntax. +fn parse_cases(path: &Path, text: &str) -> Result, String> { + let file = path.file_name().unwrap_or_default().to_string_lossy(); + let mut cases = Vec::new(); + let mut start = 1usize; + let mut block: Vec<&str> = Vec::new(); + // A synthetic terminator lets the last case close like every other one. + for (idx, line) in text.lines().chain(std::iter::once("====")).enumerate() { + if line.trim_end() != "====" { + if block.is_empty() { + start = idx + 1; + } + block.push(line); + } else { + if block.iter().any(|l| !l.trim().is_empty()) { + cases.push(split_case(&file, start, &block)?); + } + block.clear(); + } + } + Ok(cases) +} + +/// Splits one case block into header comments, input and expected output. +fn split_case(file: &str, start: usize, block: &[&str]) -> Result { + let mut name = String::new(); + let mut skip = false; + let mut body = block; + while let Some(first) = body.first() { + if !first.starts_with('#') && !first.trim().is_empty() { + break; + } + if let Some(rest) = first.strip_prefix('#') { + if rest.trim_start().starts_with("SKIP") { + skip = true; + } + if !name.is_empty() { + name.push(' '); + } + name.push_str(rest.trim()); + } + body = &body[1..]; + } + let sep = body + .iter() + .position(|l| l.trim_end() == "----") + .ok_or_else(|| format!("{file}:{start}: case has no `----` separator"))?; + if name.is_empty() { + name = format!(""); + } + Ok(Case { + name, + line: start, + input: join(&body[..sep]), + expected: join(&body[sep + 1..]), + skip, + }) +} + +/// Rejoins lines into a source string with a trailing newline (empty stays empty). +fn join(lines: &[&str]) -> String { + let mut out = String::new(); + for line in lines { + out.push_str(line); + out.push('\n'); + } + out +} + +/// True if the case would pass both assertions today. +fn passes(case: &Case, config: &Config) -> bool { + match format_source(&case.input, config) { + Ok(once) if once == case.expected => { + matches!(format_source(&case.expected, config), Ok(twice) if twice == case.expected) + } + _ => false, + } +} + +/// Renders expected vs actual as a line-oriented diff. +fn diff(expected: &str, got: &str) -> String { + let (e, g): (Vec<_>, Vec<_>) = (expected.lines().collect(), got.lines().collect()); + let mut out = String::new(); + for i in 0..e.len().max(g.len()) { + match (e.get(i), g.get(i)) { + (Some(a), Some(b)) if a == b => out.push_str(&format!(" {a}\n")), + (a, b) => { + if let Some(a) = a { + out.push_str(&format!(" - {a}\n")); + } + if let Some(b) = b { + out.push_str(&format!(" + {b}\n")); + } + } + } + } + out +} + +#[test] +fn case_tables() { + let config = Config::default(); + let mut files: Vec = std::fs::read_dir(cases_dir()) + .expect("cases dir") + .map(|e| e.expect("dir entry").path()) + .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("cases")) + .collect(); + files.sort(); + assert!(!files.is_empty(), "no .cases files found"); + + let mut failures = Vec::new(); + let mut total = 0usize; + for path in &files { + let text = std::fs::read_to_string(path).expect("read cases file"); + let file = path.file_name().unwrap().to_string_lossy().to_string(); + let cases = match parse_cases(path, &text) { + Ok(c) => c, + Err(e) => { + failures.push(e); + continue; + } + }; + for case in cases { + let at = format!("{file}:{} [{}]", case.line, case.name); + if case.skip { + // A #SKIP case documents a known bug: it must still fail. + // The moment it passes, demand the marker's removal so the + // case becomes a live regression test. + if passes(&case, &config) { + failures.push(format!( + "{at}: marked #SKIP but now passes — remove the #SKIP marker" + )); + } + continue; + } + total += 1; + let once = match format_source(&case.input, &config) { + Ok(o) => o, + Err(e) => { + failures.push(format!("{at}: format failed: {e}")); + continue; + } + }; + if once != case.expected { + failures.push(format!( + "{at}: output differs from expected\n{}", + diff(&case.expected, &once) + )); + continue; + } + match format_source(&case.expected, &config) { + Ok(twice) if twice == case.expected => {} + Ok(twice) => failures.push(format!( + "{at}: not idempotent\n{}", + diff(&case.expected, &twice) + )), + Err(e) => failures.push(format!("{at}: reformatting output failed: {e}")), + } + } + } + assert!(total > 0, "no cases found"); + assert!( + failures.is_empty(), + "{} of {total} cases failed:\n\n{}", + failures.len(), + failures.join("\n") + ); +} diff --git a/crates/vlog_formatter/tests/cases/assignments.cases b/crates/vlog_formatter/tests/cases/assignments.cases new file mode 100644 index 0000000..06b1490 --- /dev/null +++ b/crates/vlog_formatter/tests/cases/assignments.cases @@ -0,0 +1,178 @@ +# continuous assignment +module m; +assign y=a&b; +endmodule +---- +module m; + assign y = a & b; +endmodule +==== +# continuous assignment with a delay +module m; +assign #3 y = a; +endmodule +---- +module m; + assign #3 y = a; +endmodule +==== +# continuous assignment to a bit select and a slice +module m; +assign y[0] = a; +assign y[7:4] = b; +endmodule +---- +module m; + assign y[0] = a; + assign y[7:4] = b; +endmodule +==== +# several assignments in one statement +module m; +assign a = 1'b0, b = 1'b1; +endmodule +---- +module m; + assign a = 1'b0, b = 1'b1; +endmodule +==== +# blocking and non-blocking assignments +module m; +always @(posedge clk) begin +q<=d; +tmp=d; +end +endmodule +---- +module m; + always @(posedge clk) begin + q <= d; + tmp = d; + end +endmodule +==== +# assignment operators +module m; +always_comb begin +a += 1; +b -= 2; +c *= 3; +d <<= 1; +e |= mask; +end +endmodule +---- +module m; + always_comb begin + a += 1; + b -= 2; + c *= 3; + d <<= 1; + e |= mask; + end +endmodule +==== +# increment and decrement +module m; +always_comb begin +i++; +j--; +end +endmodule +---- +module m; + always_comb begin + i++; + j--; + end +endmodule +==== +# assignment with an intra-assignment delay +module m; +always begin +#5 q = d; +q <= #2 d; +end +endmodule +---- +module m; + always begin + #5 q = d; + q <= #2 d; + end +endmodule +==== +# assignment with an intra-assignment event control +module m; +always begin +q = @(posedge clk) d; +end +endmodule +---- +module m; + always begin + q = @(posedge clk) d; + end +endmodule +==== +# long right-hand side wraps under the assignment +module m; +assign result_signal_name = first_operand_name + second_operand_name + third_operand_name + fourth; +endmodule +---- +module m; + assign result_signal_name = + first_operand_name + second_operand_name + third_operand_name + fourth; +endmodule +==== +# non-blocking assignment of a concatenation +module m; +always_ff @(posedge clk) begin +{carry, sum} <= a + b; +end +endmodule +---- +module m; + always_ff @(posedge clk) begin + {carry, sum} <= a + b; + end +endmodule +==== +# assign of a ternary +module m; +assign y = sel ? a : b; +endmodule +---- +module m; + assign y = sel ? a : b; +endmodule +==== +# force and release +module m; +initial begin +force net = 1'b1; +release net; +end +endmodule +---- +module m; + initial begin + force net = 1'b1; + release net; + end +endmodule +==== +# assign inside a labeled always block +module m; +always_ff @(posedge clk or negedge rst_n) begin +if(!rst_n) q<=0; +else q<=d; +end +endmodule +---- +module m; + always_ff @(posedge clk or negedge rst_n) begin + if (!rst_n) q <= 0; + else q <= d; + end +endmodule diff --git a/crates/vlog_formatter/tests/cases/comments.cases b/crates/vlog_formatter/tests/cases/comments.cases new file mode 100644 index 0000000..b78c843 --- /dev/null +++ b/crates/vlog_formatter/tests/cases/comments.cases @@ -0,0 +1,312 @@ +# leading line comment on a module +// top level comment +module m; +endmodule +---- +// top level comment +module m; +endmodule +==== +# leading comment on a declaration +module m; +// the data bus +wire [7:0] bus; +endmodule +---- +module m; + // the data bus + wire [7:0] bus; +endmodule +==== +# trailing comment on a declaration +module m; +wire [7:0] bus; // the data bus +endmodule +---- +module m; + wire [7:0] bus; // the data bus +endmodule +==== +# block comment before a module +/* a block comment */ +module m; +endmodule +---- +/* a block comment */ +module m; +endmodule +==== +#SKIP bug: continuation lines of a multi-line block comment gain two spaces on +#SKIP every format pass -- an unbounded idempotency violation (see feature README) +# multi-line block comment is passed through verbatim +module m; +/* + * doc block + */ +wire w; +endmodule +---- +module m; + /* + * doc block + */ + wire w; +endmodule +==== +# comment between statements inside a block +module m; +always_comb begin +a = 1; +// separator +b = 2; +end +endmodule +---- +module m; + always_comb begin + a = 1; + // separator + b = 2; + end +endmodule +==== +# trailing comment on a statement +module m; +always_comb begin +a = 1; // set a +end +endmodule +---- +module m; + always_comb begin + a = 1; // set a + end +endmodule +==== +# comment inside a port list forces the list to break +module m( +input a, // first +input b +); +endmodule +---- +module m ( + input a, // first + input b +); +endmodule +==== +# comment inside a connection list forces the list to break +module m; +sub u0( +.a(x), // hook up x +.b(y) +); +endmodule +---- +module m; + sub u0 ( + .a(x), // hook up x + .b(y) + ); +endmodule +==== +# comment on a case item +module m; +always_comb begin +case (sel) +// the zero case +2'd0: y = a; +2'd1: y = b; // the one case +default: y = 0; +endcase +end +endmodule +---- +module m; + always_comb begin + case (sel) + // the zero case + 2'd0: y = a; + 2'd1: y = b; // the one case + default: y = 0; + endcase + end +endmodule +==== +# several consecutive comment lines are kept together +module m; +// line one +// line two +// line three +wire w; +endmodule +---- +module m; + // line one + // line two + // line three + wire w; +endmodule +==== +# blank lines around comments are collapsed to one +module m; +wire a; + + + +// a comment after several blank lines + + +wire b; +endmodule +---- +module m; + wire a; + + // a comment after several blank lines + wire b; +endmodule +==== +# comment at the very end of a module body +module m; +wire w; +// trailing note +endmodule +---- +module m; + wire w; + // trailing note +endmodule +==== +# comment after endmodule +module m; +endmodule +// after the module +---- +module m; +endmodule +// after the module +==== +# comment between two modules +module a; +endmodule + +// between + +module b; +endmodule +---- +module a; +endmodule + +// between +module b; +endmodule +==== +# comment before else +module m; +always_comb begin +if (a) begin +y = 0; +// explain the else +end else begin +y = 1; +end +end +endmodule +---- +module m; + always_comb begin + if (a) begin + y = 0; + // explain the else + end else begin + y = 1; + end + end +endmodule +==== +# comment on a parameter port +module m #( +// the width +parameter WIDTH = 8 +) (); +endmodule +---- +module m #( + // the width + parameter WIDTH = 8 +) (); +endmodule +==== +#SKIP bug: the comment is lifted out of the concatenation to the end of the +#SKIP statement instead of forcing the group to break (see feature README) +# comment inside a concatenation +module m; +assign y = { +a, // high +b +}; +endmodule +---- +module m; + assign y = { + a, // high + b + }; +endmodule +==== +# leading comment on an instance +module m; +// instantiate the submodule +sub u0(.a(x)); +endmodule +---- +module m; + // instantiate the submodule + sub u0 (.a(x)); +endmodule +==== +# comment in an empty module body +module m; +// nothing here yet +endmodule +---- +module m; + // nothing here yet +endmodule +==== +# preprocessor directives are passed through verbatim +`include "defs.svh" +`define WIDTH 8 +module m; +`ifdef FAST +wire fast; +`else +wire slow; +`endif +endmodule +---- +`include "defs.svh" +`define WIDTH 8 +module m; + `ifdef FAST + wire fast; + `else + wire slow; + `endif +endmodule +==== +# attribute instances are passed through +(* keep = "true" *) +module m; +(* dont_touch *) +wire w; +endmodule +---- +(* keep = "true" *) +module m; + (* dont_touch *) + wire w; +endmodule diff --git a/crates/vlog_formatter/tests/cases/declarations.cases b/crates/vlog_formatter/tests/cases/declarations.cases new file mode 100644 index 0000000..3f8fc47 --- /dev/null +++ b/crates/vlog_formatter/tests/cases/declarations.cases @@ -0,0 +1,197 @@ +# plain net and variable declarations +module m; +wire w; +reg r; +logic l; +integer i; +endmodule +---- +module m; + wire w; + reg r; + logic l; + integer i; +endmodule +==== +# multiple names in one declaration +module m; +wire a,b,c; +endmodule +---- +module m; + wire a, b, c; +endmodule +==== +# packed dimension is tight +module m; +wire [7:0] bus; +logic [WIDTH-1:0] data; +endmodule +---- +module m; + wire [7:0] bus; + logic [WIDTH-1:0] data; +endmodule +==== +# expression in a packed dimension stays tight +module m; +logic [(WIDTH*2)-1:0] wide; +endmodule +---- +module m; + logic [(WIDTH*2)-1:0] wide; +endmodule +==== +# multiple packed dimensions +module m; +logic [3:0][7:0] matrix; +endmodule +---- +module m; + logic [3:0][7:0] matrix; +endmodule +==== +# unpacked dimensions +module m; +logic [7:0] mem [0:255]; +reg r [3:0]; +endmodule +---- +module m; + logic [7:0] mem [0:255]; + reg r [3:0]; +endmodule +==== +# signed and unsigned nets +module m; +wire signed [7:0] s; +reg unsigned [7:0] u; +endmodule +---- +module m; + wire signed [7:0] s; + reg unsigned [7:0] u; +endmodule +==== +# builtin integral types +module m; +int i; +byte b; +shortint si; +longint li; +bit flag; +endmodule +---- +module m; + int i; + byte b; + shortint si; + longint li; + bit flag; +endmodule +==== +# declaration with initializer +module m; +logic [7:0] count = 8'h00; +endmodule +---- +module m; + logic [7:0] count = 8'h00; +endmodule +==== +# parameter and localparam +module m; +parameter WIDTH = 8; +localparam DEPTH = 16; +endmodule +---- +module m; + parameter WIDTH = 8; + localparam DEPTH = 16; +endmodule +==== +# typed parameter and localparam +module m; +parameter int unsigned WIDTH = 8; +localparam logic [3:0] MASK = 4'b1010; +endmodule +---- +module m; + parameter int unsigned WIDTH = 8; + localparam logic [3:0] MASK = 4'b1010; +endmodule +==== +# several parameters in one declaration +module m; +localparam A = 1, B = 2, C = 3; +endmodule +---- +module m; + localparam A = 1, B = 2, C = 3; +endmodule +==== +# genvar and defparam +module m; +genvar i; +defparam u0.WIDTH = 8; +endmodule +---- +module m; + genvar i; + defparam u0.WIDTH = 8; +endmodule +==== +# net with a delay +module m; +wire #5 slow; +endmodule +---- +module m; + wire #5 slow; +endmodule +==== +# supply and tri nets +module m; +supply0 gnd; +supply1 vdd; +tri t; +endmodule +---- +module m; + supply0 gnd; + supply1 vdd; + tri t; +endmodule +==== +# long parameter initializer that exceeds the line limit +module m; +localparam int TOTAL_ENTRY_COUNT = NUMBER_OF_BANKS * ENTRIES_PER_BANK + SPARE_ENTRIES_PER_DEVICE + 1; +endmodule +---- +module m; + localparam int TOTAL_ENTRY_COUNT = + NUMBER_OF_BANKS * ENTRIES_PER_BANK + SPARE_ENTRIES_PER_DEVICE + 1; +endmodule +==== +# blank lines between declaration groups are preserved and collapsed +module m; +wire a; + + +wire b; +endmodule +---- +module m; + wire a; + + wire b; +endmodule +==== +# var keyword and automatic-style declarations +module m; +var logic v; +endmodule +---- +module m; + var logic v; +endmodule diff --git a/crates/vlog_formatter/tests/cases/expressions.cases b/crates/vlog_formatter/tests/cases/expressions.cases new file mode 100644 index 0000000..662316c --- /dev/null +++ b/crates/vlog_formatter/tests/cases/expressions.cases @@ -0,0 +1,271 @@ +# binary operators get single spaces +module m; +assign y=a+b*c-d/e%f; +endmodule +---- +module m; + assign y = a + b * c - d / e % f; +endmodule +==== +# unary operators bind tightly +module m; +assign y = ~a & -b | !c ^ +d; +endmodule +---- +module m; + assign y = ~a & -b | !c ^ +d; +endmodule +==== +# reduction operators +module m; +assign y = &a | |b ^ ^c; +assign z = ~&a & ~|b & ~^c; +endmodule +---- +module m; + assign y = &a | |b ^ ^c; + assign z = ~&a & ~|b & ~^c; +endmodule +==== +# comparison and equality operators +module m; +assign y = (a=d)||(e==f)&&(g!==h); +endmodule +---- +module m; + assign y = (a < b) && (c >= d) || (e == f) && (g !== h); +endmodule +==== +# shift and power operators +module m; +assign y = (a << 2) + (b >>> 1) + (c ** 2); +endmodule +---- +module m; + assign y = (a << 2) + (b >>> 1) + (c ** 2); +endmodule +==== +# redundant parentheses are preserved +module m; +assign y = ((a + b)); +endmodule +---- +module m; + assign y = ((a + b)); +endmodule +==== +# nested ternary +module m; +assign y = a ? b : c ? d : e; +endmodule +---- +module m; + assign y = a ? b : c ? d : e; +endmodule +==== +# ternary that must wrap +module m; +assign output_signal_name = condition_signal_name_x ? first_alternative_value : second_alternative; +endmodule +---- +module m; + assign output_signal_name = + condition_signal_name_x ? first_alternative_value : second_alternative; +endmodule +==== +# concatenation and replication +module m; +assign y={a,b,c}; +assign z={4{a}}; +assign w={2{a,b}}; +endmodule +---- +module m; + assign y = {a, b, c}; + assign z = {4{a}}; + assign w = {2{a, b}}; +endmodule +==== +# nested concatenation +module m; +assign y = {{4{a}}, {2{b, c}}, d}; +endmodule +---- +module m; + assign y = {{4{a}}, {2{b, c}}, d}; +endmodule +==== +# part selects and indexed part selects +module m; +assign y = bus[7:0]; +assign z = bus[base+:8]; +assign w = bus[base-:8]; +endmodule +---- +module m; + assign y = bus[7:0]; + assign z = bus[base+:8]; + assign w = bus[base-:8]; +endmodule +==== +# chained selects on a hierarchical name +module m; +assign y = top.u_sub.mem[3][7:0]; +endmodule +---- +module m; + assign y = top.u_sub.mem[3][7:0]; +endmodule +==== +# casts +module m; +assign y = int'(a); +assign z = 8'(b); +assign w = signed'(c); +endmodule +---- +module m; + assign y = int'(a); + assign z = 8'(b); + assign w = signed'(c); +endmodule +==== +# assignment patterns +module m; +always_comb begin +s = '{a: 1, b: 2}; +v = '{default: 0}; +t = '{1, 2, 3}; +end +endmodule +---- +module m; + always_comb begin + s = '{a: 1, b: 2}; + v = '{default: 0}; + t = '{1, 2, 3}; + end +endmodule +==== +# inside operator +module m; +assign y = a inside {1, 2, 3}; +endmodule +---- +module m; + assign y = a inside {1, 2, 3}; +endmodule +==== +# package-scoped and hierarchical names +module m; +assign y = pkg::CONST + top.inst.sig; +endmodule +---- +module m; + assign y = pkg::CONST + top.inst.sig; +endmodule +==== +# function call in an expression +module m; +assign y = compute(a, b) + 1; +endmodule +---- +module m; + assign y = compute(a, b) + 1; +endmodule +==== +# system function call +module m; +localparam W = $clog2(DEPTH); +endmodule +---- +module m; + localparam W = $clog2(DEPTH); +endmodule +==== +# macro usage in expression position +module m; +assign y = `MY_MACRO(a, b) + 1; +endmodule +---- +module m; + assign y = `MY_MACRO(a, b) + 1; +endmodule +==== +# numeric literal forms +module m; +localparam A = 8'hFF; +localparam B = 4'b1010; +localparam C = 32'd42; +localparam D = 'x; +localparam E = 1.5e3; +endmodule +---- +module m; + localparam A = 8'hFF; + localparam B = 4'b1010; + localparam C = 32'd42; + localparam D = 'x; + localparam E = 1.5e3; +endmodule +==== +# string literal +module m; +initial $display("a string with, commas and (parens)"); +endmodule +---- +module m; + initial $display("a string with, commas and (parens)"); +endmodule +==== +# long boolean expression breaks at the top-level operator +module m; +assign ready_signal = first_condition_name && second_condition_name && third_condition_name && xyzw; +endmodule +---- +module m; + assign ready_signal = + first_condition_name && second_condition_name && third_condition_name && xyzw; +endmodule +==== +# an expression that fits in exactly 100 columns is left on one line +module m; +assign ready_signal = first_condition_name && second_condition_name && third_condition_name && xy; +endmodule +---- +module m; + assign ready_signal = first_condition_name && second_condition_name && third_condition_name && xy; +endmodule +==== +# a very long operator chain breaks one operand per line +module m; +assign ready_signal = first_condition_name && second_condition_name && third_condition_name && fourth_condition_name && fifth_condition_name; +endmodule +---- +module m; + assign ready_signal = + first_condition_name && + second_condition_name && + third_condition_name && + fourth_condition_name && + fifth_condition_name; +endmodule +==== +# a long concatenation that fits once wrapped stays on one line +module m; +assign bus_value = {first_source_word, second_source_word, third_source_word, fourth_source_word, fifth}; +endmodule +---- +module m; + assign bus_value = + {first_source_word, second_source_word, third_source_word, fourth_source_word, fifth}; +endmodule +==== +# streams of mixed precedence stay unparenthesized +module m; +assign y = a + b == c - d; +endmodule +---- +module m; + assign y = a + b == c - d; +endmodule diff --git a/crates/vlog_formatter/tests/cases/functions_tasks.cases b/crates/vlog_formatter/tests/cases/functions_tasks.cases new file mode 100644 index 0000000..3f75c7c --- /dev/null +++ b/crates/vlog_formatter/tests/cases/functions_tasks.cases @@ -0,0 +1,227 @@ +# function with an ANSI port list +module m; +function int add(input int a, input int b); +return a + b; +endfunction +endmodule +---- +module m; + function int add(input int a, input int b); + return a + b; + endfunction +endmodule +==== +# function with no ports +module m; +function int zero(); +return 0; +endfunction +endmodule +---- +module m; + function int zero(); + return 0; + endfunction +endmodule +==== +# function with old-style port declarations +module m; +function [7:0] f; +input [7:0] a; +begin +f = a + 1; +end +endfunction +endmodule +---- +module m; + function [7:0] f; + input [7:0] a; + begin + f = a + 1; + end + endfunction +endmodule +==== +# void function +module m; +function void log(input string s); +$display(s); +endfunction +endmodule +---- +module m; + function void log(input string s); + $display(s); + endfunction +endmodule +==== +# automatic function with local declarations +module m; +function automatic int sum(input int n); +int acc; +acc = 0; +for (int i = 0; i < n; i++) acc = acc + i; +return acc; +endfunction +endmodule +---- +module m; + function automatic int sum(input int n); + int acc; + acc = 0; + for (int i = 0; i < n; i++) acc = acc + i; + return acc; + endfunction +endmodule +==== +# function whose port list is too wide +module m; +function automatic logic [31:0] compute(input logic [31:0] first_operand, input logic [31:0] second); +return first_operand + second; +endfunction +endmodule +---- +module m; + function automatic logic [31:0] compute( + input logic [31:0] first_operand, + input logic [31:0] second + ); + return first_operand + second; + endfunction +endmodule +==== +# task with ANSI ports +module m; +task send(input logic [7:0] data, output logic done); +done = 1'b0; +@(posedge clk); +done = 1'b1; +endtask +endmodule +---- +module m; + task send(input logic [7:0] data, output logic done); + done = 1'b0; + @(posedge clk); + done = 1'b1; + endtask +endmodule +==== +# task with no ports and no parentheses +module m; +task reset_all; +q <= 0; +endtask +endmodule +---- +module m; + task reset_all; + q <= 0; + endtask +endmodule +==== +# task with old-style port declarations +module m; +task t; +input [7:0] a; +output b; +begin +b = |a; +end +endtask +endmodule +---- +module m; + task t; + input [7:0] a; + output b; + begin + b = |a; + end + endtask +endmodule +==== +# task with inout and ref-free defaults +module m; +task t(inout int x, input int y = 0); +x = x + y; +endtask +endmodule +---- +module m; + task t(inout int x, input int y = 0); + x = x + y; + endtask +endmodule +==== +# task call as a statement +module m; +initial begin +send(8'hFF, done); +reset_all; +end +endmodule +---- +module m; + initial begin + send(8'hFF, done); + reset_all; + end +endmodule +==== +# function call with a wide argument list +module m; +assign result = compute_the_value(first_argument_name, second_argument_name, third_argument_name); +endmodule +---- +module m; + assign result = compute_the_value(first_argument_name, second_argument_name, third_argument_name); +endmodule +==== +# function returning a struct-typed value +module m; +function my_type_t make(input int a); +make.field = a; +return make; +endfunction +endmodule +---- +module m; + function my_type_t make(input int a); + make.field = a; + return make; + endfunction +endmodule +==== +# comment on a function port +module m; +function int f( +// the operand +input int a +); +return a; +endfunction +endmodule +---- +module m; + function int f( + // the operand + input int a + ); + return a; + endfunction +endmodule +==== +# function inside a package +package p; +function int id(input int a); +return a; +endfunction +endpackage +---- +package p; + function int id(input int a); + return a; + endfunction +endpackage diff --git a/crates/vlog_formatter/tests/cases/generate.cases b/crates/vlog_formatter/tests/cases/generate.cases new file mode 100644 index 0000000..6c93cf4 --- /dev/null +++ b/crates/vlog_formatter/tests/cases/generate.cases @@ -0,0 +1,219 @@ +# generate region with a for loop +module m; +generate +for(genvar i=0;i<4;i++) begin : gen_loop +sub u(.a(i)); +end +endgenerate +endmodule +---- +module m; + generate + for (genvar i = 0; i < 4; i++) begin : gen_loop + sub u (.a(i)); + end + endgenerate +endmodule +==== +# generate for with a separate genvar declaration +module m; +genvar i; +generate +for(i=0;i8) begin : g_wide +wire [15:0] bus; +end else begin : g_narrow +wire [7:0] bus; +end +endgenerate +endmodule +---- +module m; + generate + if (WIDTH > 8) begin : g_wide + wire [15:0] bus; + end else begin : g_narrow + wire [7:0] bus; + end + endgenerate +endmodule +==== +# generate case +module m; +generate +case(MODE) +0: begin : g_zero +assign y = a; +end +default: begin : g_default +assign y = b; +end +endcase +endgenerate +endmodule +---- +module m; + generate + case (MODE) + 0: begin : g_zero + assign y = a; + end + default: begin : g_default + assign y = b; + end + endcase + endgenerate +endmodule +==== +# module-level if without a generate region +module m; +if (EN) begin : g_en +wire w; +end +endmodule +---- +module m; + if (EN) begin : g_en + wire w; + end +endmodule +==== +# module-level for without a generate region +module m; +for (genvar i = 0; i < 4; i++) begin : g +assign y[i] = a[i]; +end +endmodule +---- +module m; + for (genvar i = 0; i < 4; i++) begin : g + assign y[i] = a[i]; + end +endmodule +==== +# nested generate loops +module m; +generate +for (genvar i = 0; i < 4; i++) begin : g_outer +for (genvar j = 0; j < 4; j++) begin : g_inner +assign y[i][j] = a[i][j]; +end +end +endgenerate +endmodule +---- +module m; + generate + for (genvar i = 0; i < 4; i++) begin : g_outer + for (genvar j = 0; j < 4; j++) begin : g_inner + assign y[i][j] = a[i][j]; + end + end + endgenerate +endmodule +==== +# generate block containing declarations and an always block +module m; +generate +for (genvar i = 0; i < 4; i++) begin : g +logic tmp; +always_ff @(posedge clk) tmp <= a[i]; +assign y[i] = tmp; +end +endgenerate +endmodule +---- +module m; + generate + for (genvar i = 0; i < 4; i++) begin : g + logic tmp; + always_ff @(posedge clk) tmp <= a[i]; + assign y[i] = tmp; + end + endgenerate +endmodule +==== +# empty generate region +module m; +generate +endgenerate +endmodule +---- +module m; + generate + endgenerate +endmodule +==== +# generate if with only a then-branch +module m; +generate +if (EN) begin : g +assign y = a; +end +endgenerate +endmodule +---- +module m; + generate + if (EN) begin : g + assign y = a; + end + endgenerate +endmodule +==== +# comment inside a generate block +module m; +generate +// replicate the datapath +for (genvar i = 0; i < 4; i++) begin : g +assign y[i] = a[i]; +end +endgenerate +endmodule +---- +module m; + generate + // replicate the datapath + for (genvar i = 0; i < 4; i++) begin : g + assign y[i] = a[i]; + end + endgenerate +endmodule +==== +# generate block with a blank line between items +module m; +generate +for (genvar i = 0; i < 4; i++) begin : g +wire w; + +assign y[i] = w; +end +endgenerate +endmodule +---- +module m; + generate + for (genvar i = 0; i < 4; i++) begin : g + wire w; + + assign y[i] = w; + end + endgenerate +endmodule diff --git a/crates/vlog_formatter/tests/cases/instantiation.cases b/crates/vlog_formatter/tests/cases/instantiation.cases new file mode 100644 index 0000000..7009eea --- /dev/null +++ b/crates/vlog_formatter/tests/cases/instantiation.cases @@ -0,0 +1,181 @@ +# instance with no connections +module m; +sub u0(); +endmodule +---- +module m; + sub u0 (); +endmodule +==== +# ordered connections +module m; +sub u0(a,b,c); +endmodule +---- +module m; + sub u0 (a, b, c); +endmodule +==== +# named connections that fit on one line +module m; +sub u0(.a(x),.b(y)); +endmodule +---- +module m; + sub u0 (.a(x), .b(y)); +endmodule +==== +# named connections too wide break one per line +module m; +some_submodule u_some_submodule_instance(.clock_input(clk), .reset_input(rst_n), .data_input(data_in), .data_output(data_out)); +endmodule +---- +module m; + some_submodule u_some_submodule_instance ( + .clock_input(clk), + .reset_input(rst_n), + .data_input(data_in), + .data_output(data_out) + ); +endmodule +==== +# implicit .name connections +module m; +sub u0(.clk, .rst_n, .d(data)); +endmodule +---- +module m; + sub u0 (.clk, .rst_n, .d(data)); +endmodule +==== +# wildcard connection +module m; +sub u0(.*); +endmodule +---- +module m; + sub u0 (.*); +endmodule +==== +# wildcard mixed with explicit connections +module m; +sub u0(.clk(clk_i), .*); +endmodule +---- +module m; + sub u0 (.clk(clk_i), .*); +endmodule +==== +# unconnected port +module m; +sub u0(.a(), .b(y)); +endmodule +---- +module m; + sub u0 (.a(), .b(y)); +endmodule +==== +# parameter override by name +module m; +sub #(.WIDTH(8),.DEPTH(16)) u0(.a(x)); +endmodule +---- +module m; + sub #(.WIDTH(8), .DEPTH(16)) u0 (.a(x)); +endmodule +==== +# parameter override by order +module m; +sub #(8,16) u0(.a(x)); +endmodule +---- +module m; + sub #(8, 16) u0 (.a(x)); +endmodule +==== +# parameter override wide enough to break +module m; +sub #(.DATA_WIDTH_IN_BITS(32), .ADDRESS_WIDTH_IN_BITS(24), .NUMBER_OF_BANKS(4), .PIPELINE(1)) u0(); +endmodule +---- +module m; + sub #( + .DATA_WIDTH_IN_BITS(32), + .ADDRESS_WIDTH_IN_BITS(24), + .NUMBER_OF_BANKS(4), + .PIPELINE(1) + ) u0 (); +endmodule +==== +# instance array +module m; +sub u0[3:0](.a(x),.b(y)); +endmodule +---- +module m; + sub u0 [3:0] (.a(x), .b(y)); +endmodule +==== +#SKIP bug: multi-instance declarations always break and the continuation is +#SKIP not indented (see feature README) +# multiple instances in one statement +module m; +sub u0(.a(x)), u1(.a(y)); +endmodule +---- +module m; + sub u0 (.a(x)), u1 (.a(y)); +endmodule +==== +# gate primitive instantiation +module m; +and g0(y, a, b); +not g1(nb, b); +endmodule +---- +module m; + and g0 (y, a, b); + not g1 (nb, b); +endmodule +==== +# gate with a drive strength and delay +module m; +buf #2 g0(y, a); +endmodule +---- +module m; + buf #2 g0 (y, a); +endmodule +==== +# connection expression that itself is wide +module m; +sub u0(.data_output_bus(first_source_word | second_source_word | third_source_word | fourth_word)); +endmodule +---- +module m; + sub u0 ( + .data_output_bus(first_source_word | second_source_word | third_source_word | fourth_word) + ); +endmodule +==== +# package-scoped module type +module m; +pkg::sub u0(.a(x)); +endmodule +---- +module m; + pkg::sub u0 (.a(x)); +endmodule +==== +# instances separated by blank lines +module m; +sub u0(); + +sub u1(); +endmodule +---- +module m; + sub u0 (); + + sub u1 (); +endmodule diff --git a/crates/vlog_formatter/tests/cases/module_headers.cases b/crates/vlog_formatter/tests/cases/module_headers.cases new file mode 100644 index 0000000..8736501 --- /dev/null +++ b/crates/vlog_formatter/tests/cases/module_headers.cases @@ -0,0 +1,139 @@ +# empty module, no port list +module m;endmodule +---- +module m; +endmodule +==== +# empty parenthesized port list +module m ( ) ; +endmodule +---- +module m (); +endmodule +==== +# ANSI ports fit on one line +module m(input a,output b);endmodule +---- +module m (input a, output b); +endmodule +==== +# ANSI ports with directions and types +module m(input wire clk,input wire rst_n,output logic [7:0] q);endmodule +---- +module m (input wire clk, input wire rst_n, output logic [7:0] q); +endmodule +==== +# non-ANSI header: names in the port list, declarations in the body +module m(a,b,c); +input a; +input [3:0] b; +output reg c; +endmodule +---- +module m (a, b, c); + input a; + input [3:0] b; + output reg c; +endmodule +==== +# port list too wide for 100 columns breaks one per line +module wide_module_name(input wire clock_signal_in,input wire reset_signal_in,input wire [31:0] data_word_in,output wire [31:0] data_word_out);endmodule +---- +module wide_module_name ( + input wire clock_signal_in, + input wire reset_signal_in, + input wire [31:0] data_word_in, + output wire [31:0] data_word_out +); +endmodule +==== +# parameter port list, single parameter +module m#(parameter WIDTH=8)(input [WIDTH-1:0] d);endmodule +---- +module m #(parameter WIDTH = 8) (input [WIDTH-1:0] d); +endmodule +==== +# parameter port list with types +module m #(parameter int WIDTH = 8, parameter type T = logic) (input T d);endmodule +---- +module m #(parameter int WIDTH = 8, parameter type T = logic) (input T d); +endmodule +==== +# parameter port list too wide breaks +module m #(parameter int DATA_WIDTH_IN_BITS = 32, parameter int ADDRESS_WIDTH_IN_BITS = 24, parameter int NUMBER_OF_BANKS = 4) ();endmodule +---- +module m #( + parameter int DATA_WIDTH_IN_BITS = 32, + parameter int ADDRESS_WIDTH_IN_BITS = 24, + parameter int NUMBER_OF_BANKS = 4 +) (); +endmodule +==== +# localparam-style parameter without the keyword repeated +module m #(WIDTH = 8, DEPTH = 16) ();endmodule +---- +module m #(WIDTH = 8, DEPTH = 16) (); +endmodule +==== +# inout and multi-name ports +module m(input a,b,inout wire io,output c);endmodule +---- +module m (input a, b, inout wire io, output c); +endmodule +==== +# unpacked and packed dimensions on ports +module m(input logic [7:0] mem [0:3], output logic [3:0][7:0] q);endmodule +---- +module m (input logic [7:0] mem [0:3], output logic [3:0][7:0] q); +endmodule +==== +# module with default port values in the parameter list +module m #(parameter WIDTH = 8) (input [WIDTH-1:0] a, output [WIDTH-1:0] y); +assign y=a; +endmodule +---- +module m #(parameter WIDTH = 8) (input [WIDTH-1:0] a, output [WIDTH-1:0] y); + assign y = a; +endmodule +==== +# two modules separated by blank lines, collapsed to one +module a;endmodule + + + +module b;endmodule +---- +module a; +endmodule + +module b; +endmodule +==== +# package with a parameter and a typedef +package pkg; +parameter int N=4; +typedef logic [7:0] byte_t; +endpackage +---- +package pkg; + parameter int N = 4; + typedef logic [7:0] byte_t; +endpackage +==== +# import and timeunit inside a module +module m; +import pkg::*; +timeunit 1ns/1ps; +endmodule +---- +module m; + import pkg::*; + timeunit 1ns / 1ps; +endmodule +==== +# module with a lifetime-free body and trailing endmodule label +module m; +endmodule : m +---- +module m; +endmodule : m diff --git a/crates/vlog_formatter/tests/cases/statements.cases b/crates/vlog_formatter/tests/cases/statements.cases new file mode 100644 index 0000000..ac9d927 --- /dev/null +++ b/crates/vlog_formatter/tests/cases/statements.cases @@ -0,0 +1,475 @@ +# if with a single statement, no begin +module m; +always_comb if(a) y=1; +endmodule +---- +module m; + always_comb if (a) y = 1; +endmodule +==== +# if / else if / else chain without begin +module m; +always_comb begin +if(a) y=0; +else if(b) y=1; +else y=2; +end +endmodule +---- +module m; + always_comb begin + if (a) y = 0; + else if (b) y = 1; + else y = 2; + end +endmodule +==== +# cuddled begin/end: end else begin +module m; +always_comb begin +if(a) +begin +y=0; +end +else +begin +y=1; +end +end +endmodule +---- +module m; + always_comb begin + if (a) begin + y = 0; + end else begin + y = 1; + end + end +endmodule +==== +# cuddled else-if chain with begin/end blocks +module m; +always_comb begin +if (a) begin +y = 0; +end else if (b) begin +y = 1; +end else begin +y = 2; +end +end +endmodule +---- +module m; + always_comb begin + if (a) begin + y = 0; + end else if (b) begin + y = 1; + end else begin + y = 2; + end + end +endmodule +==== +# labeled begin, no closing label +module m; +initial begin : main +x = 1; +end +endmodule +---- +module m; + initial begin : main + x = 1; + end +endmodule +==== +#SKIP bug: the closing `end : main` label is dropped (see feature README) +# labeled begin/end with a closing label +module m; +initial begin : main +x = 1; +end : main +endmodule +---- +module m; + initial begin : main + x = 1; + end : main +endmodule +==== +# nested begin blocks +module m; +initial begin +begin +a = 1; +end +end +endmodule +---- +module m; + initial begin + begin + a = 1; + end + end +endmodule +==== +# plain case statement +module m; +always_comb begin +case(sel) +2'd0: y = a; +2'd1: y = b; +default: y = 0; +endcase +end +endmodule +---- +module m; + always_comb begin + case (sel) + 2'd0: y = a; + 2'd1: y = b; + default: y = 0; + endcase + end +endmodule +==== +# casez and casex +module m; +always_comb begin +casez(op) +8'b1???????: y = 1; +default: y = 0; +endcase +casex(op) +8'bx0??????: y = 1; +default: y = 0; +endcase +end +endmodule +---- +module m; + always_comb begin + casez (op) + 8'b1???????: y = 1; + default: y = 0; + endcase + casex (op) + 8'bx0??????: y = 1; + default: y = 0; + endcase + end +endmodule +==== +# unique and priority case +module m; +always_comb begin +unique case(sel) +2'd0: y = a; +default: y = b; +endcase +priority casez(sel) +2'b1?: y = a; +default: y = b; +endcase +end +endmodule +---- +module m; + always_comb begin + unique case (sel) + 2'd0: y = a; + default: y = b; + endcase + priority casez (sel) + 2'b1?: y = a; + default: y = b; + endcase + end +endmodule +==== +# case item with multiple labels and a begin/end body +module m; +always_comb begin +case(sel) +2'd0, 2'd1: begin +y = a; +z = b; +end +default: y = 0; +endcase +end +endmodule +---- +module m; + always_comb begin + case (sel) + 2'd0, 2'd1: begin + y = a; + z = b; + end + default: y = 0; + endcase + end +endmodule +==== +# unique if +module m; +always_comb begin +unique if (a) y = 1; +else y = 0; +end +endmodule +---- +module m; + always_comb begin + unique if (a) y = 1; + else y = 0; + end +endmodule +==== +# for loop +module m; +always_comb begin +for(int i=0;i ev; +assert (a == b); +end +endmodule +---- +module m; + initial begin + disable blk; + -> ev; + assert (a == b); + end +endmodule +==== +# immediate assertion with else clause +module m; +always_comb begin +assert (a) y = 1; +else $error("bad"); +end +endmodule +---- +module m; + always_comb begin + assert (a) y = 1; + else $error("bad"); + end +endmodule +==== +# break, continue and return in loops and tasks +module m; +always_comb begin +for (int i = 0; i < N; i++) begin +if (skip[i]) continue; +if (stop[i]) break; +end +end +endmodule +---- +module m; + always_comb begin + for (int i = 0; i < N; i++) begin + if (skip[i]) continue; + if (stop[i]) break; + end + end +endmodule +==== +# system task calls +module m; +initial begin +$display("hello %0d", x); +$finish; +end +endmodule +---- +module m; + initial begin + $display("hello %0d", x); + $finish; + end +endmodule +==== +# empty statement and empty begin/end +module m; +initial begin +end +endmodule +---- +module m; + initial begin + end +endmodule +==== +# deeply nested statements keep two-space indent steps +module m; +always_comb begin +if (a) begin +case (sel) +2'd0: begin +for (int i = 0; i < 4; i++) begin +y = y + i; +end +end +default: y = 0; +endcase +end +end +endmodule +---- +module m; + always_comb begin + if (a) begin + case (sel) + 2'd0: begin + for (int i = 0; i < 4; i++) begin + y = y + i; + end + end + default: y = 0; + endcase + end + end +endmodule diff --git a/crates/vlog_formatter/tests/cases/typedef.cases b/crates/vlog_formatter/tests/cases/typedef.cases new file mode 100644 index 0000000..50f6294 --- /dev/null +++ b/crates/vlog_formatter/tests/cases/typedef.cases @@ -0,0 +1,176 @@ +# simple type alias +module m; +typedef logic [7:0] byte_t; +endmodule +---- +module m; + typedef logic [7:0] byte_t; +endmodule +==== +# alias of a builtin type +package p; +typedef int my_int_t; +typedef logic word_t; +endpackage +---- +package p; + typedef int my_int_t; + typedef logic word_t; +endpackage +==== +# alias with unpacked dimensions +package p; +typedef logic [7:0] mem_t [0:255]; +endpackage +---- +package p; + typedef logic [7:0] mem_t [0:255]; +endpackage +==== +# enum without a base type +package p; +typedef enum {RED, GREEN, BLUE} color_t; +endpackage +---- +package p; + typedef enum {RED, GREEN, BLUE} color_t; +endpackage +==== +# enum with a base type and explicit values +package p; +typedef enum logic [1:0] {IDLE = 2'd0, RUN = 2'd1, DONE = 2'd2} state_t; +endpackage +---- +package p; + typedef enum logic [1:0] {IDLE = 2'd0, RUN = 2'd1, DONE = 2'd2} state_t; +endpackage +==== +# enum wide enough to break one member per line +package p; +typedef enum logic [2:0] {STATE_IDLE, STATE_FETCH, STATE_DECODE, STATE_EXECUTE, STATE_WRITEBACK} state_t; +endpackage +---- +package p; + typedef enum logic [2:0] { + STATE_IDLE, + STATE_FETCH, + STATE_DECODE, + STATE_EXECUTE, + STATE_WRITEBACK + } state_t; +endpackage +==== +# packed struct +package p; +typedef struct packed {logic [7:0] addr; logic [31:0] data;} req_t; +endpackage +---- +package p; + typedef struct packed { + logic [7:0] addr; + logic [31:0] data; + } req_t; +endpackage +==== +# packed struct that must break +package p; +typedef struct packed {logic [31:0] address_field; logic [63:0] data_field; logic valid_field;} req_t; +endpackage +---- +package p; + typedef struct packed { + logic [31:0] address_field; + logic [63:0] data_field; + logic valid_field; + } req_t; +endpackage +==== +# packed union +package p; +typedef union packed {logic [31:0] word; logic [3:0][7:0] bytes;} view_t; +endpackage +---- +package p; + typedef union packed { + logic [31:0] word; + logic [3:0][7:0] bytes; + } view_t; +endpackage +==== +# nested struct type +package p; +typedef struct packed {header_t header; logic [31:0] payload;} packet_t; +endpackage +---- +package p; + typedef struct packed { + header_t header; + logic [31:0] payload; + } packet_t; +endpackage +==== +# typedef used in a declaration and a port +module m(input pkg::state_t st); +pkg::req_t req; +endmodule +---- +module m (input pkg::state_t st); + pkg::req_t req; +endmodule +==== +# comment on a struct member +package p; +typedef struct packed { +// the address +logic [7:0] addr; +logic [31:0] data; +} req_t; +endpackage +---- +package p; + typedef struct packed { + // the address + logic [7:0] addr; + logic [31:0] data; + } req_t; +endpackage +==== +# enum with a comment on a member +package p; +typedef enum logic [1:0] { +IDLE, // waiting +RUN +} state_t; +endpackage +---- +package p; + typedef enum logic [1:0] { + IDLE, // waiting + RUN + } state_t; +endpackage +==== +# signed struct member and multiple names per member +package p; +typedef struct packed {logic signed [7:0] a, b; logic c;} s_t; +endpackage +---- +package p; + typedef struct packed { + logic signed [7:0] a, b; + logic c; + } s_t; +endpackage +==== +# typedefs separated by blank lines +package p; +typedef logic [7:0] a_t; + +typedef logic [15:0] b_t; +endpackage +---- +package p; + typedef logic [7:0] a_t; + + typedef logic [15:0] b_t; +endpackage diff --git a/docs/features/case-tables/README.md b/docs/features/case-tables/README.md new file mode 100644 index 0000000..d509c2d --- /dev/null +++ b/docs/features/case-tables/README.md @@ -0,0 +1,448 @@ +# case-tables + +## Goal + +Give vfmt the backbone Verible's formatter has: a large table of small +text-in/text-out `{input, expected}` pairs, organized by construct, that runs +on every `cargo test`. Verible's `formatter_test.cc` is thousands of such +pairs and is where years of edge cases live; the existing snapshot suite in +`tests/fixtures/` covers whole files well but is a poor place to pin down "what +exactly happens to *this* three-line construct". Each case asserts both +`format(input) == expected` and `format(expected) == expected`, so every pair +buys a formatting check and an idempotency check. + +## Assumptions + +- `format_source` takes a complete source file, so every case input is a full + compilation unit (`module ... endmodule`, `package ... endpackage`, ...). + There is no fragment/statement-level entry point to test against. +- Cases only exercise syntax the top-level `README.md` lists as supported. + Nothing here depends on interfaces, classes, assertions-as-properties, etc. +- Default `Config` (2-space indent, 100 columns). No case varies the config; + if configurable behavior needs coverage later, add a per-file header rather + than a second directory. +- A `#` at the start of a line can only be a case header, never Verilog: a + delay like `#5` is legal at statement level but never at the top level of a + file, which is where every case input begins. + +## Handshakes + +- **Consumes** `vlog_formatter::{format_source, Config}` only. If the signature + of `format_source` changes, `tests/cases.rs` needs the same edit as + `tests/fixtures.rs`. +- **Consumes** the runtime verification added by the correctness-safety-net + work (`src/verify.rs`): `format_source` now returns `Err` when equivalence or + convergence fails, and the harness reports that as `format failed: ...`. + Cases that used to produce (wrong) output now produce an error instead — + three of the bugs below are of that shape. +- **Promises** nothing to other modules; nothing imports this test. +- **Requests** to other agents: none. All findings below are reported, not + fixed — formatter `src/` is out of this feature's scope. + +## File format + +One `.cases` file per construct area, under +`crates/vlog_formatter/tests/cases/`. Within a file: + +```text +# a short name for the case +module m;wire w;endmodule +---- +module m; + wire w; +endmodule +==== +# the next case +... +``` + +- A line that is exactly `====` separates cases. The last case needs no + trailing separator. +- A line that is exactly `----` separates input from expected output. +- Lines starting with `#` at the *top* of a case are its name (joined with + spaces). Once a non-`#`, non-blank line is seen, the input has started and + `#` is no longer special. +- A case with a `#` header line that *starts with* `SKIP` (written + `#SKIP ...`; `SKIP` elsewhere in a name has no effect) is the parking lot + for inputs the formatter gets wrong: the expected half holds the output we + *want*. The harness asserts a `#SKIP` case still *fails* — the moment the + bug is fixed the suite demands the `#SKIP` line be deleted, turning the + case into a live regression test. +- Do not use bare `----` or `====` lines *inside* case content (e.g. as an + ASCII banner in a block comment) — they are always parsed as separators + and will silently split the case at the wrong place. +- Both halves are compared with a trailing newline, matching what + `format_source` produces. + +The harness (`crates/vlog_formatter/tests/cases.rs`, ~170 lines, std only) +discovers every `*.cases` file, parses it, and for each case asserts +`format(input) == expected` then `format(expected) == expected`. Failures are +collected (not aborted on the first one) and reported as +`file:line [case name]` plus a line-oriented diff (`-` expected, `+` got). + +## Status / TODO + +- [x] Harness `crates/vlog_formatter/tests/cases.rs` with discovery, `====` / + `----` parsing, `#SKIP` support, per-case diff reporting. +- [x] `module_headers.cases` — 17 cases +- [x] `declarations.cases` — 18 cases +- [x] `assignments.cases` — 14 cases +- [x] `statements.cases` — 26 cases +- [x] `instantiation.cases` — 18 cases +- [x] `expressions.cases` — 26 cases +- [x] `comments.cases` — 22 cases +- [x] `generate.cases` — 12 cases +- [x] `functions_tasks.cases` — 15 cases +- [x] `typedef.cases` — 15 cases +- [x] TODO.md §5 "massive text-in/text-out table tests" checked off. +- [ ] Port more cases directly from Verible's `formatter_test.cc` (only a + thematic sample is covered so far; the count should grow by an order of + magnitude). +- [ ] Cases for `--indent` / `--line-length` other than the defaults, once + there is a way to express config in a case file. +- [ ] Re-enable the four `#SKIP` cases as the bugs below are fixed. +- [ ] Close QA coverage gaps: `final` blocks, bare module-level `case` + (without a `generate` wrapper), an `initial fork ... join` case backing + the style observation, comma-separated sensitivity lists, multiple + `import`s in one module. + +### Suspected bugs (not fixed — out of scope for this feature) + +**1. Multi-line block comments are re-indented on every pass (idempotency +violation, hard invariant #2).** Highest severity: it breaks a documented hard +invariant and makes any file with a banner comment inside a module body +unformattable. + +```verilog +module m; +/* + * doc block + */ +wire w; +endmodule +``` + +Pass 1 produces ` * doc block` (2 spaces of indent prepended to the original +1 space), pass 2 produces ` * doc block`, pass 3 seven spaces — it grows +without bound. With runtime convergence checking in place this now fails +outright: + +``` +error: verification failed: formatting is not idempotent; +line 3 changed from " * doc block" to " * doc block" +``` + +The continuation lines of a block comment should be re-indented relative to +the comment's *original* opening column, not by prepending the current indent +to whatever the previous pass left. Parked as `#SKIP` in `comments.cases`. + +**2. A comment inside an expression is lifted out of its group instead of +forcing it to break.** `README.md` states "A comment inside a group forces it +to break"; that holds for port lists, connection lists, case items and struct +members, but not for expression groups. + +```verilog +module m; +assign y = { +a, // high +b +}; +endmodule +``` + +Before runtime verification existed this emitted `assign y = {a, b}; // high` +— the comment survived (invariant #3 held) but moved out of the concatenation +and changed meaning. Now it is rejected: + +``` +error: verification failed: token stream diverges at index 9: +input has comment `// high` at 3:2, output has identifier `b` at 2:18 +``` + +The same happens for a comment inside parentheses (`(a // hi\n + b)`), inside a +call argument list (`f(a, // hi\n b)`), and inside an assignment pattern +(`'{a: 1, // hi\n b: 2}`). Parked as `#SKIP` in `comments.cases`. + +**3. Closing block labels are dropped.** `endmodule : m` is preserved, but +every other closing label is silently discarded: + +| input | output | +|---|---| +| `initial begin : main ... end : main` | `... end` | +| `fork : f ... join : f` | `... join` | +| `function int f(); ... endfunction : f` | `... endfunction` | +| `task t; ... endtask : t` | `... endtask` | +| `package p; ... endpackage : p` | `... endpackage` | + +This is token loss, so with runtime verification it is now a hard error +(`token stream diverges ... input has symbol ':' ... output has keyword +'endmodule'`). Parked as `#SKIP` in `statements.cases`; the opening label +(`begin : main`) is handled correctly and is covered by a passing case. + +**4. A declaration with several instances always breaks, and the continuation +is not indented.** + +```verilog +module m; +sub u0(.a(x)), u1(.a(y)); +endmodule +``` + +gives + +```verilog +module m; + sub u0 (.a(x)), + u1 (.a(y)); +endmodule +``` + +Two problems: the whole thing is 30 columns wide and should stay on one line, +and the continuation sits at the same indent as the head, so `u1` reads as a +new statement. Parked as `#SKIP` in `instantiation.cases` with the one-line +form as the wanted output. + +### Style observations (kept as expected output — defensible, but worth a look) + +- Unpacked dimensions and instance-array ranges get a space before the + bracket: `logic [7:0] mem [0:255];`, `sub u0 [3:0] (...)`. Verible writes + `mem[0:255]` and `u0[3:0]`; packed dimensions after a type keyword do take a + space in both. Whichever way this lands, it should be stated in `README.md` + next to the "tight dimension expressions" rule. +- A long operator chain indents its first operand two columns less than the + rest: + + ```verilog + assign ready_signal = + first_condition_name && + second_condition_name && + third_condition_name; + ``` + + A flat chain reads better all at one indent. +- `timeunit 1ns/1ps;` becomes `timeunit 1ns / 1ps;` — the `/` there is a + separator, not a division operator. +- `initial begin` cuddles, but `initial fork` does not: `initial` and `fork` + end up on separate lines. +- A blank line between a leading comment and the item it documents is removed + (`// between\n\nmodule b;` → `// between\nmodule b;`). Reasonable, since the + comment binds to the following item, but it is a silent change. +- `typedef struct packed {...}` always breaks one member per line even when it + would fit; enums break only when they must. + +## Work log + +**2026-08-18 — dev agent** + +- Wrote `crates/vlog_formatter/tests/cases.rs`. Chose the `====` / `----` + plain-text format over one-file-per-case (thousands of tiny files) and over + a Rust `&[(&str, &str)]` table (unreadable escaping for multi-line Verilog). + The whole harness is one integration test that collects all failures before + asserting, so a behavior change shows every affected case at once. +- Added `#SKIP`, which was not in the original plan, once the first + genuinely-broken input turned up. Without it the choice would have been + between committing a red test and losing the finding; with it, the wanted + output is committed and the case flips green when the bug is fixed. +- Derived every expected output by piping the input through + `target/debug/vfmt -`, then reviewed each one by hand against the "Style" + section of the top-level `README.md`. Four outputs failed that review and + became the `#SKIP` cases; six more are recorded above as style observations + where the output is defensible but debatable. +- Mid-run the correctness-safety-net agent landed `src/verify.rs`, which made + bugs 1-3 hard errors instead of quietly wrong output. Rebuilt and + re-derived every expected output against the new binary; no passing case + changed. Confirmed `verify.rs` deliberately whitelists the `@*` → `@(*)` + spelling, so the `always @*` case keeps `@(*)` as expected output. +- 183 cases total, 179 asserted, 4 `#SKIP`. `cargo test` green, + `cargo clippy --all-targets` reports nothing for `tests/cases.rs`, + `cargo fmt --check` reports nothing for `tests/cases.rs` (it does report + pre-existing diffs across `src/` files owned by other agents). + +## QA log + +**2026-08-18 — QA agent** + +Ran the full check suite, audited `tests/cases.rs` line by line with deliberate +probe `.cases` files (added, exercised, then deleted — none left in the +tree), spot-checked case output against the top-level `README.md` Style +section (read essentially every case across all 10 files, not just a +sample), and reproduced all four `#SKIP` bugs by temporarily stripping the +`#SKIP` prefix in the actual `.cases` files and re-running `cargo test`, +then restoring them byte-for-byte (`diff` confirmed clean). + +**Results** + +- `cargo test` (full workspace): green. `cases_table` reports 179 asserted + (183 parsed − 4 skip), matching the claimed count exactly; independently + recounted per-file with a script and got the same 17/18/14/26/18/26/22/12/ + 15/15 = 183, 4 skip. +- `cargo clippy --all-targets`: 4 pre-existing warnings, none in + `tests/cases.rs` (`format.rs` dead_code, `printer.rs` manual_repeat_n, + `parser.rs` if_same_then_else x2). Confirmed via `grep -i cases.rs` on the + clippy output. +- `cargo fmt --check`: 151 diff blocks across `src/`, none in + `tests/cases.rs`. Did not run in write mode. +- Un-skipping all four `#SKIP` cases at once and re-running + `cargo test -p vlog_formatter --test cases` reproduces exactly the four + documented failures, with error text matching the README's bug write-ups + verbatim (idempotency divergence at line 3, token-stream divergence at + index 9/12, and the un-indented multi-instance continuation). Also + reproduced each bug independently via `target/debug/vfmt -` on a minimal + repro; error messages match character-for-character. + +**Findings** + +*Should-fix* + +1. **Stale `#SKIP` cases are not detected.** `cases.rs:138-140` `continue`s + on `case.skip` before ever calling `format_source`, so a case marked + `#SKIP` that quietly starts passing (bug fixed elsewhere, or a bad + `#SKIP` added by mistake) gives zero signal — `cargo test` stays green + forever. Verified by adding a `#SKIP`-tagged case whose expected output + already matches actual output today; the suite reports `ok` with no + indication anything is skipped. Since the whole point of `#SKIP` (per + this README) is "delete the line the moment the bug is fixed," nothing + currently prompts that deletion. A cheap fix would be to assert skipped + cases *do* fail (i.e., invert the check) so a newly-passing case turns + into a failure demanding the `#SKIP` be removed — that's a design change + for the dev agent to consider, not something I should make. +2. **A bare `----` or `====` line inside case *content* (e.g. a block-comment + ASCII banner) silently misparses instead of erroring clearly.** Probed + with a case whose input contains a legitimate `/* ---- */` banner line; + the harness split the case at the banner instead of the real `----` + separator, and the failure surfaced as an opaque `lex error: unterminated + block comment` rather than anything pointing at the ambiguity. No + existing case triggers this (checked all 10 files for bare `----`/`====` + lines outside separators — none found), so it's latent, not live. Worth + a one-line callout in the "File format" section warning case authors off + using bare `----`/`====` as content, since bug #1 (block comments) is + exactly the kind of case most likely to grow a banner divider later. +3. **Coverage gaps against `README.md` "Supported syntax":** no case + exercises a `final` block (`initial`/`final` are both listed as + supported), and no case exercises a bare module-level `case` without a + `generate` wrapper (module-level `if`/`for` both have non-generate cases + in `generate.cases`, `case` doesn't). Confirmed both parse and format + correctly via `target/debug/vfmt -` — the formatter isn't wrong, the + table just doesn't pin either down. Minor others: `always` with a + comma-separated (not `or`-separated) sensitivity list, multiple `import` + statements in one module. None of these are blocking; they're the kind + of gap the TODO already flags generally ("port more cases … the count + should grow by an order of magnitude"). +4. **The "defensible style observations" list has no case backing the + `initial fork` claim.** The README's style-observations section states + "`initial begin` cuddles, but `initial fork` does not." I confirmed this + is true (`target/debug/vfmt -` on `initial fork ... join` puts `initial` + and `fork` on separate lines), but no `.cases` file actually contains an + `initial fork` (only `fork` nested inside `initial begin`, in + `statements.cases`). The other five observations are backed by real + cases (unpacked-dim spacing: `declarations.cases`/`instantiation.cases`; + operator-chain indent and the exactly-100-column boundary: + `expressions.cases`; `timeunit` spacing and blank-line-after-comment + collapse: `module_headers.cases`/`comments.cases`; struct-always-breaks: + `typedef.cases`). None of the six observations actually contradict a + written Style rule — all are about behavior the Style section is simply + silent on, so "defensible" is the right call for all six. + +*Nit* + +5. `README.md`'s bug #4 write-up says the one-line multi-instance form "is + 30 columns wide"; the actual wanted output (` sub u0 (.a(x)), u1 + (.a(y));`) is 29 columns. Off by one, cosmetic only, not fixing since it + doesn't affect the finding. +6. The File-format section describes `#SKIP` as "a case whose name + *contains* SKIP," but the parser (`split_case`, `cases.rs:57-60`) only + sets the skip flag when a `#`-line *starts with* `SKIP` after trimming, + not when `SKIP` appears anywhere in the assembled name. Harmless today — + all four real `#SKIP` cases use the line-initial form the code expects — + but a future case author relying on the literal wording could write + `# note: might SKIP this` expecting it to be skipped and be wrong. + +**Harness audit (no bugs found beyond the above)** + +- Discovery (`cases_dir`/`read_dir`) panics loudly if the directory is + missing (`.expect("cases dir")`); an empty-but-present directory is + caught by `assert!(!files.is_empty(), ...)`. Neither path passes + vacuously. (Verified by code inspection only — did not delete the real + directory to test live, to avoid disturbing other in-flight work.) +- Last case needing no trailing `====`: verified live (probe file, single + case, no trailing separator, parsed and ran correctly). +- Missing `----` separator: verified live, fails loudly with correct + `file:line` (`zz_probe2.cases:1: case has no ` + "`----`" + ` separator`). +- CRLF line endings: verified live with a CRLF-only probe file; `str::lines` + strips the `\r`, no corruption, case parses and runs correctly. No CRLF + files exist in the real `tests/cases/` tree today. +- Blank lines directly after a `====` separator (before the next case's + name/content) were checked for across all 10 files — none exist, so the + theoretical off-by-one in `start` line tracking (a blank line right after + `====` would itself become `start`, one line before the name) is latent, + not live. +- No case has an empty input or empty expected half (checked + programmatically across all 10 files). +- `file:line` accuracy for a failure in the *second* case of a file + (not just the first) was verified live and points at the exact line of + the case's `#` header, not the file start or the previous case. +- Diff rendering (`-` expected / `+` got) matches its documented convention, + confirmed on a live failing probe case. + +**Spot-check of case quality** + +Read essentially all 183 cases (not just ~20) against the Style section. +Nothing found where an expected output was rubber-stamping formatter +behavior that contradicts a *written* Style rule — the closest candidates +(unpacked-dim spacing, operator-chain indent, struct-always-breaks) are all +already called out as observations, and none of them contradict a stated +rule since the Style section doesn't speak to any of them. The "exactly 100 +columns stays on one line" case (`expressions.cases:231`) was checked +byte-for-byte: the expected line is exactly 100 columns. All four `#SKIP` +expected outputs match the "wanted" output described in the bug write-ups +and are not what the formatter currently produces (confirmed above). + +**Claim verdicts** + +1. Harness behavior (discovery, `====`/`----`/`#`/`#SKIP` parsing, dual + assertion, collected failures with file:line + diff): **pass**, with + should-fix findings #1 and #2 above (both about corner cases the current + design doesn't defend against, not about anything mis-implemented + relative to the documented spec). +2. 183 cases (179 asserted + 4 SKIP) across 10 files, hand-reviewed against + Style: **pass**, counts verified independently; found no case that + contradicts a written rule. +3. Four suspected bugs + six style observations: **pass**. All four bugs + reproduce exactly as documented (byte-identical error messages) both via + the harness and via the standalone binary. Five of six observations are + directly backed by a case; the sixth (`initial fork`) is true but + untested (finding #4). + +## Review + +**2026-08-18 — lead. Verdict: accepted and committed, with three lead fixes.** + +Good work on both sides. The harness is exactly the right size (~180 lines, +std only), the format is readable, and the dev agent's decision to report +formatter bugs instead of rubber-stamping output is the most valuable thing +this feature produced — all four bugs are real, and two of them break hard +invariants. The QA pass was genuinely adversarial (probe files, un-skip + +restore, byte-level recounts) and left the tree clean; that is the standard +going forward. + +Changes I made while accepting (small and unambiguous, so lead-fixed rather +than another dev round): + +1. **Inverted `#SKIP` semantics** (QA finding 1): a `#SKIP` case must still + *fail*; if it starts passing the suite now fails with "remove the #SKIP + marker". `tests/cases.rs` gained a small `passes()` helper. Verified: all + four parked bugs still fail, suite green. +2. **File-format doc corrections** (QA findings 2 and 6): documented the + line-initial `#SKIP` rule as implemented, and warned against bare + `----`/`====` banner lines inside case content. The parser was right; + the prose was loose. +3. **Coverage gaps → TODO** (QA findings 3 and 4): `final`, bare module-level + `case`, `initial fork`, comma sensitivity lists, multiple imports — + recorded as an unchecked TODO item for the next dev round on this feature, + not silently dropped. + +Direction for the next round: the four suspected bugs move to a dedicated +fix feature (they are formatter work, not test work); the six style +observations should each get a one-line ruling in the top-level `README.md` +Style section once decided — the QA agent is right that "defensible" only +holds while the Style section is silent. diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..2a35f02 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1 @@ +use_small_heuristics = "Max"