diff --git a/TODO.md b/TODO.md index dc6ade9..9df33ed 100644 --- a/TODO.md +++ b/TODO.md @@ -1588,3 +1588,53 @@ docs/features/completion-core/README.md, TODO.md §13. architecture, same order of magnitude, still within the ~1.1 ms absolute framing the lead already accepted. See the feature README's QA log for the full latency table and repro. + +## 14. Null items wave (2026-09-01) — owner report "for loop inside generate" + +Lead diagnosis: the generate-for itself parses in every spelling +(genvar in the header, declared outside, region-less; the three +systemverilog.io examples all round-trip). What fails is the stray +`;` the owner wrote after `endgenerate` — a **null item**, legal SV +(IEEE 1800-2017 A.1.4 `package_or_generate_item_declaration ::= … | ;` +and `class_item ::= … | ;`; slang warns `-Wempty-member`, "an +unnecessary semicolon in a non-procedural scope"). Rejected today at +module scope, inside `generate…endgenerate`, after a generate block's +`end`, in package/interface/class bodies and at file scope; the +procedural null *statement* already works; `endfunction;`/`endtask;` +already survive via `end_semi`. Single lane. Files: +crates/vlog_parser/src/{ast.rs,parser.rs}, crates/vlog_parser/tests/ +spans.rs, crates/vlog_formatter/src/format.rs (+align.rs only if a +group rule needs it), crates/vlog_formatter/tests/cases/ +null_items.cases (new), crates/vlog_formatter/tests/verification.rs, +crates/vlog_semantic/src/bind.rs (arm), crates/vlog_linter/src/ +rules/empty_item.rs (new) + registry + a .lint case + rule docs, +compile-fix arms elsewhere as the compiler demands (listed in +Handshakes), docs/features/null-items/README.md (new), TODO.md §14. + +- [x] **`ItemKind::Empty`** — a first-class null item wherever an + item may appear (module, generate region, generate-block body, + package, interface, program, class body, file scope), span = + the `;` token, comments attached through the ordinary `Meta`. + No cascade: tolerant mode emits no diagnostic for it. +- [x] **Formatter layout, token-preserving**: a null item on the same + line as the previous item's last token prints glued + (`endgenerate;`, `end;`, `;;`); one on its own line prints `;` + at the current indent. Idempotent both ways; alignment groups + are not joined across it. Corpus byte-identical (813/820). +- [x] **Blast radius arms**: `format.rs`, `bind.rs`, `tests/spans.rs` + (+ any other exhaustive match the compiler names). +- [x] **Safety-net template**: `verify.rs` untouched; rejection pairs + added anyway (dropped `;`, `;` moved across a comment, `;` + moved into a procedural block). +- [x] **Lint `empty-item`** (slang's `-Wempty-member`): warn on a null + item, safe auto-fix removes it; default on; `.lint` case with + the fix output verified by the harness. +- [x] **Online-example pins**: the three systemverilog.io generate + examples (16-input mux, arbiter assertions, nested memory case) + as formatter cases, plus the owner's `endgenerate;` shape and + slang's two warning examples. +- [x] **QA**: adversarial null-item placements (before/after + directives, between `` `ifdef `` arms, after attributes, with + trailing/leading comments, CRLF), idempotency, opentitan sweep + unchanged at 11 failures (read-only), LSP diagnostics show the + lint (not a parse error) with the quick fix. diff --git a/crates/vlog_formatter/src/format.rs b/crates/vlog_formatter/src/format.rs index afb99b7..cc8eee9 100644 --- a/crates/vlog_formatter/src/format.rs +++ b/crates/vlog_formatter/src/format.rs @@ -902,19 +902,55 @@ impl<'a> Fmt<'a> { fn item_seq(&self, items: &[Item], depth: usize) -> Vec { let aligns = self.param_decl_aligns(items, depth); let mut docs = Vec::new(); + // The last item that actually emitted something, which is what a + // glued null item glues to. + let mut prev: Option<&Item> = None; for (item, align) in items.iter().zip(&aligns) { let item_docs = self.item_docs(item, align.as_ref(), depth); if item_docs.is_empty() { continue; } - if !docs.is_empty() { + if !docs.is_empty() && !prev.is_some_and(|p| self.glued_null_item(p, item)) { docs.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); } docs.extend(item_docs); + prev = Some(item); } docs } + /// True when `item` is a null item (`;`) the source wrote on the line the + /// item before it ended on, which is how it is printed back: + /// `endgenerate;`, `end;`, `endmodule;`, `;;`. + /// + /// The question is asked of the source rather than of the AST because it + /// is a layout fact about the gap between two siblings, and this is the + /// one place that gap is laid out — the same reason `eq_offset` and + /// `default_has_colon` read `src` here. A null item that begins a body has + /// no sibling to glue to and prints on its own line. + /// + /// Anything that gives the `;` docs of its own — a leading comment, an + /// attribute, a blank line, a format-off fence opening on it — takes the + /// own-line path instead, so the glue only ever appends a bare `;`. Note + /// that a `//` comment cannot stand in a newline-free gap: it would + /// swallow the `;` that follows it. The only comment that fits is a + /// one-line block comment, which prints inline before the `;`, in the + /// order it was written. + fn glued_null_item(&self, prev: &Item, item: &Item) -> bool { + if !matches!(item.kind, ItemKind::Empty) { + return false; + } + if item.meta.blank_before || !item.meta.leading.is_empty() || !item.meta.attrs.is_empty() { + return false; + } + if self.is_verbatim(item.span) || self.opens_at(item.span.start as usize).is_some() { + return false; + } + self.src + .get(prev.span.end as usize..item.span.start as usize) + .is_some_and(|gap| !gap.contains('\n')) + } + fn stmt_seq(&self, stmts: &[Stmt]) -> Vec { let mut docs = Vec::new(); for (i, s) in stmts.iter().enumerate() { @@ -1113,6 +1149,9 @@ impl<'a> Fmt<'a> { ItemKind::Modport(decls) => self.modport(decls), ItemKind::Clocking(c) => self.clocking(c), ItemKind::Verbatim(raw) => self.raw_text(raw), + // A null item is its `;`. Whether it keeps the previous item's + // line or takes one of its own is `item_seq`'s call. + ItemKind::Empty => text(";"), ItemKind::Defparam(pairs) => { let parts: Vec = pairs .iter() diff --git a/crates/vlog_formatter/tests/cases/null_items.cases b/crates/vlog_formatter/tests/cases/null_items.cases new file mode 100644 index 0000000..9d03e87 --- /dev/null +++ b/crates/vlog_formatter/tests/cases/null_items.cases @@ -0,0 +1,327 @@ +# the owner's report: a stray `;` after `endgenerate` +module m #(parameter int N = 4) (input logic [N-1:0] a, output logic [N-1:0] y); + generate + for (genvar i = 0; i < N; i++) begin : g + assign y[i] = ~a[i]; + end + endgenerate; +endmodule +---- +module m #(parameter int N = 4) (input logic [N-1:0] a, output logic [N-1:0] y); + generate + for (genvar i = 0; i < N; i++) begin : g + assign y[i] = ~a[i]; + end + endgenerate; +endmodule +==== +# a null item on its own line at module scope +module m (input logic clk, output logic q); + always_ff @(posedge clk) q <= ~q; + ; +endmodule +---- +module m (input logic clk, output logic q); + always_ff @(posedge clk) q <= ~q; + ; +endmodule +==== +# slang's -Wempty-member example: `module m; ; endmodule` +module m; ; endmodule +---- +module m; + ; +endmodule +==== +# a null item that opens a generate region takes its own line +module m; generate ; endgenerate endmodule +---- +module m; + generate + ; + endgenerate +endmodule +==== +# `end;` after a generate block inside a region +module m #(parameter int N = 2) (output logic [N-1:0] y); + generate + for (genvar i = 0; i < N; i++) begin : g + assign y[i] = 1'b0; + end; + endgenerate +endmodule +---- +module m #(parameter int N = 2) (output logic [N-1:0] y); + generate + for (genvar i = 0; i < N; i++) begin : g + assign y[i] = 1'b0; + end; + endgenerate +endmodule +==== +# region-less `end;`, and `;;` after it +module m #(parameter int N = 2) (output logic [N-1:0] y); + if (N > 1) begin : g1 + assign y = '0; + end; + ;; +endmodule +---- +module m #(parameter int N = 2) (output logic [N-1:0] y); + if (N > 1) begin : g1 + assign y = '0; + end; + ;; +endmodule +==== +# a null item in a package body +package p; + localparam int W = 1; + ; +endpackage +---- +package p; + localparam int W = 1; + ; +endpackage +==== +# a null item in an interface body +interface ifc; + logic a; + ; +endinterface +---- +interface ifc; + logic a; + ; +endinterface +==== +# a null item in a class body +class c; + int x; + ; +endclass +---- +class c; + int x; + ; +endclass +==== +# `endmodule;` — a null item at file scope +module m; +endmodule; +---- +module m; +endmodule; +==== +# glued stays glued: the output of the owner's shape formats to itself +module m; + generate + endgenerate; +endmodule +---- +module m; + generate + endgenerate; +endmodule +==== +# own-line stays own-line +module m; + wire a; + ; +endmodule +---- +module m; + wire a; + ; +endmodule +==== +# a trailing comment after a glued `;` stays on that line +module m; + generate + endgenerate; // note +endmodule +---- +module m; + generate + endgenerate; // note +endmodule +==== +# a leading comment keeps the `;` on a line of its own +module m; + wire a; + // why the semicolon is here + ; +endmodule +---- +module m; + wire a; + // why the semicolon is here + ; +endmodule +==== +# a blank line before a null item is kept, and unglues it +module m; + wire a; + + ; +endmodule +---- +module m; + wire a; + + ; +endmodule +==== +# a block comment between the item and its `;` keeps its place +module m; + generate endgenerate /* b */ ; +endmodule +---- +module m; + generate + endgenerate /* b */; +endmodule +==== +# a null item splits an alignment group +module m; + localparam int A = 1; + localparam int LONGER = 22; + ; + localparam int B = 3; + localparam int OTHER = 44; +endmodule +---- +module m; + localparam int A = 1; + localparam int LONGER = 22; + ; + localparam int B = 3; + localparam int OTHER = 44; +endmodule +==== +# the null *statement* is untouched (slang's -Wempty-stmt example) +module m; + initial begin + ; + end +endmodule +---- +module m; + initial begin + ; + end +endmodule +==== +# `endfunction;`/`endtask;` still print through `end_semi`, not as null items +module m; + function int f(); return 1; endfunction; + task t(); endtask; +endmodule +---- +module m; + function int f(); + return 1; + endfunction; + task t(); + endtask; +endmodule +==== +# systemverilog.io: a 16-input mux built with a generate for +module mux16 (input logic [3:0] select, input logic [15:0] mux_in, output logic mux_out); + logic [15:0] temp; + genvar i; + generate + for (i=0; i < 16; i++) begin + assign temp[i] = (select == i) ? mux_in[i] : 0; + end + endgenerate + assign mux_out = |temp; +endmodule +---- +module mux16 (input logic [3:0] select, input logic [15:0] mux_in, output logic mux_out); + logic [15:0] temp; + genvar i; + generate + for (i = 0; i < 16; i++) begin + assign temp[i] = (select == i) ? mux_in[i] : 0; + end + endgenerate + assign mux_out = |temp; +endmodule +==== +# systemverilog.io: `assert property` inside a generate for +module arb_sva (input logic clk, input logic [7:0] req, input logic [7:0] ack); + genvar k; + generate + for (k=0; k < 8; k++) begin + req_a: assert property (@(posedge clk) req[k] |=> ack[k]); + end + endgenerate +endmodule +---- +module arb_sva (input logic clk, input logic [7:0] req, input logic [7:0] ack); + genvar k; + generate + for (k = 0; k < 8; k++) begin + req_a: assert property (@(posedge clk) req[k] |=> ack[k]); + end + endgenerate +endmodule +==== +# systemverilog.io: a generate case with a nested for and instantiations +module mem #(parameter MEM_SIZE = 8, parameter MEM_WIDTH = 16) ( + input clk, input csx, input cke, input [1:0] ba, input [11:0] addr, + input rasx, input casx, input wex, input [7:0] dqm, inout [63:0] data, input [3:0] dev_id); + genvar i; + case ({MEM_SIZE, MEM_WIDTH}) + {32'd8, 32'd16}: + begin: memory + for (i=0; i<4; i=i+1) begin:word16 + sms_08b216t0 p(.clk(clk), .csb(csx), .cke(cke),.ba(ba), + .addr(addr), .rasb(rasx), .casb(casx), + .web(wex), .udqm(dqm[2*i+1]), .ldqm(dqm[2*i]), + .dqi(data[15+16*i:16*i]), .dev_id(dev_id)); + end + end + endcase +endmodule +---- +module mem #( + parameter MEM_SIZE = 8, + parameter MEM_WIDTH = 16 +) ( + input clk, + input csx, + input cke, + input [1:0] ba, + input [11:0] addr, + input rasx, + input casx, + input wex, + input [7:0] dqm, + inout [63:0] data, + input [3:0] dev_id +); + genvar i; + case ({MEM_SIZE, MEM_WIDTH}) + {32'd8, 32'd16}: begin : memory + for (i = 0; i < 4; i = i + 1) begin : word16 + sms_08b216t0 p ( + .clk(clk), + .csb(csx), + .cke(cke), + .ba(ba), + .addr(addr), + .rasb(rasx), + .casb(casx), + .web(wex), + .udqm(dqm[2*i+1]), + .ldqm(dqm[2*i]), + .dqi(data[15+16*i:16*i]), + .dev_id(dev_id) + ); + end + end + endcase +endmodule diff --git a/crates/vlog_formatter/tests/verification.rs b/crates/vlog_formatter/tests/verification.rs index be64170..f5bf9a8 100644 --- a/crates/vlog_formatter/tests/verification.rs +++ b/crates/vlog_formatter/tests/verification.rs @@ -1486,3 +1486,75 @@ fn a_default_disable_carrying_a_dist_set_keeps_every_byte() { "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", + ); +} diff --git a/crates/vlog_linter/src/registry.rs b/crates/vlog_linter/src/registry.rs index 7234422..f4d1abf 100644 --- a/crates/vlog_linter/src/registry.rs +++ b/crates/vlog_linter/src/registry.rs @@ -44,6 +44,7 @@ pub fn all_rules() -> Vec<&'static dyn Rule> { &rules::always_comb_blocking::AlwaysCombBlocking, &rules::always_ff_non_blocking::AlwaysFfNonBlocking, &rules::case_missing_default::CaseMissingDefault, + &rules::empty_item::EmptyItem, &rules::enum_name_style::EnumNameStyle, &rules::explicit_parameter_storage_type::ExplicitParameterStorageType, &rules::module_filename::ModuleFilename, diff --git a/crates/vlog_linter/src/rules/empty_item.rs b/crates/vlog_linter/src/rules/empty_item.rs new file mode 100644 index 0000000..5a0f549 --- /dev/null +++ b/crates/vlog_linter/src/rules/empty_item.rs @@ -0,0 +1,189 @@ +//! `empty-item` — no stray `;` where an item belongs. + +use crate::context::LintContext; +use crate::registry::Rule; +use crate::violation::{Applicability, Fix, Violation}; +use crate::visit::walk_items; +use vlog_parser::ast::ItemKind; +use vlog_parser::span::TextRange; + +/// See [`Rule::doc`]. +pub struct EmptyItem; + +const NAME: &str = "empty-item"; + +impl Rule for EmptyItem { + fn name(&self) -> &'static str { + NAME + } + + fn summary(&self) -> &'static str { + "drop a `;` that stands where an item belongs" + } + + fn doc(&self) -> &'static str { + "A lone `;` in a module, generate, package, interface, program or class \ + body is a *null item* (IEEE 1800-2017 A.1.4). It is legal and it means \ + nothing, so it is almost always a typo — the habit of ending a block \ + with a semicolon, carried over from C or from a statement context: \ + `endgenerate;`, `end;`, `endmodule;`. slang reports the same thing as \ + `-Wempty-member` (\"an unnecessary semicolon is located in a \ + non-procedural scope\"). The fix deletes the `;`, and the line with it \ + when the line held nothing else; a comment written on that line is \ + kept. The procedural null *statement* (`begin ; end`) is a different \ + construct and is not reported here." + } + + fn fix(&self) -> Option { + Some(Applicability::Safe) + } + + fn check(&self, ctx: &LintContext) -> Vec { + let src = ctx.source(); + let mut out = Vec::new(); + walk_items(ctx.file(), &mut |item| { + if !matches!(item.kind, ItemKind::Empty) { + return; + } + let mut violation = + Violation::new(NAME, "unnecessary `;`; a null item does nothing", item.span); + if let Some(range) = deletion(src, item.span) { + violation = violation.with_fix(Fix::safe(vec![(range, String::new())])); + } + out.push(violation); + }); + out + } +} + +/// The bytes to delete for the null item at `semi`: the `;`, the horizontal +/// whitespace before it on its line, and — when nothing but whitespace and +/// other null items shared that line — the line's newline too. +/// +/// `None` when the range would cover anything but `;` and whitespace, which +/// cannot happen given how it is built and is checked anyway: a fix that +/// swallowed a comment would break a hard invariant, so the guard is cheaper +/// than the risk. +fn deletion(src: &str, semi: TextRange) -> Option { + let bytes = src.as_bytes(); + let mut start = semi.start as usize; + while start > 0 && matches!(bytes[start - 1], b' ' | b'\t') { + start -= 1; + } + let mut end = semi.end as usize; + // The rest of the line: only whitespace means the line can go, but only if + // what stood before this `;` on it was whitespace and null items — a `;` + // written after real code leaves that code, and its line, alone. + let mut after = end; + while matches!(bytes.get(after), Some(b' ' | b'\t' | b'\r')) { + after += 1; + } + let line_is_ours = src[line_start(src, start)..start] + .bytes() + .all(|b| matches!(b, b' ' | b'\t' | b';' | b'\r')); + if line_is_ours { + match bytes.get(after) { + Some(b'\n') => end = after + 1, + // A last line with no newline of its own. + None => end = after, + _ => {} + } + } + let range = TextRange::new(start as u32, end as u32); + src.get(range.as_range())? + .bytes() + .all(|b| matches!(b, b';' | b' ' | b'\t' | b'\r' | b'\n')) + .then_some(range) +} + +/// Byte offset of the start of the line `at` sits on. +fn line_start(src: &str, at: usize) -> usize { + src[..at].rfind('\n').map_or(0, |i| i + 1) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::violation::apply_fixes; + + fn violations(src: &str) -> Vec { + EmptyItem.check(&LintContext::new(src, None)) + } + + fn fix(src: &str) -> String { + apply_fixes(src, &violations(src), false).output + } + + #[test] + fn the_owners_shape_is_reported_and_the_semicolon_alone_is_removed() { + let src = "module m;\n generate\n endgenerate;\nendmodule\n"; + let found = violations(src); + assert_eq!(found.len(), 1); + assert_eq!(found[0].rule, NAME); + assert_eq!(&src[found[0].span.as_range()], ";"); + assert_eq!(fix(src), "module m;\n generate\n endgenerate\nendmodule\n"); + } + + #[test] + fn a_null_item_on_its_own_line_takes_the_line_with_it() { + let src = "module m;\n wire a;\n ;\nendmodule\n"; + assert_eq!(fix(src), "module m;\n wire a;\nendmodule\n"); + } + + #[test] + fn a_comment_on_the_line_survives_the_fix() { + let src = "module m;\n generate\n endgenerate; // note\nendmodule\n"; + assert_eq!(fix(src), "module m;\n generate\n endgenerate // note\nendmodule\n"); + + let src = "module m;\n wire a;\n ; // why\nendmodule\n"; + let fixed = fix(src); + assert!(fixed.contains("// why"), "the comment was dropped:\n{fixed}"); + } + + #[test] + fn a_leading_comment_is_left_where_it_was() { + let src = "module m;\n // why\n ;\nendmodule\n"; + assert_eq!(fix(src), "module m;\n // why\nendmodule\n"); + } + + #[test] + fn a_run_of_null_items_is_one_finding_each_and_the_line_goes() { + let src = "module m;\n wire a;\n ;;;\nendmodule\n"; + assert_eq!(violations(src).len(), 3); + assert_eq!(fix(src), "module m;\n wire a;\nendmodule\n"); + } + + #[test] + fn every_item_scope_is_reached() { + let sources = [ + "module m;\nendmodule;\n", + "module m;\n ;\nendmodule\n", + "interface ifc;\n ;\nendinterface\n", + "package p;\n ;\nendpackage\n", + "class c;\n ;\nendclass\n", + "module m;\n generate\n ;\n endgenerate\nendmodule\n", + "module m;\n for (genvar i = 0; i < 2; i++) begin : g\n ;\n end\nendmodule\n", + ]; + for src in sources { + assert_eq!(violations(src).len(), 1, "{src}"); + } + } + + #[test] + fn the_procedural_null_statement_is_not_this_rule() { + assert!(violations("module m;\n initial begin\n ;\n end\nendmodule\n").is_empty()); + } + + #[test] + fn endfunction_and_endtask_semicolons_are_not_reported() { + // They are recorded on the declaration, not as null items. + let src = + "module m;\n function int f();\n endfunction;\n task t();\n endtask;\nendmodule\n"; + assert!(violations(src).is_empty()); + } + + #[test] + fn a_clean_file_is_clean() { + assert!(violations("module m;\n wire a;\nendmodule\n").is_empty()); + } +} diff --git a/crates/vlog_linter/src/rules/mod.rs b/crates/vlog_linter/src/rules/mod.rs index b80ca0e..eecdd84 100644 --- a/crates/vlog_linter/src/rules/mod.rs +++ b/crates/vlog_linter/src/rules/mod.rs @@ -8,6 +8,7 @@ pub mod always_comb_blocking; pub mod always_ff_non_blocking; pub mod case_missing_default; +pub mod empty_item; pub mod enum_name_style; pub mod explicit_parameter_storage_type; pub mod module_filename; diff --git a/crates/vlog_linter/tests/cases/empty_item.lint b/crates/vlog_linter/tests/cases/empty_item.lint new file mode 100644 index 0000000..3b6d9aa --- /dev/null +++ b/crates/vlog_linter/tests/cases/empty_item.lint @@ -0,0 +1,181 @@ +# the owner's report: a stray `;` after `endgenerate` +module m; + generate + endgenerate; +//^ 14 empty-item +endmodule +==== +# a null item on its own line at module scope +module m; + wire a; + ; +//^ 3 empty-item +endmodule +==== +# `endmodule;` — a null item at file scope +module m; +endmodule; +//^ 10 empty-item +==== +# every non-procedural scope is reached: package +package p; + localparam int W = 1; + ; +//^ 3 empty-item +endpackage +==== +# every non-procedural scope is reached: interface +interface ifc; + logic a; + ; +//^ 3 empty-item +endinterface +==== +# every non-procedural scope is reached: class +class c; + int x; + ; +//^ 3 empty-item +endclass +==== +# every non-procedural scope is reached: inside a generate region +module m; + generate + ; +//^ 5 empty-item + endgenerate +endmodule +==== +# every non-procedural scope is reached: inside a generate-for body +module m; + for (genvar i = 0; i < 2; i++) begin : g + ; +//^ 5 empty-item + end +endmodule +==== +# `end;` after a generate block, and a run of null items after it +module m; + if (N > 1) begin : g1 + wire x; + end; +//^ 6 empty-item + ;; +//^ 3 empty-item +//^ 4 empty-item +endmodule +==== +# the procedural null statement is a different construct and is quiet +module m; + initial begin + ; + end +endmodule +==== +# `endfunction;` / `endtask;` are recorded on the declaration, not as null items +module m; + function int f(); + endfunction; + task t(); + endtask; +endmodule +==== +# waived on the same line +module m; + wire a; + ; // lucisv: waive empty-item +endmodule +==== +# a clean file is clean +module m; + wire a; +endmodule +==== +# fix: the `;` alone goes, the closing keyword stays +module m; + generate + endgenerate; +//^ 14 empty-item +endmodule +---- +module m; + generate + endgenerate +//^ 14 empty-item +endmodule +==== +# fix: a null item alone on its line takes the line with it +module m; + wire a; + ; +//^ 3 empty-item +endmodule +---- +module m; + wire a; +//^ 3 empty-item +endmodule +==== +# fix: a run of null items leaves no blank line behind +module m; + wire a; + ;;; +//^ 3 empty-item +//^ 4 empty-item +//^ 5 empty-item +endmodule +---- +module m; + wire a; +//^ 3 empty-item +//^ 4 empty-item +//^ 5 empty-item +endmodule +==== +# fix: a comment written after the `;` survives it +module m; + generate + endgenerate; // note +//^ 14 empty-item +endmodule +---- +module m; + generate + endgenerate // note +//^ 14 empty-item +endmodule +==== +# fix: a comment on a null item's own line keeps the line alive +module m; + wire a; + ; // why it was here +//^ 3 empty-item +endmodule +---- +module m; + wire a; + // why it was here +//^ 3 empty-item +endmodule +==== +# fix: a comment written above a null item stays where it was +module m; + // why it was here + ; +//^ 3 empty-item +endmodule +---- +module m; + // why it was here +//^ 3 empty-item +endmodule +==== +# fix: `endmodule;` at file scope +module m; +endmodule; +//^ 10 empty-item +---- +module m; +endmodule +//^ 10 empty-item +==== diff --git a/crates/vlog_parser/src/ast.rs b/crates/vlog_parser/src/ast.rs index 62f9bfc..7cf723a 100644 --- a/crates/vlog_parser/src/ast.rs +++ b/crates/vlog_parser/src/ast.rs @@ -247,6 +247,18 @@ pub enum ItemKind { /// `docs/features/assertions/README.md` for why each one is verbatim. Verbatim(RawText), Defparam(Vec<(Expr, Expr)>), + /// A **null item**: a lone `;` standing where an item belongs + /// (IEEE 1800-2017 A.1.4 `package_or_generate_item_declaration ::= … | ;` + /// and `class_item ::= … | ;`). Legal and meaningless in every item + /// scope, and written constantly after `endgenerate`, after a generate + /// block's `end` and after `endmodule`. The span is the `;` itself; the + /// `empty-item` lint is what tells the user about it. + /// + /// The `;` after `endfunction`/`endtask` is *not* one of these: it is + /// consumed inside the declaration and recorded as + /// [`FunctionDecl::end_semi`] / [`TaskDecl::end_semi`], which predates + /// this variant. + Empty, /// Source that could not be parsed as an item, kept verbatim. /// /// Only error-tolerant parsing diff --git a/crates/vlog_parser/src/parser.rs b/crates/vlog_parser/src/parser.rs index f456d04..2046641 100644 --- a/crates/vlog_parser/src/parser.rs +++ b/crates/vlog_parser/src/parser.rs @@ -1413,6 +1413,14 @@ impl<'a> Parser<'a> { if self.at_macro_item() || self.at_spaced_macro_call() { return Ok(ItemKind::MacroItem(self.parse_macro_call()?)); } + // A null item. Nothing else in the item grammar starts with `;`, so + // one token settles it — and it is tested here rather than in the + // `TokenKind` match below because punctuation is matched by text + // everywhere in this file. See `ItemKind::Empty`. + if self.cur().is_sym(";") { + self.bump(); + return Ok(ItemKind::Empty); + } let t = self.cur(); match t.kind { TokenKind::Directive => { diff --git a/crates/vlog_parser/tests/null_items.rs b/crates/vlog_parser/tests/null_items.rs new file mode 100644 index 0000000..27202dd --- /dev/null +++ b/crates/vlog_parser/tests/null_items.rs @@ -0,0 +1,178 @@ +//! The null item — a lone `;` where an item belongs (IEEE 1800-2017 A.1.4 +//! `package_or_generate_item_declaration ::= … | ;` and `class_item ::= … | ;`). +//! See `docs/features/null-items/README.md`. +//! +//! Every item list in the parser reaches `parse_item_kind` through +//! `item_or_recover`, so one branch is meant to cover all eight scopes. That +//! claim is checked here by parsing one source per scope rather than by +//! reading the parser. + +use vlog_parser::ast::*; +use vlog_parser::{parse_source, parse_source_tolerant}; + +/// Parses `src` strictly and returns the tree; panics with the parse error. +fn tree(src: &str) -> SourceFile { + parse_source(src).unwrap_or_else(|e| panic!("{src}\n=> {e}")) +} + +/// Every null item in `file`, as its source slice — which must be `";"`. +fn null_item_slices(src: &str, file: &SourceFile) -> Vec { + let mut out = Vec::new(); + walk(&file.items, &mut |item| { + if matches!(item.kind, ItemKind::Empty) { + out.push(src[item.span.as_range()].to_string()); + } + }); + out +} + +fn walk(items: &[Item], f: &mut dyn FnMut(&Item)) { + for item in items { + f(item); + match &item.kind { + ItemKind::Module(m) => walk(&m.items, f), + ItemKind::Package { items, .. } => walk(items, f), + ItemKind::Class(c) => walk(&c.items, f), + ItemKind::GenerateRegion { items, .. } => walk(items, f), + ItemKind::GenFor(g) => walk(&g.body.items, f), + ItemKind::GenIf(g) => { + walk(&g.then.items, f); + let mut els = g.els.as_deref(); + while let Some(branch) = els { + match branch { + GenElse::If(_, nested) => { + walk(&nested.then.items, f); + els = nested.els.as_deref(); + } + GenElse::Block(block) => { + walk(&block.items, f); + els = None; + } + } + } + } + ItemKind::GenCase(g) => { + for case_item in &g.items { + walk(&case_item.body.items, f); + } + } + _ => {} + } + } +} + +/// One `;` per scope, and every one of them is an `ItemKind::Empty` whose span +/// is exactly the semicolon. +#[test] +fn a_null_item_parses_in_every_item_scope() { + let scopes = [ + ("file scope", "module m;\nendmodule;\n"), + ("module body", "module m;\n wire a;\n ;\nendmodule\n"), + ("interface body", "interface ifc;\n logic a;\n ;\nendinterface\n"), + ("program body", "program p;\n ;\nendprogram\n"), + ("package body", "package p;\n localparam int W = 1;\n ;\nendpackage\n"), + ("class body", "class c;\n int x;\n ;\nendclass\n"), + ("generate region", "module m;\n generate\n ;\n endgenerate\nendmodule\n"), + ( + "generate-for body", + "module m;\n for (genvar i = 0; i < 2; i++) begin : g\n ;\n end\nendmodule\n", + ), + ( + "generate-if body", + "module m;\n if (A) begin : g\n ;\n end else begin : h\n ;\n end\nendmodule\n", + ), + ( + "generate-case body", + "module m;\n case (A)\n 1: begin : g\n ;\n end\n endcase\nendmodule\n", + ), + ]; + for (what, src) in scopes { + let file = tree(src); + let found = null_item_slices(src, &file); + assert!(!found.is_empty(), "{what}: no null item parsed from\n{src}"); + assert!(found.iter().all(|s| s == ";"), "{what}: span is not the `;`: {found:?}"); + } +} + +/// The shape the owner reported, and its neighbours: a `;` after a closing +/// keyword rather than on a line of its own. +#[test] +fn a_semicolon_after_a_closing_keyword_is_a_null_item() { + let sources = [ + "module m;\n generate\n endgenerate;\nendmodule\n", + "module m;\n generate\n if (A) begin : g\n wire x;\n end;\n endgenerate\nendmodule\n", + "module m;\n if (A) begin : g\n wire x;\n end;\nendmodule\n", + "module m;\nendmodule;\n", + ]; + for src in sources { + let file = tree(src); + assert_eq!(null_item_slices(src, &file), vec![";"], "{src}"); + } +} + +/// `;;` is two of them, not one. +#[test] +fn repeated_semicolons_are_one_null_item_each() { + let src = "module m;\n ;;;\nendmodule\n"; + let file = tree(src); + assert_eq!(null_item_slices(src, &file).len(), 3); +} + +/// Comments ride the ordinary `Meta`, like any other item's. +#[test] +fn comments_around_a_null_item_are_kept() { + let src = "module m;\n // lead\n ; // trail\nendmodule\n"; + let file = tree(src); + let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; + let item = m.items.iter().find(|i| matches!(i.kind, ItemKind::Empty)).expect("a null item"); + assert_eq!(item.meta.leading.iter().map(|c| c.text.as_str()).collect::>(), ["// lead"]); + assert_eq!(item.meta.trailing.as_ref().map(|c| c.text.as_str()), Some("// trail")); +} + +/// Tolerant mode is silent about a null item: it is a successful parse, not a +/// recovery, so an editor shows the `empty-item` lint and no parse error. +#[test] +fn tolerant_parsing_reports_no_diagnostic() { + let sources = [ + "module m;\n generate\n endgenerate;\nendmodule\n", + "module m;\n ;;\nendmodule\n", + "package p;\n ;\nendpackage\n", + "class c;\n ;\nendclass\n", + "module m;\nendmodule;\n", + ]; + for src in sources { + let (file, diagnostics) = parse_source_tolerant(src); + assert!(diagnostics.is_empty(), "{src}=> {diagnostics:?}"); + assert!(!null_item_slices(src, &file).is_empty(), "{src}"); + assert!( + null_item_slices(src, &file).iter().all(|s| s == ";"), + "an error leaf, not a null item: {src}" + ); + } +} + +/// The `;` after `endfunction`/`endtask` stays where it always was — on +/// `FunctionDecl::end_semi` / `TaskDecl::end_semi`, consumed inside the +/// declaration — so the two mechanisms do not both claim it. +#[test] +fn endfunction_and_endtask_keep_their_own_semicolon_flag() { + let src = "module m;\n function int f();\n return 1;\n endfunction;\n task t();\n endtask;\nendmodule\n"; + let file = tree(src); + assert!(null_item_slices(src, &file).is_empty(), "the `;` must not become a null item"); + let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; + let mut seen = 0; + for item in &m.items { + match &item.kind { + ItemKind::Function(f) => { + assert!(f.end_semi); + seen += 1; + } + ItemKind::Task(t) => { + assert!(t.end_semi); + seen += 1; + } + _ => panic!("unexpected item"), + } + } + assert_eq!(seen, 2); +} diff --git a/crates/vlog_parser/tests/spans.rs b/crates/vlog_parser/tests/spans.rs index 87c924c..d35ee82 100644 --- a/crates/vlog_parser/tests/spans.rs +++ b/crates/vlog_parser/tests/spans.rs @@ -603,8 +603,10 @@ fn check_item(src: &str, item: &Item, parent: TextRange) { } } // A `constraint`/`covergroup` block: one verbatim leaf whose span is - // the item's own, checked above. - ItemKind::Verbatim(_) => {} + // the item's own, checked above. A null item is a leaf too — its span + // is the `;`, which the caller has already asserted sits inside its + // parent. + ItemKind::Verbatim(_) | ItemKind::Empty => {} ItemKind::Function(f) => { check_name(src, "function name", &f.name, f.name_span, here); check_dpi_import(src, f.dpi.as_ref(), here); diff --git a/crates/vlog_semantic/src/bind.rs b/crates/vlog_semantic/src/bind.rs index 37e991b..aafd53f 100644 --- a/crates/vlog_semantic/src/bind.rs +++ b/crates/vlog_semantic/src/bind.rs @@ -371,6 +371,8 @@ impl<'a> Binder<'a> { | ItemKind::MacroItem(_) | ItemKind::Timeunit(_) | ItemKind::Error(_) + // A null item (`;`) declares nothing and references nothing. + | ItemKind::Empty | ItemKind::Verbatim(_) => {} } } diff --git a/docs/features/null-items/README.md b/docs/features/null-items/README.md new file mode 100644 index 0000000..6588121 --- /dev/null +++ b/docs/features/null-items/README.md @@ -0,0 +1,452 @@ +# null-items + +## Goal + +Accept the **null item** — a lone `;` written where a module, generate, +package, interface, program or class item belongs, and at file scope. It is +legal SystemVerilog (IEEE 1800-2017 A.1.4: +`package_or_generate_item_declaration ::= … | ;`, `class_item ::= … | ;`, and +`description → package_item` reaches it at file scope), it means nothing, and +people write it all the time — after `endgenerate`, after a generate block's +`end`, after `endmodule`. lucisv rejected every one of those with +`parse error: expected item (found ";")`, which is what the owner hit when +they wrote `endgenerate;` after a perfectly good generate-`for` loop. (The +generate-`for` itself was never the problem: every spelling of it already +parsed and round-tripped, and this feature pins three real-world examples to +keep it that way.) + +Three things ship together: `ItemKind::Empty` in the parser, a +token-preserving layout rule in the formatter (a `;` written on the same line +as the item before it stays on that line), and a default-on lint, +`empty-item`, whose safe fix deletes the `;` — the equivalent of slang's +`-Wempty-member` ("an unnecessary semicolon is located in a non-procedural +scope (such as a module body)"). The procedural sibling — the null +*statement*, `initial begin ; end` — already worked and is untouched, as is +`endfunction;`/`endtask;`, which the `end_semi` flag on `FunctionDecl` / +`TaskDecl` has recorded since the classes round (`parser.rs`, +`parse_function_decl`: "the stray `;` is a null class item"). That flag is the +precedent this work generalizes; it is deliberately left alone, so the two +mechanisms do not overlap. + +## Assumptions + +- **A `;` at item position is always a null item.** Nothing else in the item + grammar can start with `;`, so the one-token test in `parse_item_kind` is + unambiguous. Before this change the token was a hard error there, so no + previously-parsing source changes meaning. +- **`endfunction;` / `endtask;` keep going through `end_semi`.** The parser + consumes that `;` inside `parse_function_decl`/`parse_task_decl` before the + item loop ever sees it, so it never becomes an `ItemKind::Empty`. Two + spellings of the same source fact would be worse than one; the existing one + already prints back where it was written. +- **"Same line" is a question about the previous *sibling item*, not the + previous token.** See Handshakes for the argument; the consequence is that a + null item that is the *first* item of a body always prints on its own line + (`module m;` ⏎ ` ;` ⏎ `endmodule`, `generate` ⏎ ` ;` ⏎ `endgenerate`), + because there is no sibling to glue to. +- **A `//` comment can never stand between the previous item and a glued + `;`.** It would swallow the `;` to end of line, so the only comment that + fits in a newline-free gap is a single-line block comment, which prints + inline and keeps the `;` after it. This is what makes gluing safe: the + formatter can never append `;` after a line comment. +- **A null item declares nothing and references nothing**, so + `vlog_semantic`'s `bind.rs` treats it as a leaf, and `vlog_linter`'s + catch-all `visit.rs` walk needs no arm. +- **The 820-file corpus contains no null item**, so its output must stay + byte-identical. Any drift there is a bug in this feature, not a style + change. + +## Handshakes + +### Consumed + +- `vlog_parser::ast::Item`/`Meta` — the null item's comments ride the ordinary + `Meta` (leading, trailing), exactly like any other item; its `span` is the + `;` token alone. +- `vlog_formatter`'s `Fmt::src` and item spans — the same way `align.rs` and + `format.rs`'s `eq_offset` / `open_paren_offset` / `default_has_colon` + already ask the source a layout question the AST does not answer. +- `vlog_linter`'s `registry::Rule`, `visit::walk_items`, `Fix::safe` and the + `.lint` harness's `----` fix section. + +### Promised (exhaustive-match arms this variant costs) + +Per `docs/topo.md` §3.3, a new `ItemKind` variant costs an arm everywhere the +match is exhaustive. Added by this lane: + +| file | arm | +|---|---| +| `crates/vlog_parser/src/ast.rs` | the variant itself, `ItemKind::Empty` | +| `crates/vlog_parser/src/parser.rs` | `parse_item_kind`'s `;` branch | +| `crates/vlog_parser/tests/spans.rs` | `ItemKind::Empty => {}` (a leaf; the item's own span is checked by the caller) | +| `crates/vlog_formatter/src/format.rs` | `item_kind`'s `ItemKind::Empty => text(";")`, plus the `item_seq` glue rule | +| `crates/vlog_semantic/src/bind.rs` | folded into the leaf group `\| ItemKind::Verbatim(_) => {}` | + +Catch-all matches that needed nothing, confirmed by compiling: `vlog_linter`'s +`visit.rs` / `signals.rs`, `vlog_formatter`'s `fence.rs` / `range.rs` / +`verify.rs`, `vlog_refactor`'s `ports.rs` / `instantiate.rs`, `vlog_semantic`'s +`instantiations.rs` / `classes.rs`, and the server's `completion.rs`, +`type_def.rs`, `linked.rs`, `selection.rs`, `symbols.rs`, `tokens.rs`, +`on_type.rs`, `type_hierarchy.rs`. + +### The glued/own-line decision, and where "same line" is decided + +**Decided in the formatter, from `src` spans; no parser flag.** `item_seq` is +the one place that emits the separator between two sibling items, and the +question the glue asks is exactly the one it is already answering ("what goes +between item *n-1* and item *n*"). A parser-recorded flag would answer a +*different* question — "was there a newline since the previous **token**" — +which differs precisely where it matters least and hurts most: for the first +item of a body the previous token is the opener (`generate`, the header `;`, +`begin`), and gluing there would mean reaching back into a construct's +header layout from its body's item list. It would also put a formatter-only +layout fact into the AST that every other consumer must ignore. The source +check is one `contains('\n')` over the gap between the previous item's +`span.end` and the `;`'s `span.start`, which is the established idiom in this +file. + +The rule, then: + +- a null item whose `;` has **no newline** between it and the previous + sibling item prints **glued** to that item's last line: `endgenerate;`, + `end;`, `;;`, `endmodule;`; +- **otherwise** — a newline in the gap, no previous sibling, a leading + comment, an attribute, or a format-off fence opening on it — it prints `;` + on its own line at the current indent. + +Both are fixed points: re-parsing glued output finds no newline in the gap and +glues again; re-parsing own-line output finds one and does not. Both +directions are pinned in `tests/cases/null_items.cases`. + +Alignment: `param_decl_row` returns `None` for any non-`ParamDecl` item and +`align_groups` breaks a run at a `None` row, so a null item between two +`parameter` declarations splits the alignment group with no new code. Pinned +by a case. + +### Filed (nothing) + +No cross-module request; nothing is owed by another module. Every file this +lane touched: + +| file | change | +|---|---| +| `crates/vlog_parser/src/ast.rs` | `ItemKind::Empty` | +| `crates/vlog_parser/src/parser.rs` | the `;` branch in `parse_item_kind` | +| `crates/vlog_parser/tests/spans.rs` | the leaf arm | +| `crates/vlog_parser/tests/null_items.rs` | **new** — the per-scope parser tests the brief asked for | +| `crates/vlog_formatter/src/format.rs` | `item_kind` arm, `item_seq` glue, `glued_null_item` | +| `crates/vlog_formatter/tests/cases/null_items.cases` | **new** — 22 layout/idempotency cases | +| `crates/vlog_formatter/tests/verification.rs` | three masked-corruption pairs | +| `crates/vlog_semantic/src/bind.rs` | the leaf arm | +| `crates/vlog_linter/src/rules/empty_item.rs` | **new** — the rule | +| `crates/vlog_linter/src/rules/mod.rs` | `pub mod empty_item;` | +| `crates/vlog_linter/src/registry.rs` | one line in `all_rules()` | +| `crates/vlog_linter/tests/cases/empty_item.lint` | **new** — 20 lint/fix cases | +| `docs/features/null-items/README.md` | **new** — this document | +| `TODO.md` | §14 ticked | + +`vlog_formatter/src/align.rs` was **not** touched: the group split falls out +of `param_decl_row` returning `None`, so the rule the brief allowed for was +not needed. `verify.rs` was not touched either (invariant 4). Two files are +outside the brief's literal list and are recorded here rather than assumed: +`vlog_parser/tests/null_items.rs` (the brief asked for parser unit tests but +named no file) and `vlog_linter/src/rules/mod.rs` (a new rule module cannot +be registered without it). + +## Status / TODO + +- [x] `ItemKind::Empty` — a leaf variant, span = the `;`, comments through + `Meta`. +- [x] `parse_item_kind` accepts `;`; every item list reaches it (they all go + through `item_or_recover` → `parse_item`). +- [x] Tolerant mode emits no diagnostic for it (it is a successful parse, not + a recovery). +- [x] Formatter: glued / own-line layout, idempotent both ways. +- [x] Alignment groups are not joined across a null item. +- [x] Blast-radius arms (`format.rs`, `bind.rs`, `spans.rs`). +- [x] `verify.rs` untouched; three rejection pairs added to + `tests/verification.rs` anyway. +- [x] Lint `empty-item`, default on, safe fix, `.lint` case with fix output. +- [x] `tests/cases/null_items.cases` — the owner's shape, every reproduction, + slang's two examples, three systemverilog.io generate examples. +- [x] Parser unit tests per scope. +- [x] `TODO.md` §14 ticked. + +## Work log + +### 2026-09-01 — dev + +Reproduced the lead's list against the tree at `1e30ea0` first: `b.sv` +(`endgenerate;`), `e.sv` (lone `;` at module scope), `f1` (`generate ; +endgenerate`), `f2` (`end;` inside a region), `f3`/`f4`/`f5` +(package/interface/class), `f7` (`endmodule;`), `f9` (region-less `end;` and +`;;`) all failed with `expected item (found ";")`; `a`/`c`/`d` (three +generate-`for` spellings), `f8` (procedural null statement) and `f6` +(`endfunction;`/`endtask;`) already passed. Same verdicts the lead reported. + +**Parser.** `ItemKind::Empty` added to `ast.rs` as a unit variant directly +before `Error`, and one branch at the top of `parse_item_kind`: + +```rust +if self.cur().is_sym(";") { + self.bump(); + return Ok(ItemKind::Empty); +} +``` + +Every item list in the parser — file, module/interface/program body, package +body, class body, `generate` region, `parse_gen_block`'s begin/end body and +its single-item body — goes through `item_or_recover` → `parse_item` → +`parse_item_kind`, so one branch covers all eight scopes. Verified by test +rather than by reading, per the brief: `tests/null_items.rs` parses one case +per scope strictly and asserts an `Empty` item with `src[span] == ";"`. + +The branch sits *before* the `TokenKind` match, not inside it, because the +lexer's symbol tokens are matched by text (`is_sym`), not by a `TokenKind` +variant per symbol; that is how the rest of the file tests for punctuation. + +**Formatter.** `item_kind` gets `ItemKind::Empty => text(";")`. The layout +lives in `item_seq`, which now tracks the previous item that actually emitted +docs and suppresses the separator when `glued_null_item` says so. The +predicate refuses to glue when the null item has a leading comment, an +attribute, a blank line before it, or a fence opening on it — each of those +gives the `;` docs of its own that must not be appended to the previous +line — and finally asks the source whether the gap holds a newline. + +**Blast radius.** `cargo check --workspace` named exactly three other +exhaustive matches: `format.rs` (the arm above), `bind.rs` (folded into the +existing leaf group), `spans.rs` (`Empty => {}`). Nothing else in the eight +crates or the server needed a line, which the Handshakes table records. + +**Safety net.** `verify.rs` untouched, per CLAUDE.md invariant 4. Three +masked-corruption pairs added to `tests/verification.rs`: an output that drops +the `;`, one that moves it to the other side of a comment, and one that moves +an item-level `;` into an adjacent procedural block. All three are rejected by +the net as it stands, which is the point of writing them down. + +**Lint.** `empty-item`, default on, safe fix, listed between +`case-missing-default` and `enum-name-style` (the registry is asserted +alphabetical). The fix deletes the `;` plus the horizontal whitespace before +it, and takes the newline too when what stood on that line was nothing but +whitespace and other null items — so `;;;` on a line leaves no blank line +behind, while `endgenerate; // note` becomes `endgenerate // note` with the +comment untouched and `; // why` leaves the comment on its line. A final +guard refuses to emit a fix whose range covers anything but `;` and +whitespace: the range is built so that it cannot, and the check makes +"comments are never dropped" true by construction rather than by argument. +Both shapes are in `tests/cases/empty_item.lint`, whose harness re-lints to a +fixpoint and re-formats the fixed text. + +**Cases.** `tests/cases/null_items.cases`: 22 cases — the owner's shape, each +reproduction from the lead's list, slang's `-Wempty-member` / `-Wempty-stmt` +examples, the glued/own-line idempotency pair in both directions, the +comment shapes, the alignment-group split, and the three systemverilog.io +generate examples verbatim (16-input mux, `assert property` inside a +generate-`for`, the memory `case` with a nested `for` and hierarchical +instantiations) so a regression in generate-`for` is caught here too. The +harness re-formats every expected output, so each case is an idempotency +assertion as well as a layout one. + +Parser coverage lives in `crates/vlog_parser/tests/null_items.rs`: one source +per scope, asserting `src[span] == ";"`; the `;;;` split; the comment +attachment; tolerant mode's silence; and that `endfunction;`/`endtask;` still +produce no null item. + +**Gates.** `cargo fmt --all -- --check` clean; `cargo clippy --all-targets +--workspace` zero warnings; `cargo test --workspace` 2709 passed / 0 failed +(1 formatter case-table run covering 22 new cases, 1 lint case-table run +covering 21 new ones, 6 new parser tests, 3 new verification tests); +`scripts/corpus_gate.sh corpus` → `{"passing":813,"total":820,"pct":99.1}`, +exit 0, zero verification errors and zero crashes — the baseline unchanged. +Byte-identity was measured directly rather than inferred: a worktree at +`1e30ea0` was built and both binaries were run over all 820 corpus files — +**813 identical, 0 differing, 7 refused by both** (release and debug builds +agree). `cargo build -p lucisv_server` + `node editors/vscode/smoke.js +target/debug/lucisv-server` → OK, 20 messages. + +Hand checks beyond the suites, each re-formatted to confirm a fixed point: a +null item after a `` `define`` and inside both arms of an `` `ifdef``; `` `endif; ``; +a CRLF file; an attributed `(* keep *) ;`; and `--lines` range runs that touch +the null item, the item before it and neither. + +## QA log + +### 2026-09-01 — QA + +**Verdict: SHIP.** + +**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets +--workspace` zero warnings. `cargo test --workspace`: 2709 passed / 0 failed +before my addition, matching the dev's number exactly (summed every `test +result:` line by hand); 2710 / 0 after adding one more verification test +(below). `scripts/corpus_gate.sh corpus` → +`{"passing":813,"total":820,"pct":99.1,...}` with all four failure categories +at their pre-existing counts, 0 verification errors, 0 crashes. `cargo build +-p lucisv_server` + `node editors/vscode/smoke.js target/debug/lucisv-server` +→ OK, 20 messages. + +**Scope.** `git status --porcelain` / `git diff --stat` match the README's +file list exactly, with one addition the dev's list did not carry: +`docs/topo.md` (a `null-items` row added to §2.1 and §2.4, plus the doc-count +line and the `vlog_parser` feature-list row bumped) — reasonable and +consistent with how every other single-lane feature in this repo's history +self-registers in topo.md; not flagged as scope creep. `verify.rs` confirmed +absent from the diff (`git diff --name-only | grep verify.rs` → nothing). +No `unwrap()`/`expect()`/`panic!` introduced in library code — the two +`format.rs` matches (declarators, guarded by `items.len() == 1`) and every +`parser.rs`/`registry.rs` match are pre-existing and sit inside `#[cfg(test)]` +modules, confirmed by diff (this feature's parser.rs diff is exactly the +6-line `;`-branch add; nothing near those test lines). + +**Doc finding (fixed directly, low severity).** The Filed table +(README:144, and the identical claim in `TODO.md`'s round-up) said +`empty_item.lint` holds "21 lint/fix cases"; counting `====`-delimited blocks +and `# ` case-name headers gives **20** (7 carry a `----` fix section, not +8). Miscount only — the harness (`lint_case_tables`) counts the same file the +same way and every case passes; nothing about the shipped behavior changes. +Fixed the README's line to 20; left `TODO.md`'s narrative prose alone since +it does not state a count. `null_items.cases`' claimed 22 is exact (`grep -c +'^# '` → 22). + +**Parser + formatter attack (scratch `cargo run --example`, reverted after — +nothing here needed pinning beyond what the dev already has).** Every scope +in the checklist: first/last item of a module body, between two `assign`s in +an alignment group (splits correctly, columns differ across the split — +confirmed against the case at README-adjacent `null_items.cases:186`), +immediately after `(* attr *)`, both arms of `` `ifdef ``/`` `else ``/`` +`endif ``, a `;` directly after `` `endif ``, after the `generate` keyword, +after `endgenerate`, `end;` after generate-`for`/generate-`if`/named +(`end : g;`) blocks, `;;;`, class/package/interface(with modport)/program +bodies, file scope between `endmodule` and `module`. All parsed, formatted, +and idempotent (`format(format(x)) == format(x)` checked directly, not just +via the case harness). Comment shapes — trailing line comment glued +(`endgenerate; // note`), trailing block comment glued, a block comment +alone on the null item's line, a line comment separating `endgenerate` from +a next-line `;` (stays own-line, correctly not glued across it), a leading +comment with a blank line above (blank preserved) — all round-tripped +correctly. CRLF file with `endgenerate;\r\n` formats and converges (CRLF→LF +is pre-existing general formatter behavior, not particular to this feature). + +**One interaction checked and found pre-existing, not a regression.** A +`;` on its own line immediately after `endfunction` (e.g. inside a class, +between two methods) never becomes an `ItemKind::Empty`: `parse_function_decl`'s +`end_semi = self.eat_sym(";")` (parser.rs, untouched by this diff) is +whitespace/newline-blind — it eats the very next token regardless of an +intervening newline — so that `;` is absorbed into `FunctionDecl::end_semi` +and reprinted glued onto `endfunction`'s line, changing layout (not content) +on the first pass. Verified byte-for-byte identical on a worktree built from +`1e30ea0` (pre-feature) with the same input: this is standing `end_semi` +behavior this feature explicitly declines to touch (Assumptions), not +something introduced here. No action taken. + +**Safety net (verify.rs).** Read all three new tests (7 pairs): dropped `;` +in two directions plus an invented one, a null item moved across a one-line +block comment (both directions: comment-then-semicolon vs +semicolon-then-comment, and a leading full-line comment swapped past the +`;`), and a null item's `;` swapped between an item slot and a procedural +statement slot. Ran `cargo test -p vlog_formatter --test verification +null_item` — all 3 tests / 7 pairs pass (i.e. `verify_equivalence` correctly +returns `Err` for every one). Read `verify.rs` in full: it is a strict +positional token-stream comparison (whitespace-blind, with only multi-line +directive/attribute/comment text trimmed per-line and the `@(*)` +canonicalization) — nothing in it forgives a token reorder, so every pair +above was expected to be rejected by construction, not by luck. + +Added the checklist's suggested gap test — a null item carried from one +`` `ifdef `` arm to the other — as +`a_null_item_moved_from_one_ifdef_arm_to_the_other_is_rejected` in +`crates/vlog_formatter/tests/verification.rs` (kept; it is a real +regression pin, distinct from the existing pairs since the item list is +flat across `Directive` items and a directive-adjacent reorder was the one +shape not yet attacked). Confirmed rejected; noted in the test's own comment +that this was expected to hold given `verify.rs`'s positional design, so +this is a pinned confirmation, not a bug find. + +**LSP smoke (checklist item 3, tolerant mode + diagnostics + code action).** +`crates/vlog_parser/tests/null_items.rs::tolerant_parsing_reports_no_diagnostic` +covers the parser side. For the editor-visible side, drove +`target/debug/lucisv-server` headlessly over stdio (hand-rolled framing +copied from `editors/vscode/smoke.js`'s pattern, run from the scratchpad, not +added to the tree): opened a buffer containing `endgenerate;`, requested +`textDocument/codeAction` over the `;`. Result: `publishDiagnostics` carries +no parse-error (severity-1) diagnostic, only an `empty-item` warning +(severity 2, code `empty-item`, message "unnecessary `;`; a null item does +nothing"); the code action response offers both the single-finding quick fix +(`lucisv: drop a `;` that stands where an item belongs [empty-item]`, +`isPreferred: true`) and `source.fixAll.lucisv`, both producing the correct +edit. Exactly the "warning, not a parse error, with a working fix" contract +the checklist asks for. + +**Opentitan sweep (read-only throughout).** `git -C +/Users/guoliangchen/repo/opentitan status --porcelain` before and after: +unchanged, exactly the three expected pre-existing owner-modified files +(`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`, +`hw/top_earlgrey/ip/ast/rtl/ast.sv`). Swept all 3,943 real `.sv`/`.svh` files +(32 symlinks excluded, same file count the clocking-wave baseline used) with +this feature's release `lucisv --no-cache --check`: **12** files exit +outside {0,1}, not 11 — but the 12th is +`hw/top_darjeeling/ip/ast/rtl/ast.sv`, one of the three files with a local +uncommitted owner edit (`parse error: 749:1: expected declaration or +instantiation (found "as")`, clearly mid-edit). Built a second release +binary from a `git stash` of this feature's diff (i.e. trunk `1e30ea0`) and +swept the identical file list: **same 12 files, byte-identical set** (`diff` +of the two sorted failing-file lists is empty). So the standing 11-failure +grammar baseline is unchanged, and the 12th is the owner's own local WIP on +a file already flagged as "leave alone" — not a lucisv regression in either +direction, and not something this feature's parser change touches (it is a +`typedef`/enum-ish token error, nothing to do with a null item). Restored +this feature's worktree state (`git stash pop`) and rebuilt before +continuing; `git status --porcelain` on the lucisv tree also confirmed clean +of scratch artifacts (temporary `cargo run --example` files removed after +use). Lint sweep: `lucisv check --no-cache` over all 3,943 files, `grep -c +empty-item` → **0** — opentitan has no null items, matching the feature's +own stated assumption. + +**Overall:** every gate green, scope matches modulo the topo.md +self-registration (normal), one doc miscount fixed, one interaction traced +to pre-existing `end_semi` behavior and confirmed not a regression, the +safety net's 7 pairs plus 1 QA-added pair all correctly rejected, the LSP +contract (warning + working fix, no false parse error) verified live, and +the opentitan sweep confirmed byte-identical to trunk. No blocking findings. + +## Review + +*(reserved for the lead)* + +**2026-09-01 — lead.** Approved and committed. + +- The owner's report was "for loop inside generate"; the lead's diagnosis + before dispatch was that every generate-for spelling — and the three + systemverilog.io examples — already parsed, and that the failing token was + the null item after `endgenerate`. The dev built exactly that, and the + case file pins both halves: the online examples (so a generate-for + regression is caught here too) and every null-item scope. +- Read the load-bearing code in full. The parser branch is one line at the + top of `parse_item_kind`. `glued_null_item` refuses any `;` that carries + docs of its own (leading comment, attribute, blank line, fence), so the + glue only ever appends a bare `;` — and deciding it from `src` spans in + `item_seq` rather than a parser flag is the right call: it is a layout + fact about the gap between siblings, asked where that gap is laid out, + the same idiom `eq_offset` and `default_has_colon` use. The lint's + `deletion` range ends in a guard that admits only `;`/whitespace bytes, + which makes swallowing a same-line comment structurally impossible + (invariant 3), and `;;` yields two adjacent non-overlapping fixes. +- Exhaustive-arm cost was exactly the three §3.3 predicts (`format.rs`, + `bind.rs`, `tests/spans.rs`); every other walker is catch-all. `verify.rs` + untouched, seven attack pairs from the dev plus QA's eighth (a `;` moved + between `` `ifdef `` arms), all rejected. +- Corpus byte-identical at 813/820, measured by the dev against a + pre-change worktree and re-run by QA. Opentitan sweep identical to trunk + file-for-file (the twelfth "failure" is the owner's in-progress `ast.sv` + edit, present before the round); `empty-item` fires zero times there, + confirming the tree has no null items and nothing moved. +- QA's informational note stands as designed: an own-line `;` right after + `endfunction`/`endtask` is still absorbed by the older `end_semi` + mechanism rather than becoming `ItemKind::Empty`; behavior is unchanged + from trunk and the lint deliberately does not report it. Worth a future + tidy (fold `end_semi` into the null item) but not this round's. +- Gates re-run by the lead before commit: fmt clean, clippy zero warnings, + full suite green (2 710), corpus gate 813/820, smoke OK. `docs/topo.md` + gains a grammar-lane row and a linter-lane row. Ships as 0.21.0 — + formatter output changes for files that contain a null item, so the + version bump is owed by the format-cache rule as well. diff --git a/docs/topo.md b/docs/topo.md index 1d10311..cfa2b65 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -18,7 +18,8 @@ scope widening, the request-fan-out performance wave and verbose-timing inline-instantiation, the two-level module-instantiation split (106 feature READMEs — the testbench wave's five arrived in between, their edges already tabled below; +§2.9-19); updated 2026-08-30 again -for fuzzy-completion (107 feature READMEs). +for fuzzy-completion (107 feature READMEs); updated 2026-09-01 for +null-items (108 feature READMEs). **Edge notation, used in all three sections:** @@ -357,6 +358,7 @@ recursion-limit, whose edges sit in §2.1). Code edges: | `out-of-class-constraints ──▶ classes` | depends | Reuses the verbatim constraint capture and `parse_method_name` unchanged; one line in `parse_constraint`, no new AST variant, so none of the exhaustive-arm blast radius applies (2026-08-29 testbench wave, Lane A). | | `directive-in-statements ──▶ directive-split / directives-in-lists / assertions` | depends | The mirror-image recovery: a directive OPENING inside a statement/expression, captured verbatim through `construct_end` (Semi / endfunction+label / Unknown → refuse) and `terminated_in_arm`; `take_list_directives` additionally stops harvesting an outer region's `` `else `` as a list element. No new AST variant (2026-08-29 testbench wave, serial round). | | `directive-in-statements ◀──▶ formatter-bug-fixes` | handshake | formatter-bug-fixes round 2 filed the `take_before_open` pending-comment drain; directive-in-statements delivered it as `Parser::take_gap` (comments kept only when `span.start >= last_end()`, `CallComments::dangling` included — the specified fix alone was insufficient). The refusal pin flipped to a formats case on the merged tree, closing the last bucket-2 file (`keymgr_scoreboard.sv`). | +| `null-items ──▶ corpus-check / safety-net` | depends | `ItemKind::Empty` (2026-09-01): a lone `;` where an item belongs — IEEE 1800-2017 A.1.4's null item — accepted in every item scope by one branch at the top of `parse_item_kind`. The variant's exhaustive-arm cost was paid in exactly the three places §3.3 predicts (`format.rs`, `bind.rs`, `tests/spans.rs`); every other walker is catch-all and a leaf needs nothing. Formatter layout is decided from `src` spans in `item_seq` (glued to the previous sibling's line when no newline separates them and the `;` carries no docs of its own; else its own line), so the AST carries no layout flag. `verify.rs` untouched, seven attack pairs added; corpus byte-identical at 813/820, measured against the pre-change binary. Ships with the `empty-item` lint (slang's `-Wempty-member`) and its safe fix — see §2.4. | | `formatter-bug-fixes (round 2) ──▶ safety-net` | depends | Three comment-shape bugs fixed in `format.rs` (`then_is_block` trailing-line-comment cuddle guard, `Fmt::header_parens`, `default_has_colon`); `verify.rs` untouched, four masked-corruption rejection pairs added per the standing template, plus three more for the directive capture at merge (2026-08-29 testbench wave, Lane B + lead). | | `lexer-cleanup ──▶ error-recovery / lint-rules-2` (QA logs) | depends | Fixes three lexer gaps: `@(* )` (TODO §1) plus the BOM and non-ASCII-honesty findings those two QA rounds filed; adds `ParsedSource::lex_error()` so `lucisv check` stops silently passing unlexable files. | | `error-recovery ─▶ lucisv-server / linter-core` | depends (downstream) | `parse_source_tolerant` is the entry point the whole LSP and the linter stand on; the strict/tolerant split (shared grammar, no second parser) is the contract. | @@ -400,6 +402,7 @@ promise: | `semantic-lints ──▶ vlog-semantic` | depends | The three symbol-table rules; new (justified) crate dep `vlog_linter → vlog_semantic`; lazy analysis; the lead's pre-authorization to modify `vlog_semantic` went **unused** (recorded so it is not read as taken). | | `semantic-lints ──▶ one-parse` | depends | Reaches the server and CLI through the existing one-parse path (`LintContext::semantics()` / `with_semantics`). | | `server-lint ──▶ linter-core` | depends | Protocol wiring only; relies on the three written promises (stable names, no panics/writes, sorted findings). | +| `null-items ──▶ linter-core / shared-fence-filter` | depends | The `empty-item` rule (2026-09-01) walks `ItemKind::Empty` through `visit::walk_items`; its safe fix deletes the `;`, the horizontal whitespace before it, and the line only when nothing but whitespace and other null items stood on it — a final guard refuses any range holding a byte other than `;`/whitespace, so a same-line comment structurally cannot be swallowed (invariant 3). Rule name is stable API from this release on. | | `server-lint ◀──▶ shared-fence-filter, one-parse` | handshake | Both of server-lint's filed requests were delivered by those rounds (fence-safe quick fixes; lint-from-Document). | ### 2.5 Semantics & index lane @@ -552,7 +555,7 @@ untouched, reusing existing arms. | module | features whose home it is | |---|---| -| `vlog_parser` | spans, name-spans, recursion-limit, error-recovery, define-table, lexer-cleanup, and the grammar lane: *macro-items*, *classes*, *bind*, *dynamic-types*, *types-decls*, *item-misc*, *directives-in-lists*, *directives-in-instances*, *dpi-export*, *assertions*, *interfaces*, *expressions-2*, *dv-statements*, *mop-up-2*, *directive-split*, *ansi-first-port* (most also add formatter arms — parser+formatter pairs by default; directive-split and ansi-first-port reused existing arms and left `vlog_formatter/src` untouched) | +| `vlog_parser` | spans, name-spans, recursion-limit, error-recovery, define-table, lexer-cleanup, and the grammar lane: *macro-items*, *classes*, *bind*, *dynamic-types*, *types-decls*, *item-misc*, *directives-in-lists*, *directives-in-instances*, *dpi-export*, *assertions*, *interfaces*, *expressions-2*, *dv-statements*, *mop-up-2*, *directive-split*, *ansi-first-port*, *null-items* (most also add formatter arms — parser+formatter pairs by default; directive-split and ansi-first-port reused existing arms and left `vlog_formatter/src` untouched) | | `vlog_formatter` | safety-net (`verify.rs`), case-tables, formatter-bug-fixes, corpus-bugs, comments-round, comments-round-2, alignment (`align.rs`), format-fences (`fence.rs`), range-formatting (`range.rs`), shared-fence-filter | | `vlog_semantic` | vlog-semantic (`bind`/`resolve`/`model`), workspace-index (`workspace.rs`), class-semantics, overlay-promotion, port-detail-spans (`Symbol`/`Def::detail_span` and `Semantics::symbols_named`), hover-line-index (`DeclLines`, facts codec + `FACTS_FORMAT` 4), scan-interleave (`WorkspaceIndex::absorb`), refactor-rename's performance amendment (`files_spelling`), plus the index halves of indexing-ux (`index_order`/`IndexBuilder`), index-scope (order-insensitive `finish`, facts-from-analysis), incremental-index (`update_file`, edge/reference tables, `instantiations.rs`, `classes.rs`), index-persistence (`facts.rs`; plus a small `vlog_parser::defines` touch — `DefineTable::from_entries`, `Eq` derives) | | `vlog_linter` | linter-core, lint-harness, lint-rules-2, semantic-lints (`signals.rs`), one-parse (`context.rs`) |