diff --git a/README.md b/README.md index f4c9fc0..223825f 100644 --- a/README.md +++ b/README.md @@ -360,7 +360,18 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset: blocks, `begin`/`end` and `fork`/`join`, case-item and `if`/`else` bodies, function and task bodies. The invocation is passed through verbatim (a multi-line argument list keeps its own line structure, re-indented); a - trailing `;` is reproduced only if the source wrote one + trailing `;` is reproduced only if the source wrote one. At item and + statement position a space before the argument list is accepted too + (`` `uvm_field_int (a, UVM_DEFAULT) ``) and is reproduced as written; in + *expression* position `` `A (b) `` still parses as a call applied to `(b)`. + A macro that ends its line is a complete macro, so the declaration on the + next line is its own item. See `docs/features/item-misc/README.md` +- Elaboration system tasks where a module or generate item belongs: + `$fatal`, `$error`, `$warning`, `$info` — at module scope and inside + generate `if`/`for`/`case` and `begin`/`end`, including a generate-`if` + whose whole body is one of them. The argument list is a breakable group, + like any other call. `` `error``/`` `warning`` compiler directives are + passed through verbatim, like `` `define`` - `` `ifdef``/`` `ifndef``/`` `else``/`` `elsif``/`` `endif``, `` `define``, `` `undef``, `` `include`` and macro invocations written **between the elements** of a module header's port list, its parameter port list, an enum @@ -400,6 +411,13 @@ corpus baseline this ordering comes from: (`interface` at 25 files is now the top one — item 8 below) 5. Declarations with identifier (typedef'd) types in some positions (`my_t [N-1:0] x;`) +5b. ~~Macro invocation with a space before its argument list + (`` `uvm_field_int (a, b) ``), a bare macro item followed by a declaration + on the next line, `` `error``/`` `warning`` directives, and elaboration + system tasks (`$error(...)`) at item position~~ — **done**; see + `docs/features/item-misc/README.md`. Unblocked 25 corpus files and moved + the parse rate from 77.6% to 80.6%; the 2 remaining files of those two + buckets advanced to blockers in other categories 6. ~~`` `ifdef``/`` `define``/`` `include`` inside a port, parameter or enum list~~ — **done**; see `docs/features/directives-in-lists/README.md`. Two corpus files unblocked and six advanced to their next blocker diff --git a/TODO.md b/TODO.md index a16a8a0..d2cb15c 100644 --- a/TODO.md +++ b/TODO.md @@ -323,6 +323,15 @@ Adapt each: README roadmap item 8), then `` `else`` inside an element (13, the documented directives-in-lists non-goal) and `` `uvm_field_int `` (11, the documented macro-items lexer gap). + → item-misc (`docs/features/item-misc/README.md`) then took it from + 636/820 to **661/820 (80.6%)** — 25 files gained, 0 lost, passing set + verified as a strict superset. The `` `uvm_field_int `` gap is closed + (in the parser, at item position only — the lexer glue stays parked for + the reason `docs/features/lexer-cleanup/README.md` gives), along with a + bare macro item followed by a declaration on the next line, + `` `error``/`` `warning`` directives and elaboration system tasks + (`$error`/`$fatal`/`$warning`/`$info`) at item position. `interface` + (31 files) and `bind` (28) are now the top two blockers. - [ ] **[R] Fuzzing.** ruff fuzzes its parser. `cargo-fuzz` targets: (a) parser must never panic on arbitrary bytes, (b) for inputs that parse, format must satisfy equivalence + convergence. diff --git a/crates/vlog_formatter/src/format.rs b/crates/vlog_formatter/src/format.rs index d0b07d0..7c09171 100644 --- a/crates/vlog_formatter/src/format.rs +++ b/crates/vlog_formatter/src/format.rs @@ -976,6 +976,9 @@ impl<'a> Fmt<'a> { // parses strictly, so this arm exists to keep the match total. ItemKind::Error(d) => self.raw_text(d), ItemKind::MacroItem(m) => self.macro_call(m), + // Printed exactly like the statement it looks like; the call's own + // argument group supplies the line breaks. + ItemKind::ElabTask(e) => concat(vec![self.expr(e), text(";")]), ItemKind::Import(paths) => text(format!("import {};", join_paths(paths))), ItemKind::Timeunit(t) => text(format!("{t};")), ItemKind::Typedef(t) => self.typedef(t), diff --git a/crates/vlog_formatter/tests/cases/item_misc.cases b/crates/vlog_formatter/tests/cases/item_misc.cases new file mode 100644 index 0000000..2581929 --- /dev/null +++ b/crates/vlog_formatter/tests/cases/item_misc.cases @@ -0,0 +1,152 @@ +# `error at item position is a compiler directive, passed through verbatim +`ifdef PICOSOC_V +`error "icebreaker.v must be read before picosoc.v!" +`endif +module m; +endmodule +---- +`ifdef PICOSOC_V +`error "icebreaker.v must be read before picosoc.v!" +`endif +module m; +endmodule +==== +# `warning is the same directive, and is re-indented like `ifdef is +module m; +`ifndef SYNTHESIS +`warning "simulation-only build" +`endif +endmodule +---- +module m; + `ifndef SYNTHESIS + `warning "simulation-only build" + `endif +endmodule +==== +# a generate-if whose whole body is an elaboration task, no begin/end +module popcount #(parameter int unsigned INPUT_WIDTH = 8) (); +if (INPUT_WIDTH < 1) +$error("INPUT_WIDTH must be larger or equal to 1."); +endmodule +---- +module popcount #(parameter int unsigned INPUT_WIDTH = 8) (); + if (INPUT_WIDTH < 1) $error("INPUT_WIDTH must be larger or equal to 1."); +endmodule +==== +# $error inside a labelled generate block, arguments broken onto their own lines +module m #(parameter int SYNC_STAGES = 2) (); +if (SYNC_STAGES < 3) begin : gen_elaboration_assertion +$error("The clearable 2-phase CDC with async reset", +"synchronization requires at least 3 synchronizer stages for the FIFO."); +end +endmodule +---- +module m #(parameter int SYNC_STAGES = 2) (); + if (SYNC_STAGES < 3) begin : gen_elaboration_assertion + $error( + "The clearable 2-phase CDC with async reset", + "synchronization requires at least 3 synchronizer stages for the FIFO." + ); + end +endmodule +==== +# $fatal at module scope, guarded by an `ifndef +module m; +`ifndef RVFI +$fatal("Fatal error: RVFI needs to be defined globally."); +`endif +logic v; +endmodule +---- +module m; + `ifndef RVFI + $fatal("Fatal error: RVFI needs to be defined globally."); + `endif + logic v; +endmodule +==== +# $warning whose argument list opens on the next line joins back onto one +module m; +if (SHOW_WARNING) begin : gen_elab_warning +$warning( +"This clock divider is deprecated ", +"use clk_int_div instead. "); +end +endmodule +---- +module m; + if (SHOW_WARNING) begin : gen_elab_warning + $warning("This clock divider is deprecated ", "use clk_int_div instead. "); + end +endmodule +==== +# elaboration tasks inside generate case items +module m; +case (ARBITER) +"rr": begin : gen_rr +$info("round robin"); +end +default: begin : gen_arb_error +$fatal(1, "Invalid value for parameter 'ARBITER'!"); +end +endcase +endmodule +---- +module m; + case (ARBITER) + "rr": begin : gen_rr + $info("round robin"); + end + default: begin : gen_arb_error + $fatal(1, "Invalid value for parameter 'ARBITER'!"); + end + endcase +endmodule +==== +# comments around an elaboration task item are kept on both sides +module m; +// why this is illegal +$error("nope"); // and a trailing note +endmodule +---- +module m; + // why this is illegal + $error("nope"); // and a trailing note +endmodule +==== +# an elaboration task inside a format fence comes out byte-exact +module m; +// verilog_format: off + $error( "spaced" , "out" ); +// verilog_format: on +wire a; +endmodule +---- +module m; +// verilog_format: off + $error( "spaced" , "out" ); +// verilog_format: on + wire a; +endmodule +==== +# an elaboration task that lands exactly on the 100-column limit stays on one line +module m; +$error("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); +endmodule +---- +module m; + $error("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); +endmodule +==== +# one column over the limit and the argument list breaks +module m; +$error("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); +endmodule +---- +module m; + $error( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ); +endmodule diff --git a/crates/vlog_formatter/tests/cases/macros.cases b/crates/vlog_formatter/tests/cases/macros.cases index 0962959..0014f84 100644 --- a/crates/vlog_formatter/tests/cases/macros.cases +++ b/crates/vlog_formatter/tests/cases/macros.cases @@ -263,3 +263,105 @@ module m; line two" end endmodule +==== +# a space before the argument list is an invocation, not a broken declaration +class ibex_ifetch_pmp_seq_item extends uvm_sequence_item; + bit [31:0] fetch_addr; + `uvm_object_utils_begin(ibex_ifetch_pmp_seq_item) + `uvm_field_int (fetch_addr, UVM_DEFAULT) + `uvm_object_utils_end +endclass +---- +class ibex_ifetch_pmp_seq_item extends uvm_sequence_item; + bit [31:0] fetch_addr; + `uvm_object_utils_begin(ibex_ifetch_pmp_seq_item) + `uvm_field_int (fetch_addr, UVM_DEFAULT) + `uvm_object_utils_end +endclass +==== +# a spaced macro call is a statement too, semicolon and all +module m; +initial begin +`uvm_info ("id", "msg", UVM_LOW); +end +endmodule +---- +module m; + initial begin + `uvm_info ("id", "msg", UVM_LOW); + end +endmodule +==== +# a spaced macro call is reproduced verbatim: the space and the inner spacing stay +module m; +`ASSERT_INIT ( CheckN_A , N > 0 ) +endmodule +---- +module m; + `ASSERT_INIT ( CheckN_A , N > 0 ) +endmodule +==== +# a multi-line spaced macro call is re-indented, not reflowed +module m; +`ASSERT_NEVER (NoOverflow_A, + a && b, + clk_i, rst_ni) +endmodule +---- +module m; + `ASSERT_NEVER (NoOverflow_A, + a && b, + clk_i, rst_ni) +endmodule +==== +# a bare macro that ends its line is complete: the next line declares on its own +class c extends b; +`uvm_component_new + +uvm_report_server rs; +endclass +---- +class c extends b; + `uvm_component_new + + uvm_report_server rs; +endclass +==== +# a comment between a bare macro item and the declaration under it changes nothing +class c extends b; +`uvm_object_new + +// Non-null if this is a later item. +ibex_icache_core_base_seq prev_sequence = null; +endclass +---- +class c extends b; + `uvm_object_new + + // Non-null if this is a later item. + ibex_icache_core_base_seq prev_sequence = null; +endclass +==== +# a macro-named type still declares when name and declarator share a line +module m; +`MY_TYPE_T sig; +endmodule +---- +module m; + `MY_TYPE_T sig; +endmodule +==== +# a spaced macro call inside a format fence comes out byte-exact +module m; +// verilog_format: off + `uvm_field_int (fetch_addr,UVM_DEFAULT) +// verilog_format: on +wire a; +endmodule +---- +module m; +// verilog_format: off + `uvm_field_int (fetch_addr,UVM_DEFAULT) +// verilog_format: on + wire a; +endmodule diff --git a/crates/vlog_formatter/tests/verification.rs b/crates/vlog_formatter/tests/verification.rs index 3204718..d27fe73 100644 --- a/crates/vlog_formatter/tests/verification.rs +++ b/crates/vlog_formatter/tests/verification.rs @@ -102,6 +102,39 @@ fn a_changed_macro_argument_is_still_rejected() { } } +/// Why `` `uvm_field_int (a, b) `` keeps its space instead of being tightened +/// to the canonical `` `uvm_field_int(a, b) ``: the two spellings are *one* +/// token each, of different text, so closing the gap is a token rewrite the +/// safety net refuses. Nothing in `verify.rs` forgives it, and this test is +/// here so nothing starts to. +#[test] +fn tightening_a_spaced_macro_call_is_rejected() { + let input = "module m;\n `A (x, y)\nendmodule\n"; + let output = "module m;\n `A(x, y)\nendmodule\n"; + match expect_divergence(input, output) { + VerificationError::Divergence { expected, got, .. } => { + assert_eq!(expected.expect("expected item").text, "`A"); + assert_eq!(got.expect("got item").text, "`A(x, y)"); + } + other => panic!("wrong error: {other}"), + } +} + +/// The mirror image: re-spacing a *glued* invocation is rejected too, so the +/// formatter cannot drift between the two spellings in either direction. +#[test] +fn loosening_a_glued_macro_call_is_rejected() { + let input = "module m;\n `A(x, y)\nendmodule\n"; + let output = "module m;\n `A (x, y)\nendmodule\n"; + match expect_divergence(input, output) { + VerificationError::Divergence { expected, got, .. } => { + assert_eq!(expected.expect("expected item").text, "`A(x, y)"); + assert_eq!(got.expect("got item").text, "`A"); + } + other => panic!("wrong error: {other}"), + } +} + #[test] fn differing_token_is_rejected() { let err = expect_divergence("assign x = a;\n", "assign x = b;\n"); diff --git a/crates/vlog_parser/src/ast.rs b/crates/vlog_parser/src/ast.rs index 20decb6..9ec25ce 100644 --- a/crates/vlog_parser/src/ast.rs +++ b/crates/vlog_parser/src/ast.rs @@ -157,6 +157,11 @@ pub enum ItemKind { Directive(RawText), /// Macro invocation used as a module item. MacroItem(MacroCall), + /// An elaboration system task standing where a module or generate item + /// belongs: `$error("...");`, `$fatal(1, "...");` (IEEE 1800 §20.11). + /// The payload is the ordinary system-task-call expression — only the + /// position is special. + ElabTask(Expr), Import(Vec), Timeunit(String), Typedef(Typedef), diff --git a/crates/vlog_parser/src/lexer.rs b/crates/vlog_parser/src/lexer.rs index 69e77b6..11c53eb 100644 --- a/crates/vlog_parser/src/lexer.rs +++ b/crates/vlog_parser/src/lexer.rs @@ -677,10 +677,20 @@ fn is_base_intro(c: u8) -> bool { /// Directives that consume the rest of the source line. Anything else that /// starts with a backtick is treated as a macro usage token. +/// +/// The list is closed on purpose: every backtick name *not* named here is a +/// macro invocation, so adding a name here takes it away from the macro +/// population for good. `` `error`` / `` `warning`` are in because IEEE 1800 +/// §22.8 spells them as directives whose operand is a bare string on the rest +/// of the line (`` `error "must be read first!" ``, corpus +/// `picorv32/picosoc/icebreaker.v:21`), which nothing else in the grammar can +/// parse. fn is_line_directive(word: &str) -> bool { matches!( word, "define" + | "error" + | "warning" | "undef" | "undefineall" | "ifdef" @@ -882,6 +892,23 @@ mod tests { assert!(err.message.contains("macro argument nesting too deep"), "unexpected: {err}"); } + #[test] + fn error_and_warning_are_line_directives() { + let toks = kinds("`error \"a b (c)\"\nwire w;"); + assert_eq!(toks[0], (TokenKind::Directive, "`error \"a b (c)\"".to_string())); + assert_eq!(toks[1], (TokenKind::Keyword, "wire".to_string())); + let toks = kinds("`warning \"deprecated\"\nwire w;"); + assert_eq!(toks[0], (TokenKind::Directive, "`warning \"deprecated\"".to_string())); + } + + #[test] + fn the_directive_list_stays_closed_around_error() { + // Only the exact names are directives: a macro whose name merely + // starts with one is still a macro usage token. + let toks = kinds("`error_if(x) wire w;"); + assert_eq!(toks[0], (TokenKind::Ident, "`error_if(x)".to_string())); + } + #[test] fn bare_macro_does_not_swallow_the_next_line() { let toks = kinds("`BARE\n(a);"); diff --git a/crates/vlog_parser/src/parser.rs b/crates/vlog_parser/src/parser.rs index 688f6ca..bf4aa09 100644 --- a/crates/vlog_parser/src/parser.rs +++ b/crates/vlog_parser/src/parser.rs @@ -86,6 +86,12 @@ const GATE_KEYWORDS: &[&str] = &[ "rtran", "tranif0", "tranif1", "rtranif0", "rtranif1", ]; +/// The elaboration system tasks: the only `$...` calls that may stand where a +/// module or generate item belongs (IEEE 1800 §20.11). The list is closed — +/// `$display(...)` at module scope is still an error, because it is only legal +/// inside a procedural block. +const ELAB_TASKS: &[&str] = &["$fatal", "$error", "$warning", "$info"]; + /// Keywords that close a construct an enclosing parse loop is waiting for. /// Recovery stops *before* them without consuming, so the loop that opened the /// construct still gets to close it — that is what keeps an error inside a @@ -791,7 +797,9 @@ impl<'a> Parser<'a> { /// continues (`` `MACRO(x) = y; ``, `` `MOD #(...) u(); ``, /// `` `TYPE [3:0] x; ``); /// * next token is a plain identifier — `` `TYPE x; `` / - /// `` `MOD u (...); ``, *unless* this invocation has an argument list, + /// `` `MOD u (...); ``, *unless* the identifier is on a **later line** + /// (a type and its declarator are written together; a macro that ends + /// its line is finished), or this invocation has an argument list, /// which no type or module name in real RTL does, or the identifier is /// itself followed by a `#(` — `` `uvm_component_new `` ⏎ /// `` uvm_analysis_port #(bit [31:0]) p; `` is a standalone macro and a @@ -814,6 +822,13 @@ impl<'a> Parser<'a> { TokenKind::Symbol => false, TokenKind::Ident if !next.is_macro() => { self.cur().has_macro_args() + // A line break between the macro and the identifier ends + // the macro: `` `uvm_component_new `` ⏎ ⏎ + // `uvm_report_server rs;` (corpus + // `ibex/dv/uvm/core_ibex/tests/core_ibex_test_lib.sv:19`). + // A macro-named *type* is written on its declarator's own + // line (`` `MY_TYPE_T sig; ``), so this never steals one. + || next.line != self.cur().line || (self.nth(2).is_sym("#") && self.nth(3).is_sym("(")) // `` `WAIT_FOR_RESET `` ⏎ `cov.cg.sample(...);` — a // declarator name is never followed by `.`, so the macro @@ -824,11 +839,49 @@ impl<'a> Parser<'a> { } } + /// True when the cursor is a bare macro name whose argument list the lexer + /// did *not* attach because a space stands between them: + /// `` `uvm_field_int (fetch_addr, UVM_DEFAULT) `` (corpus + /// `ibex/dv/uvm/core_ibex/common/ibex_cosim_agent/ibex_ifetch_pmp_seq_item.sv:10`). + /// + /// Deliberately *not* folded into [`Parser::at_macro_item`]: this reading + /// is only offered where an item or a statement belongs, never in an + /// expression or a port/parameter list. In an expression `` `A (b) `` may + /// well be `` `A `` applied to the parenthesized value `(b)` — the answer + /// depends on whether the macro was defined with formals, which lives in + /// a file vfmt does not read (IEEE 1800 §22.5.1, and the analysis in + /// `docs/features/lexer-cleanup/README.md`). At item position there is no + /// such ambiguity: neither reading is an item on its own. + /// + /// The `(` must be on the macro's own line. A `(` opening the next line is + /// the far more likely start of a separate construct. + fn at_spaced_macro_call(&self) -> bool { + let cur = self.cur(); + cur.is_macro() + && !cur.has_macro_args() + && self.nth(1).is_sym("(") + && self.nth(1).line == cur.line + } + /// Consume a standalone macro invocation and its optional trailing `;`. - fn parse_macro_call(&mut self) -> MacroCall { - let raw = self.take_raw_text(); + fn parse_macro_call(&mut self) -> PResult { + let raw = if self.at_spaced_macro_call() { + let start = self.here(); + let col = self.cur().col; + self.bump(); // `NAME + self.bump(); // ( + self.skip_balanced("(", ")")?; + // Verbatim, space included: the argument text is preprocessor + // input vfmt does not model, and closing the gap would make the + // output's token text differ from the input's (`` `A (b) `` and + // `` `A(b) `` are one token each, of different text) — which the + // safety net rightly refuses. + self.verbatim_since(start, col) + } else { + self.take_raw_text() + }; let semi = self.eat_sym(";"); - MacroCall { raw, semi } + Ok(MacroCall { raw, semi }) } /// Take the comments the lexer attached *before* the current token, @@ -994,14 +1047,19 @@ impl<'a> Parser<'a> { } fn parse_item_kind(&mut self) -> PResult { - if self.at_macro_item() { - return Ok(ItemKind::MacroItem(self.parse_macro_call())); + if self.at_macro_item() || self.at_spaced_macro_call() { + return Ok(ItemKind::MacroItem(self.parse_macro_call()?)); } let t = self.cur(); match t.kind { TokenKind::Directive => Ok(ItemKind::Directive(self.take_raw_text())), TokenKind::Keyword => self.parse_keyword_item(), TokenKind::Ident => self.parse_ident_item(), + TokenKind::SystemIdent if ELAB_TASKS.contains(&t.text.as_str()) => { + let call = self.parse_expr()?; + self.expect_sym(";")?; + Ok(ItemKind::ElabTask(call)) + } _ => self.error("expected item"), } } @@ -2558,8 +2616,8 @@ impl<'a> Parser<'a> { } fn parse_stmt_kind(&mut self) -> PResult { - if self.at_macro_item() { - return Ok(StmtKind::MacroStmt(self.parse_macro_call())); + if self.at_macro_item() || self.at_spaced_macro_call() { + return Ok(StmtKind::MacroStmt(self.parse_macro_call()?)); } let t = self.cur(); if t.kind == TokenKind::Directive { @@ -3823,6 +3881,101 @@ mod tests { ); } + /// `` `uvm_field_int (a, b) `` — the lexer only glues a `(` that touches + /// the macro name, so the argument list arrives as separate tokens and the + /// parser has to rebuild the invocation from the source bytes. + #[test] + fn a_space_before_the_argument_list_is_still_a_macro_item() { + let file = parse_ok( + "class c;\n `uvm_object_utils_begin(c)\n `uvm_field_int (a, UVM_DEFAULT)\n `uvm_object_utils_end\nendclass", + ); + let ItemKind::Class(c) = &file.items[0].kind else { panic!("expected a class") }; + let texts: Vec<&str> = c + .items + .iter() + .map(|i| match &i.kind { + ItemKind::MacroItem(call) => call.raw.text.as_str(), + other => panic!("expected a macro item, got {other:?}"), + }) + .collect(); + assert_eq!( + texts, + [ + "`uvm_object_utils_begin(c)", + "`uvm_field_int (a, UVM_DEFAULT)", + "`uvm_object_utils_end", + ], + "the space and the argument text are reproduced byte-for-byte" + ); + } + + /// The spaced reading is offered at item and statement position only. In + /// an expression `` `A (b) `` may be `` `A `` applied to `(b)`, which + /// depends on a `` `define`` vfmt never sees. + #[test] + fn a_spaced_macro_in_expression_position_is_still_a_call() { + let file = parse_ok("module m;\nassign x = `A (b);\nendmodule"); + let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; + let ItemKind::ContAssign(a) = &m.items[0].kind else { panic!("expected an assign") }; + assert!( + matches!(a.assigns[0].rhs.kind, ExprKind::Call { .. }), + "expression position must keep its old parse: {:?}", + a.assigns[0].rhs.kind + ); + } + + /// A `(` that opens the *next* line is not the macro's argument list. + #[test] + fn a_paren_on_the_next_line_does_not_join_the_macro() { + let file = parse_ok("module m;\n`BARE\ninitial x = (a);\nendmodule"); + let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; + let ItemKind::MacroItem(call) = &m.items[0].kind else { panic!("expected a macro item") }; + assert_eq!(call.raw.text, "`BARE"); + assert!(matches!(m.items[1].kind, ItemKind::Initial(_))); + } + + /// A macro that ends its line is complete; the declaration below it is its + /// own item, not the declarator of a macro-named type. + #[test] + fn a_bare_macro_ending_its_line_does_not_type_the_next_declaration() { + let file = parse_ok( + "class c;\n `uvm_component_new\n\n uvm_report_server rs;\n `MY_TYPE_T sig;\nendclass", + ); + let ItemKind::Class(c) = &file.items[0].kind else { panic!("expected a class") }; + assert!(matches!(c.items[0].kind, ItemKind::MacroItem(_))); + assert!(matches!(c.items[1].kind, ItemKind::DataDecl(_))); + // Same line ⇒ still a declaration with a macro-named type. + assert!(matches!(c.items[2].kind, ItemKind::DataDecl(_))); + } + + #[test] + fn elaboration_tasks_stand_where_items_do() { + let file = parse_ok( + "module m;\n\ + $error(\"a\", \"b\");\n\ + $fatal(1, \"c\");\n\ + $warning(\"d\");\n\ + $info(\"e\");\n\ + if (W < 1) $error(\"f\");\n\ + endmodule", + ); + let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; + for item in &m.items[..4] { + assert!(matches!(item.kind, ItemKind::ElabTask(_)), "got {:?}", item.kind); + } + let ItemKind::GenIf(g) = &m.items[4].kind else { panic!("expected a generate if") }; + assert!(matches!(g.then.items[0].kind, ItemKind::ElabTask(_))); + } + + /// The list is closed: `$display` is only legal inside a procedural block, + /// and accepting it as an item would swallow a real error. + #[test] + fn a_non_elaboration_system_task_is_not_an_item() { + let src = "module m;\n$display(\"x\");\nendmodule"; + let err = parse(tokenize(src).expect("lex error"), src).expect_err("strict must refuse"); + assert!(err.message.contains("expected item"), "unexpected: {err}"); + } + #[test] fn macro_semicolon_is_reproduced_not_invented() { let file = parse_ok("module m;\n`A(x)\n`B(y);\nendmodule"); diff --git a/crates/vlog_parser/tests/spans.rs b/crates/vlog_parser/tests/spans.rs index 8560eb0..114a10c 100644 --- a/crates/vlog_parser/tests/spans.rs +++ b/crates/vlog_parser/tests/spans.rs @@ -484,6 +484,7 @@ fn check_item(src: &str, item: &Item, parent: TextRange) { check_expr(src, &pair.rhs, pair.span); } } + ItemKind::ElabTask(e) => check_expr(src, e, here), ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => { check_stmt(src, stmt, here); } diff --git a/crates/vlog_semantic/src/bind.rs b/crates/vlog_semantic/src/bind.rs index 7abb3ea..e0b4140 100644 --- a/crates/vlog_semantic/src/bind.rs +++ b/crates/vlog_semantic/src/bind.rs @@ -235,6 +235,9 @@ impl<'a> Binder<'a> { self.bind_expr(&a.rhs, scope); } } + // The arguments name real parameters (`$error("...", W)`), so they + // resolve like any other expression. + ItemKind::ElabTask(e) => self.bind_expr(e, scope), ItemKind::Always { stmt, .. } => self.bind_stmt(stmt, scope), ItemKind::Initial(s) | ItemKind::Final(s) => self.bind_stmt(s, scope), ItemKind::Instantiation(i) => self.bind_instantiation(i, scope), diff --git a/docs/features/item-misc/README.md b/docs/features/item-misc/README.md new file mode 100644 index 0000000..3eb1728 --- /dev/null +++ b/docs/features/item-misc/README.md @@ -0,0 +1,281 @@ +# item-misc + +## Goal + +Four unrelated shapes that all stand where a **module / generate / class item** +belongs, and that the corpus loop bucketed into `macro-items` (18 files) and +`elab-tasks` (9 files). Each was a hard parse error, so each cost a whole file: + +1. **A macro invocation with a space before its argument list** — + `` `uvm_field_int (fetch_addr, UVM_DEFAULT) ``. The + `` `uvm_object_utils_begin … `uvm_field_* … `uvm_object_utils_end `` idiom, + 12 corpus files, e.g. + `corpus/ibex/dv/uvm/core_ibex/common/ibex_cosim_agent/ibex_ifetch_pmp_seq_item.sv:10`, + `corpus/ibex/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_env_cfg.sv:66`, + `corpus/ibex/dv/uvm/icache/dv/env/ibex_icache_env_cfg.sv:24`. Documented as + a known gap in `docs/features/macro-items/README.md` and assessed-and-parked + as a *lexer* change in `docs/features/lexer-cleanup/README.md`; this round + lands it as a *parser* change instead, which is what makes it safe. +2. **A bare macro invocation that ends its line, followed by an ordinary + declaration** — `` `uvm_component_new `` ⏎ ⏎ `uvm_report_server rs;`. + 4 corpus files: `corpus/ibex/dv/uvm/core_ibex/tests/core_ibex_test_lib.sv:19`, + `corpus/ibex/vendor/lowrisc_ip/dv/sv/push_pull_agent/push_pull_agent_cov.sv:35`, + `corpus/ibex/dv/uvm/icache/dv/ibex_icache_core_agent/ibex_icache_core_sequencer.sv:13`, + `corpus/ibex/dv/uvm/icache/dv/ibex_icache_core_agent/seq_lib/ibex_icache_core_base_seq.sv:17`. + The old one-token lookahead read the pair as one macro-typed declaration + (`` `uvm_component_new uvm_report_server ``) and then choked on the + declarator. +3. **`` `error "message" ``** as a compiler directive at item position — + `corpus/picorv32/picosoc/icebreaker.v:21`, + `corpus/picorv32/picosoc/picosoc.v:22`, both inside an `` `ifdef``. +4. **Elaboration system tasks as items** — `$error(...)`, `$fatal(...)`, + `$warning(...)`, `$info(...)` with a `;`, at module scope and inside + generate `if`/`for`/`case`/`begin…end`. 9 corpus files: + `corpus/common_cells/src/clk_int_div.sv:109` (inside + `if (...) begin : gen_elab_error`), `corpus/common_cells/src/popcount.sv:31` + (a generate-`if` whose entire body is a bare system task, no `begin`/`end`), + `corpus/common_cells/src/cdc_2phase_clearable.sv:93` and + `corpus/common_cells/src/cdc_fifo_gray_clearable.sv:153` (two string + literals as separate arguments across lines), + `corpus/common_cells/src/deprecated/clk_div.sv:45` (`$warning(` with the + arguments starting on the next line), + `corpus/common_cells/src/stream_arbiter_flushable.sv:78` (inside + `` `ifndef SYNTHESIS `` inside a generate case item), + `corpus/ibex/rtl/ibex_top_tracing.sv:136` (inside `` `ifndef RVFI `` at + module scope), `corpus/common_cells/src/clk_int_div_static.sv:71`, + `corpus/common_cells/src/clk_mux_glitch_free.sv:92`. + +## Assumptions + +- **A spaced macro invocation is still opaque text, and the space is part of + it.** The formatter reproduces `` `uvm_field_int (a, b) `` byte-for-byte + rather than tightening it to the canonical `` `uvm_field_int(a, b) ``. This + is *not* a style preference — it is forced. The lexer delivers a glued + invocation as **one** `Ident` token whose text is the whole call, so + `` `A (x) `` (two-plus tokens) and `` `A(x) `` (one token, text `` `A(x) ``) + are different token streams. Removing the space would make the output's + stream differ from the input's, and `verify.rs` — which this feature must not + and does not touch — would rightly refuse the result. Proven in both + directions by `tightening_a_spaced_macro_call_is_rejected` and + `loosening_a_glued_macro_call_is_rejected` in + `crates/vlog_formatter/tests/verification.rs`. The ruff-like answer (one + canonical spelling) is reachable only from inside the safety net, which is + the lead's call, not this round's. +- **The spaced reading is offered at item and statement position only, never + in an expression.** `assign x = `A (b);` keeps today's parse + (`ExprKind::Call`). `docs/features/lexer-cleanup/README.md` established why: + whether `(b)` is `` `A ``'s argument list or an independent parenthesized + value depends on whether the macro was `` `define``d with formals (IEEE 1800 + §22.5.1), and that definition routinely lives in an `` `include``d file vfmt + never reads — `` `define NOT ~ `` plus `` `NOT (a) `` is the counterexample. + At *item* position that ambiguity does not exist: neither reading is a legal + item on its own, so accepting the invocation cannot take a valid parse away + from anything. That asymmetry is the whole reason this landed in the parser + and not in the lexer, where it was correctly parked. +- **The `(` must be on the macro's own line.** A `(` opening the next line is + far more likely the start of a separate construct, and the lexer already + guards the glued case the same way (`bare_macro_does_not_swallow_the_next_line`). +- **A macro that ends its line is a complete macro.** A type and its declarator + are written together (`` `MY_TYPE_T sig; ``); nobody writes the type on one + line and the declarator on the next. Guessing wrong here still cannot corrupt + code — both readings emit the same tokens in the same order, so only line + breaks differ (the standing `macro-items` argument). +- **`` `error`` / `` `warning`` are a closed two-name addition to the directive + list, not a general "unknown backtick name is a directive" rule.** The + opposite rule would swallow every macro invocation in the corpus. The price + of the closed list is that a *macro* actually named `` `error`` would now be + read as a directive; no such macro exists in the corpus (checked: the only + `` `error``/`` `warning`` occurrences are the two directives above), and IEEE + 1800 §22.8 reserves the names. +- **`$display` at item position stays an error.** Only the four elaboration + tasks of IEEE 1800 §20.11 (`$fatal`, `$error`, `$warning`, `$info`) may stand + where an item does; `$display` is legal only inside a procedural block, and + accepting it would turn a real error into silent acceptance. +- **An elaboration task's arguments are an ordinary expression list.** The + adjacent-string-literal "concatenation by juxtaposition" the corpus uses is + not juxtaposition at all — the strings are separate `,`-separated arguments — + so nothing special is needed for it. +- **An elaboration task item requires its `;`.** `$error` with no parentheses + and no semicolon is legal LRM-wise but appears nowhere; requiring the `;` + keeps a missing one an error rather than a silent re-parse. + +## Handshakes + +**Consumed from `vlog_parser::lexer`:** unchanged contracts — +`Token::is_macro()` / `Token::has_macro_args()`, and `Token::line`, which is +what makes the "ends its line" rule expressible. The one lexer change is two +names added to `is_line_directive` (`error`, `warning`); anything that +enumerates directives by name should know the list grew. + +**Consumed from `vlog_parser::parser` internals (used, not changed):** +`Parser::skip_balanced` and `Parser::verbatim_since` — the same pair +`parse_constraint`/`parse_covergroup` use to lift verbatim source by span. The +spaced invocation is rebuilt from the source bytes with them, which is why +`RawText.col` still points at the backtick and the existing `Fmt::raw_lines` +dedent/re-indent contract keeps working for a multi-line spaced call. + +**Promised to `vlog_formatter`:** + +- `ItemKind::MacroItem(MacroCall)` may now carry a `raw.text` that contains a + space (or a comment, or a newline) between the macro name and its `(`. The + existing "print `raw_text(&call.raw)` verbatim" handling is already correct + for it; nothing must re-space it. +- **New AST variant `ItemKind::ElabTask(Expr)`** — an elaboration system task + standing where a module or generate item belongs. The payload is the ordinary + system-task-call expression, so the formatter prints it exactly like + `StmtKind::ExprStmt`: `concat([self.expr(e), text(";")])`. Its argument group + is the existing breakable call group. + +**Exhaustive-match arms added elsewhere for that new variant** (minimal, no +behavior beyond what the variant needs): + +- `crates/vlog_formatter/src/format.rs` — prints it like a statement. +- `crates/vlog_semantic/src/bind.rs` — `bind_expr` on the payload, because the + arguments name real parameters (`$error("...", DIV_VALUE_WIDTH)`). +- `crates/vlog_parser/tests/spans.rs` — `check_expr` on the payload. +- `crates/vlog_linter/src/visit.rs` needed **no** arm (it already ends in a + catch-all); no lint rule looks at elaboration tasks. + +**Not touched:** `crates/vlog_formatter/src/verify.rs`. No normalization was +added or widened, so the "guilty until proven innocent" clause of CLAUDE.md +does not fire. The two verification tests this feature adds are *attack* tests +in the same spirit — they assert the net still rejects the one rewrite this +feature could plausibly have wanted to make. + +**Requests to other features (out of scope here, not acted on):** none. The two +files that advanced past this feature's constructs into other categories are +listed in the work log for whoever owns those buckets. + +## Status / TODO + +- [x] Baseline `scripts/score.sh` captured before any change. +- [x] Shape 1 — spaced macro invocation at item/statement position + (`Parser::at_spaced_macro_call`, `Parser::parse_macro_call`). +- [x] Shape 1 — expression position deliberately unchanged, with a parser test + pinning it. +- [x] Shape 2 — line-aware `Parser::at_macro_item`. +- [x] Shape 3 — `` `error`` / `` `warning`` added to `is_line_directive`. +- [x] Shape 4 — `ItemKind::ElabTask(Expr)`, parsed at item position, printed + like a statement. +- [x] Cases: 8 in `crates/vlog_formatter/tests/cases/macros.cases` (shapes 1–2, + where the existing macro-item cases live), 11 in the new + `crates/vlog_formatter/tests/cases/item_misc.cases` (shapes 3–4). + Negative/edge cases included: both constructs inside a + `// verilog_format: off` fence, comments attached above and trailing, and + the 100-column boundary in both directions. +- [x] Parser unit tests (6) and lexer unit tests (2). +- [x] Safety-net attack tests (2) for the space-tightening rewrite. +- [x] `cargo fmt --all`, `cargo clippy --all-targets`, `cargo test --workspace` + all clean. +- [x] Score re-run; passing set is a strict superset of the baseline. +- [x] `README.md` "Supported syntax" and the roadmap list updated. +- [x] `TODO.md` note about the macro-items lexer gap updated. + +## Work log + +### 2026-08-20 — dev + +**Baseline** (`cargo build --release && scripts/score.sh`): + +``` +{"passing":636,"total":820,"pct":77.6,"failures_by_category":{"interface":31,"bind":28,"dv-statements":24,"expressions":18,"macro-items":18,"directive-split":14,"assertions":13,"dpi-export":11,"types-decls":11,"elab-tasks":9,"invalid-or-fragment":3,"lex-macro-number":2,"not-verilog":1,"other":1}} +``` + +**After**: + +``` +{"passing":661,"total":820,"pct":80.6,"failures_by_category":{"interface":31,"bind":28,"dv-statements":25,"expressions":19,"directive-split":14,"assertions":13,"dpi-export":11,"types-decls":11,"invalid-or-fragment":3,"lex-macro-number":2,"not-verilog":1,"other":1}} +``` + +**+25 files, 0 lost.** `macro-items` and `elab-tasks` are both gone from the +bucket list. Verified as a set operation, not just as a count: the passing +file list before is a strict subset of the list after (`comm -23` on the two +sorted `pass` columns of `.score-results.tsv` is empty). + +25 of the 27 files in the two categories now pass end to end. The other 2 +advanced to a **new first error in a different category** — progress, and +neither is mine to fix: + +| file | was | now | +|---|---|---| +| `corpus/common_cells/src/cdc_fifo_gray_clearable.sv` | `elab-tasks` 153:5 `$error` | `expressions` 182:5 `expected expression (found "(* async *)")` | +| `corpus/ibex/dv/uvm/core_ibex/tests/core_ibex_test_lib.sv` | `macro-items` 19:21 `expected ';' (found "rs")` | `dv-statements` 483:29 `expected ')' (found "[")` | + +(That is where the `dv-statements` 24→25 and `expressions` 18→19 deltas come +from — both are files arriving from my buckets, not regressions.) + +**Decisions.** + +*Shape 1, parser not lexer.* `docs/features/lexer-cleanup/README.md` assessed +the lexer glue and parked it, correctly: in expression position the reading +depends on a `` `define`` vfmt cannot see. That analysis is entirely about +expression position, so the fix is the same predicate applied only where an +item or a statement belongs. `Parser::at_spaced_macro_call` is deliberately a +*separate* predicate from `at_macro_item` rather than a clause inside it, +because `at_macro_item` is also what `take_list_directives` uses to spot a +macro standing between port/parameter list elements — folding the spaced case +in there would have had that loop consume the bare name and leave the `(` +behind, turning a clean error into a mis-parse. `parse_macro_call` grew a +`PResult` return for `skip_balanced`'s sake. + +*Shape 1, space preserved.* Removing it is the ruff-like choice and I did not +take it, because it is a token-text rewrite the safety net refuses and +`verify.rs` is off limits this round (and should stay off limits for this: the +normalization that would forgive it — "ignore whitespace between a macro name +and its `(`" — is exactly the kind of widening CLAUDE.md invariant 4 is about). +Two attack tests now pin both directions of the rewrite as rejected. Preserving +also keeps the round consistent with the standing `macro-items` assumption that +an invocation is reproduced byte-for-byte. Idempotency is trivially fine: the +output *is* the input bytes. + +*Shape 2, line-awareness in `at_macro_item` itself.* Here the change does +belong in the shared predicate — "a macro that ends its line is finished" is +true at list position too. Checked against the corpus rather than argued: the +passing set stayed a superset, and `macro_lookahead_leaves_declarations_alone` +(the existing test pinning `` `MY_TYPE_T sig; ``, `` `MY_MODULE u_inst (...) `` +and friends) still passes untouched, because each of those writes the macro and +what follows on one line. A comment line between the macro and the declaration +changes nothing — comments are trivia on the token, so the declarator token's +`line` is still a later line. + +*Shape 3, closed list.* Two names, `error` and `warning`, added to +`is_line_directive` with a comment saying why the list must stay closed. Grepped +the corpus first: the only `` `error``/`` `warning`` occurrences anywhere are +the two real directives. A lexer test pins that `` `error_if(x) `` is still a +macro, i.e. that the match is on the exact word and not a prefix. + +*Shape 4, one new item kind.* `ItemKind::ElabTask(Expr)` wrapping the existing +system-task-call expression, gated on a closed four-name list. No new statement +kind and no new expression machinery: `parse_expr` already parses +`$error("a", "b")` as a `Call`, and the generate-block parser already falls +through to `item_or_recover()` for a body with no `begin`/`end`, so +`if (W < 1) $error(...);` (popcount.sv) works with no generate-side change at +all. Formatting is `expr` + `";"`, byte-identical to how `StmtKind::ExprStmt` +prints — which means the argument list is the existing breakable call group and +the 100-column behavior is inherited rather than invented (both boundary +directions are pinned in `item_misc.cases`). + +**Files changed.** + +- `crates/vlog_parser/src/lexer.rs` — `error`/`warning` in `is_line_directive` + + 2 tests. +- `crates/vlog_parser/src/parser.rs` — `ELAB_TASKS`, line-aware + `at_macro_item`, new `at_spaced_macro_call`, `parse_macro_call` rebuilds a + spaced invocation verbatim, `parse_item_kind` accepts an elaboration task + + 6 tests. +- `crates/vlog_parser/src/ast.rs` — `ItemKind::ElabTask(Expr)`. +- `crates/vlog_formatter/src/format.rs` — one arm for it. +- `crates/vlog_semantic/src/bind.rs` — one arm for it. +- `crates/vlog_parser/tests/spans.rs` — one arm for it. +- `crates/vlog_formatter/tests/verification.rs` — 2 attack tests. +- `crates/vlog_formatter/tests/cases/macros.cases` — 8 cases. +- `crates/vlog_formatter/tests/cases/item_misc.cases` — new, 11 cases. +- `README.md`, `TODO.md` — documentation. + +**Gates.** `cargo fmt --all` clean; `cargo clippy --all-targets` clean (no new +`#[allow]`); `cargo test --workspace` green, 28 test binaries, 0 failed. No +`unwrap`/`expect`/`panic!` added outside tests. No `unsafe`. No new dependency. + +## QA log + +## Review diff --git a/docs/features/macro-items/README.md b/docs/features/macro-items/README.md index a2f8c96..0bf7029 100644 --- a/docs/features/macro-items/README.md +++ b/docs/features/macro-items/README.md @@ -60,6 +60,13 @@ already are, so support costs one AST leaf rather than a grammar. *(2026-08-19: assessed by lexer-cleanup and parked — the expression-position risk is real and the glue cannot be proven meaning-preserving; full analysis in `docs/features/lexer-cleanup/README.md`.)* + **(2026-08-20: closed by item-misc, in the parser rather than the lexer. + `Parser::at_spaced_macro_call` offers the invocation reading only where an + item or a statement belongs — the position where neither reading is a legal + parse, so the ambiguity the lexer park is about does not arise. Expression + position is unchanged and still parses `` `A (b) `` as a call. The space is + reproduced as written, not tightened. See + `docs/features/item-misc/README.md`.)** - **Whitespace next to a line break inside a *string literal* is data, not layout.** This is the premise the first round of this feature got wrong; see the QA finding and the fix under Handshakes and Design. Everywhere else in a