From e35da292bddaf60e98f55d93b24e287eea81c5c7 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Fri, 21 Aug 2026 01:42:53 -0700 Subject: [PATCH] Add mop-up-2: macro items ending their line, new shallow copy, 32'h`MACRO A macro invocation that ends its line is a complete item whatever opens the next line; new shallow-copy constructor; a based number whose digits come from a macro (32'h`BOOT_ADDR) lexes as a base-only number joined with the macro in the parser. verify.rs untouched, attack tests added. Coverage loop round 2: 796 -> 800 / 820 (97.1% -> 97.6%). Feature README: docs/features/mop-up-2/README.md Co-Authored-By: Claude Fable 5 --- README.md | 21 +- TODO.md | 11 + crates/vlog_formatter/src/format.rs | 3 + .../vlog_formatter/tests/cases/classes.cases | 69 +++++ .../tests/cases/expressions_2.cases | 43 +++ .../vlog_formatter/tests/cases/macros.cases | 86 ++++++ crates/vlog_formatter/tests/verification.rs | 34 +++ crates/vlog_parser/src/ast.rs | 6 + crates/vlog_parser/src/lexer.rs | 44 +++ crates/vlog_parser/src/parser.rs | 202 +++++++++++++- crates/vlog_parser/src/token.rs | 17 ++ crates/vlog_parser/tests/spans.rs | 1 + crates/vlog_semantic/src/bind.rs | 2 + docs/features/mop-up-2/README.md | 255 ++++++++++++++++++ 14 files changed, 778 insertions(+), 16 deletions(-) create mode 100644 docs/features/mop-up-2/README.md diff --git a/README.md b/README.md index 299f448..24d9f20 100644 --- a/README.md +++ b/README.md @@ -406,7 +406,9 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset: assignment target), casts over any constant primary (`int'(x)`, `(NumLevels)'(x)`, `pkg::Width'(x)`), assignment patterns (`'{...}`, including the replication form `'{N{0}}`), `inside` (with a `{...}` set or - a macro standing in for one), hierarchical and package-scoped names. See + a macro standing in for one), hierarchical and package-scoped names, and + the `new` forms — the constructor `new(...)`, the dynamic-array resize + `new[N]` and the shallow copy `new obj` (IEEE 1800 §8.12). See `docs/features/expressions-2/README.md` - Drive strengths on a continuous assignment (`assign (weak0, pull1) x = y;`), `const ref` task/function arguments, and @@ -421,8 +423,13 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset: 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` + A macro that ends its line is a complete macro, so whatever opens the next + line — a declaration, or a statement starting with `@`, `#`, `->` or `{` — + is its own item. See `docs/features/item-misc/README.md` and + `docs/features/mop-up-2/README.md` +- A based number whose digits come from a macro (`` 32'h`DM_ADDR ``, + `` 8'b`BITS ``). The backtick must touch the base; `` 32'h `X `` stays a lex + error. See `docs/features/mop-up-2/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` @@ -527,6 +534,14 @@ corpus baseline this ordering comes from: 26 files format, the other 2 advanced to a macro-items blocker and to the `new obj` shallow-copy expression. `specify` blocks, `checker`, `program`, `interface class` and `randsequence` remain unsupported +11. ~~A macro statement that ends its line followed by a symbol on the next + one, the `new obj` shallow copy (IEEE 1800 §8.12), and a based number + whose digits come from a macro (`` 32'h`DM_ADDR ``)~~ — **done**; see + `docs/features/mop-up-2/README.md`. Unblocked the last 4 fixable corpus + files and moved the parse rate from 97.1% to 97.6%. Every file still + failing is in a deliberately unsupported category, except + `compare_helper.sv`, whose `` `X_EACH_CSR 1 `` needs a macro body from + another file — vfmt does not preprocess, so it stays a parse error Like ruff, `vfmt` refuses to output anything for a file it cannot fully parse, so it can never corrupt code. diff --git a/TODO.md b/TODO.md index e699220..d7a8073 100644 --- a/TODO.md +++ b/TODO.md @@ -368,6 +368,17 @@ Adapt each: macro-items (a bare macro followed by `@` on the next line), `riscv_instr.sv` to the `new obj` shallow-copy expression. `directive-split` (14 files) is now the top blocker. + → mop-up-2 (`docs/features/mop-up-2/README.md`) then took it from + 796/820 (97.1%, the baseline on the same tree) to **800/820 (97.6%)** + — 4 files gained, 0 lost, passing set verified as a strict superset. A + macro statement that ends its line followed by a symbol on the next + one, the `new obj` shallow copy (IEEE 1800 §8.12), and a based number + whose digits are a macro (`` 32'h`DM_ADDR ``) are done; the + `lex-macro-number` bucket is gone. `compare_helper.sv` stays failing + and is not fixable: `` `X_EACH_CSR 1 `` needs the macro's body, which + lives in a file vfmt deliberately does not read. `directive-split` (14 + files) is still the top blocker, and every remaining failure is in a + deliberately-unsupported category. - [ ] **[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 e6c0323..17fd603 100644 --- a/crates/vlog_formatter/src/format.rs +++ b/crates/vlog_formatter/src/format.rs @@ -2784,6 +2784,9 @@ impl<'a> Fmt<'a> { ExprKind::Call { callee, args } => { concat(vec![self.expr(callee), self.expr_list("(", args, ")")]) } + // `new src` — one space, never a break: the source handle is a + // postfix expression that breaks internally if it must. + ExprKind::New(src) => concat(vec![text("new "), self.expr(src)]), ExprKind::Index { base, index } => { concat(vec![self.expr(base), text("["), self.expr_compact(index), text("]")]) } diff --git a/crates/vlog_formatter/tests/cases/classes.cases b/crates/vlog_formatter/tests/cases/classes.cases index 7ab5cbb..42d076f 100644 --- a/crates/vlog_formatter/tests/cases/classes.cases +++ b/crates/vlog_formatter/tests/cases/classes.cases @@ -491,3 +491,72 @@ name == "a b"; } endclass +==== +# a shallow copy: `new ` (IEEE 1800 8.12) +class c; +function riscv_instr get_rand_instr(); +riscv_instr instr_h; +// Shallow copy for all relevant fields, avoid using create() +instr_h = new instr_template[name]; +h2 = new pkg::templates[idx].handle; +return instr_h; +endfunction +endclass +---- +class c; + function riscv_instr get_rand_instr(); + riscv_instr instr_h; + // Shallow copy for all relevant fields, avoid using create() + instr_h = new instr_template[name]; + h2 = new pkg::templates[idx].handle; + return instr_h; + endfunction +endclass +==== +# the constructor, the bare handle and the dynamic-array resize keep their old parse +class c; +function void f(); +a = new; +b = new(x, y); +data_valid = new[num_ways]; +q = new[n](old_q); +endfunction +endclass +---- +class c; + function void f(); + a = new; + b = new(x, y); + data_valid = new[num_ways]; + q = new[n](old_q); + endfunction +endclass +==== +# a shallow copy at the line-length boundary is not broken apart +class c; +function void f(); +this.a_fairly_long_destination_handle_name = new a_fairly_long_source_handle[i]; +endfunction +endclass +---- +class c; + function void f(); + this.a_fairly_long_destination_handle_name = new a_fairly_long_source_handle[i]; + endfunction +endclass +==== +# a bare `new` whose `;` opens the next line is still a bare handle +class c; +function void f(); +h = +new; +g = 1; +endfunction +endclass +---- +class c; + function void f(); + h = new; + g = 1; + endfunction +endclass diff --git a/crates/vlog_formatter/tests/cases/expressions_2.cases b/crates/vlog_formatter/tests/cases/expressions_2.cases index efae1ce..f729ad7 100644 --- a/crates/vlog_formatter/tests/cases/expressions_2.cases +++ b/crates/vlog_formatter/tests/cases/expressions_2.cases @@ -308,3 +308,46 @@ module m; assign other_target_name_here = {<<8{some_quite_long_source_signal_name_x}}; endmodule ==== +==== +# a based number whose digits are a macro: the two stay adjacent +module m; +parameter int unsigned DmBaseAddr = 32'h`DM_ADDR; +localparam int Z = 'h`UNSIZED; +localparam int W = 32'sh`SIGNED; +localparam int V = 8'b`BITS; +endmodule +---- +module m; + parameter int unsigned DmBaseAddr = 32'h`DM_ADDR; + localparam int Z = 'h`UNSIZED; + localparam int W = 32'sh`SIGNED; + localparam int V = 8'b`BITS; +endmodule +==== +# a macro-digit number inside a parenthesized `&`/`|` expression +module m; +initial begin +cosim_cfg.start_pc = ((32'h`BOOT_ADDR & ~(32'h0000_00FF)) | 8'h80); +end +endmodule +---- +module m; + initial begin + cosim_cfg.start_pc = ((32'h`BOOT_ADDR & ~(32'h0000_00FF)) | 8'h80); + end +endmodule +==== +# a macro-digit number inside a format fence comes out byte-exact +module m; +// verilog_format: off +localparam int X = 32'h`RAW; +// verilog_format: on +localparam int Y = 32'h`RAW; +endmodule +---- +module m; +// verilog_format: off +localparam int X = 32'h`RAW; +// verilog_format: on + localparam int Y = 32'h`RAW; +endmodule diff --git a/crates/vlog_formatter/tests/cases/macros.cases b/crates/vlog_formatter/tests/cases/macros.cases index 0014f84..44ed03f 100644 --- a/crates/vlog_formatter/tests/cases/macros.cases +++ b/crates/vlog_formatter/tests/cases/macros.cases @@ -365,3 +365,89 @@ module m; // verilog_format: on wire a; endmodule +==== +# a macro statement that ends its line is complete: a symbol opens the next statement +class c extends b; +task t; +`uvm_info(`gfn, "waiting for rst_n assertion...", UVM_MEDIUM) +@(negedge cfg.clk_rst_vif.rst_n); +`DV_WAIT +#10ns; +`SEND +-> ev; +`PRE +{a, b} = c; +endtask +endclass +---- +class c extends b; + task t; + `uvm_info(`gfn, "waiting for rst_n assertion...", UVM_MEDIUM) + @(negedge cfg.clk_rst_vif.rst_n); + `DV_WAIT + #10ns; + `SEND + -> ev; + `PRE + {a, b} = c; + endtask +endclass +==== +# a `(` on the next line opens a new statement; a `;` on it still ends the macro +module m; +initial begin +`M +(x) = y; +`AFTER +; +end +endmodule +---- +module m; + initial begin + `M + (x) = y; + `AFTER; + end +endmodule +==== +# a symbol on the macro's own line still continues it +module m; +`MY_TYPE_T [3:0] vec; +`MY_MODULE #(.W(8)) u_param (.a(sig)); +initial `LVALUE(x) = 1; +endmodule +---- +module m; + `MY_TYPE_T [3:0] vec; + `MY_MODULE #(.W(8)) u_param (.a(sig)); + initial `LVALUE(x) = 1; +endmodule +==== +# a macro whose arguments span lines ends on its last line, not on its first +module m; +`PACKED(a, + b) [3:0] vec; +endmodule +---- +module m; + `PACKED(a, + b) [3:0] vec; +endmodule +==== +# a macro item followed by a comment line and then a statement symbol +class c extends b; +task t; +`uvm_info(`gfn, "done", UVM_HIGH) +// wait for the next edge +@(posedge clk); +endtask +endclass +---- +class c extends b; + task t; + `uvm_info(`gfn, "done", UVM_HIGH) + // wait for the next edge + @(posedge clk); + endtask +endclass diff --git a/crates/vlog_formatter/tests/verification.rs b/crates/vlog_formatter/tests/verification.rs index 133adc2..f7f02ad 100644 --- a/crates/vlog_formatter/tests/verification.rs +++ b/crates/vlog_formatter/tests/verification.rs @@ -120,6 +120,40 @@ fn tightening_a_spaced_macro_call_is_rejected() { } } +/// Why `` 32'h`DM_ADDR `` is printed with no gap: the backtick has to touch +/// the base or the text does not lex as a number at all. Nothing in +/// `verify.rs` forgives the space, and this test is here so nothing starts to. +#[test] +fn spacing_out_a_macro_digit_number_is_rejected() { + let input = "module m;\n localparam int A = 32'h`W;\nendmodule\n"; + let output = "module m;\n localparam int A = 32'h `W;\nendmodule\n"; + match expect_divergence(input, output) { + VerificationError::Lex { .. } => {} + other => panic!("wrong error: {other}"), + } + // And the mirror image: a number that really does carry its own digits + // must not gain a macro. + let input = "module m;\n localparam int A = 32'h1;\nendmodule\n"; + let output = "module m;\n localparam int A = 32'h`W;\nendmodule\n"; + expect_divergence(input, output); +} + +/// `new src` (IEEE 1800 §8.12) prints with exactly one space. Closing it would +/// make one identifier out of two tokens — the net refuses that, in both +/// directions. +#[test] +fn gluing_a_shallow_copy_to_its_source_handle_is_rejected() { + let input = "class c;\n function void f();\n a = new src;\n endfunction\nendclass\n"; + let output = "class c;\n function void f();\n a = newsrc;\n endfunction\nendclass\n"; + match expect_divergence(input, output) { + VerificationError::Divergence { expected, got, .. } => { + assert_eq!(expected.expect("expected item").text, "new"); + assert_eq!(got.expect("got item").text, "newsrc"); + } + other => panic!("wrong error: {other}"), + } +} + /// The mirror image: re-spacing a *glued* invocation is rejected too, so the /// formatter cannot drift between the two spellings in either direction. #[test] diff --git a/crates/vlog_parser/src/ast.rs b/crates/vlog_parser/src/ast.rs index f654c82..cb1f76e 100644 --- a/crates/vlog_parser/src/ast.rs +++ b/crates/vlog_parser/src/ast.rs @@ -1344,6 +1344,12 @@ pub enum ExprKind { callee: Box, args: Vec, }, + /// A shallow copy, IEEE 1800 §8.12: `new instr_template[name]` (corpus + /// `ibex/vendor/google_riscv-dv/src/isa/riscv_instr.sv:238`). The payload + /// is the source handle — a postfix expression, never a call, because + /// `new(...)` and `new[N]` are the constructor and the dynamic-array + /// resize, which stay an ordinary `Call`/`Index` on the name `new`. + New(Box), Index { base: Box, index: Box, diff --git a/crates/vlog_parser/src/lexer.rs b/crates/vlog_parser/src/lexer.rs index 541b782..174c922 100644 --- a/crates/vlog_parser/src/lexer.rs +++ b/crates/vlog_parser/src/lexer.rs @@ -634,6 +634,20 @@ impl<'a> RawLexer<'a> { return Err(self.error("expected number base after '".to_string())); } text.push(self.bump() as char); + // A based number whose digits come from a macro: `` 32'h`DM_ADDR `` + // (corpus `ibex/dv/uvm/core_ibex/tb/core_ibex_tb_top.sv:75`). The + // digits are preprocessor output vfmt does not expand, so the number + // token ends here, with no digits, and the invocation lexes as the + // macro token it is; the parser rejoins the pair into one primary + // expression and the formatter prints them adjacent, as written. + // + // The backtick must *touch* the base: `` 32'h `DM_ADDR `` keeps the + // "expected digits" error below, because a space there is far more + // likely a typo than this idiom, and accepting it would silently + // change what the source says. + if self.peek() == b'`' { + return Ok(text); + } // Whitespace is allowed between base and value. while matches!(self.peek(), b' ' | b'\t') { self.bump(); @@ -916,6 +930,36 @@ mod tests { assert_eq!(toks[1], (TokenKind::Symbol, "(".to_string())); } + #[test] + fn a_macro_supplies_the_digits_of_a_based_number() { + // `parameter int unsigned DmBaseAddr = 32'h`DM_ADDR;` (corpus + // `ibex/dv/uvm/core_ibex/tb/core_ibex_tb_top.sv:75`): the number token + // ends at the base and the macro follows as its own token. + let toks = kinds("32'h`DM_ADDR;"); + assert_eq!(toks[0], (TokenKind::Number, "32'h".to_string())); + assert_eq!(toks[1], (TokenKind::Ident, "`DM_ADDR".to_string())); + assert_eq!(toks[2], (TokenKind::Symbol, ";".to_string())); + // Unsized and signed spellings take the same path. + assert_eq!(kinds("'h`X")[0], (TokenKind::Number, "'h".to_string())); + assert_eq!(kinds("32'sh`X")[0], (TokenKind::Number, "32'sh".to_string())); + } + + #[test] + fn a_space_before_the_macro_digits_is_still_a_lex_error() { + // The backtick has to touch the base. A space there is a typo, and + // accepting it would change what the source says. + let err = tokenize("32'h `DM_ADDR;").expect_err("expected a lex error"); + assert!(err.message.contains("expected digits after number base"), "unexpected: {err}"); + } + + #[test] + fn a_base_followed_by_a_non_digit_is_still_a_lex_error() { + for src in ["32'h;", "32'h)", "32'h"] { + let err = tokenize(src).expect_err("expected a lex error"); + assert!(err.message.contains("expected digits after number base"), "unexpected: {err}"); + } + } + #[test] fn attributes() { let toks = kinds("(* keep = \"true\" *) wire w;"); diff --git a/crates/vlog_parser/src/parser.rs b/crates/vlog_parser/src/parser.rs index bd62571..eddf91a 100644 --- a/crates/vlog_parser/src/parser.rs +++ b/crates/vlog_parser/src/parser.rs @@ -819,13 +819,17 @@ impl<'a> Parser<'a> { /// one-token lookahead: /// /// * next token is `;` — always a standalone invocation; - /// * next token is any other symbol — an expression or declaration - /// continues (`` `MACRO(x) = y; ``, `` `MOD #(...) u(); ``, + /// * next token is on a **later line** than the one the invocation ends + /// on — a macro that ends its line is a finished macro item, and + /// whatever opens the next line opens a new construct + /// (`` `uvm_info(`gfn, "...", UVM_MEDIUM) `` ⏎ + /// `@(posedge cfg.clk_rst_vif.rst_n);`, corpus + /// `ibex/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_vseq.sv:160`); + /// * next token is any other symbol on the same line — an expression or + /// declaration continues (`` `MACRO(x) = y; ``, `` `MOD #(...) u(); ``, /// `` `TYPE [3:0] x; ``); - /// * next token is a plain identifier — `` `TYPE x; `` / - /// `` `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, + /// * next token is a plain identifier on the same line — `` `TYPE x; `` / + /// `` `MOD u (...); ``, *unless* 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 @@ -844,17 +848,21 @@ impl<'a> Parser<'a> { if next.is_sym(";") { return true; } + // A line break between the invocation and the next token ends the + // macro, whatever kind that token is: `` `uvm_component_new `` ⏎ ⏎ + // `uvm_report_server rs;` (corpus + // `ibex/dv/uvm/core_ibex/tests/core_ibex_test_lib.sv:19`) and + // `` `uvm_info(...) `` ⏎ `@(posedge clk);` are the same shape. A type + // and its declarator are written together (`` `MY_TYPE_T sig; ``), and + // so are a macro and the `[3:0]` / `= y` that continues it, so this + // never steals one. + if next.line != self.macro_end_line() { + return true; + } match next.kind { 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 @@ -865,6 +873,15 @@ impl<'a> Parser<'a> { } } + /// The source line the macro invocation at the cursor *ends* on. The lexer + /// hands a whole invocation over as one token, so a call whose argument + /// list spans lines (`` `uvm_info(a, `` ⏎ `` b) ``) starts well before it + /// ends, and only the end line answers "did this macro end its line?". + fn macro_end_line(&self) -> u32 { + let cur = self.cur(); + cur.line + cur.text.bytes().filter(|b| *b == b'\n').count() as u32 + } + /// 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 @@ -4298,11 +4315,45 @@ impl<'a> Parser<'a> { Ok(self.expr_at(start, ExprKind::AssignPatternRepl { count: Box::new(count), inner })) } + /// True when the cursor is the `new` of a shallow copy, IEEE 1800 §8.12: + /// `instr_h = new instr_template[name];` (corpus + /// `ibex/vendor/google_riscv-dv/src/isa/riscv_instr.sv:238`). + /// + /// `new` is deliberately not a keyword (see `token.rs`'s `is_keyword`), so + /// this is a two-token test on an ordinary name. Only a plain identifier + /// **on `new`'s own line** starts a source handle: the constructor call + /// `new(...)`, the dynamic-array resize `new[N]` and the bare `new` of + /// `x = new;` are all followed by a symbol and keep parsing as a `Call`, + /// an `Index` and an `Ident`. Requiring the same line keeps a variable + /// actually named `new` that ends its line (`x = new;` written without the + /// `;` on the same line is not valid anyway) from swallowing the next + /// statement. + fn at_shallow_copy(&self) -> bool { + let cur = self.cur(); + let next = self.nth(1); + cur.kind == TokenKind::Ident + && cur.text == "new" + && next.kind == TokenKind::Ident + && !next.is_macro() + && next.line == cur.line + } + fn parse_primary(&mut self) -> PResult { let start = self.here(); let t = self.cur(); match t.kind { TokenKind::Number => { + // `` 32'h`DM_ADDR `` — a based number whose digits are a macro + // invocation (corpus + // `ibex/dv/uvm/core_ibex/tb/core_ibex_tb_top.sv:75`). The two + // tokens are one literal; joining their text here prints them + // back adjacent, which is the only spelling that re-lexes to + // the same pair. + if t.is_base_only_number() && self.nth(1).is_macro() { + let mut text = self.bump().text; + text.push_str(&self.bump().text); + return Ok(self.expr_at(start, ExprKind::Number(text))); + } let text = self.bump().text; Ok(self.expr_at(start, ExprKind::Number(text))) } @@ -4311,6 +4362,11 @@ impl<'a> Parser<'a> { Ok(self.expr_at(start, ExprKind::Str(text))) } TokenKind::Ident | TokenKind::SystemIdent => { + if self.at_shallow_copy() { + self.bump(); // new + let src = self.parse_postfix()?; + return Ok(self.expr_at(start, ExprKind::New(Box::new(src)))); + } let text = self.bump().text; Ok(self.expr_at(start, ExprKind::Ident(text))) } @@ -4922,6 +4978,126 @@ mod tests { assert!(matches!(c.items[2].kind, ItemKind::DataDecl(_))); } + /// A macro statement that ends its line is complete whatever *kind* of + /// token opens the next line — a symbol as much as an identifier + /// (`corpus/ibex/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_vseq.sv:160`). + #[test] + fn a_symbol_on_the_next_line_does_not_continue_a_macro_statement() { + let file = parse_ok( + "class c;\n\ + task t;\n\ + `uvm_info(`gfn, \"waiting\", UVM_MEDIUM)\n\ + @(negedge rst_n);\n\ + `DV_WAIT\n\ + #10ns;\n\ + `SEND\n\ + -> ev;\n\ + `PRE\n\ + {a, b} = c;\n\ + endtask\n\ + endclass", + ); + let ItemKind::Class(c) = &file.items[0].kind else { panic!("expected a class") }; + let ItemKind::Task(t) = &c.items[0].kind else { panic!("expected a task") }; + let macros = t.stmts.iter().filter(|s| matches!(s.kind, StmtKind::MacroStmt(_))).count(); + assert_eq!(macros, 4, "each macro stands alone: {:?}", t.stmts); + assert_eq!(t.stmts.len(), 8, "and each next line opens its own statement"); + } + + /// The same rule must not fire on the macro's *own* line, and a macro + /// whose argument list spans lines owns every line it covers. + #[test] + fn a_symbol_on_the_macros_own_line_still_continues_it() { + let file = parse_ok( + "module m;\n\ + `MY_TYPE_T [3:0] vec;\n\ + `PACKED(a,\n\ + b) [7:0] wide;\n\ + endmodule", + ); + let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; + assert!( + !m.items.iter().any(|i| matches!(i.kind, ItemKind::MacroItem(_))), + "both lines declare: {:?}", + m.items + ); + } + + /// `instr_h = new instr_template[name];` — IEEE 1800 §8.12 shallow copy + /// (corpus `ibex/vendor/google_riscv-dv/src/isa/riscv_instr.sv:238`). + #[test] + fn new_followed_by_a_name_is_a_shallow_copy() { + let file = parse_ok( + "class c;\n\ + function void f();\n\ + instr_h = new instr_template[name];\n\ + endfunction\n\ + endclass", + ); + let ItemKind::Class(c) = &file.items[0].kind else { panic!("expected a class") }; + let ItemKind::Function(f) = &c.items[0].kind else { panic!("expected a function") }; + let StmtKind::Assign { rhs, .. } = &f.stmts[0].kind else { panic!("expected an assign") }; + let ExprKind::New(src) = &rhs.kind else { + panic!("expected a shallow copy: {:?}", rhs.kind) + }; + assert!(matches!(src.kind, ExprKind::Index { .. }), "got {:?}", src.kind); + } + + /// The constructor, the bare handle and the dynamic-array resize are all + /// followed by a symbol, so they keep parsing as they always did. + #[test] + fn the_other_spellings_of_new_keep_their_old_parse() { + let file = parse_ok( + "class c;\n\ + function void f();\n\ + a = new;\n\ + b = new(x, y);\n\ + d = new[n];\n\ + new = 1;\n\ + endfunction\n\ + endclass", + ); + let ItemKind::Class(c) = &file.items[0].kind else { panic!("expected a class") }; + let ItemKind::Function(f) = &c.items[0].kind else { panic!("expected a function") }; + let rhs_kinds: Vec<&ExprKind> = f + .stmts + .iter() + .map(|s| { + let StmtKind::Assign { rhs, .. } = &s.kind else { panic!("expected an assign") }; + &rhs.kind + }) + .collect(); + assert!(matches!(rhs_kinds[0], ExprKind::Ident(n) if n == "new")); + assert!(matches!(rhs_kinds[1], ExprKind::Call { .. })); + assert!(matches!(rhs_kinds[2], ExprKind::Index { .. })); + // `new` used as an ordinary variable name is still an ordinary name. + assert!(matches!(rhs_kinds[3], ExprKind::Number(_))); + } + + /// `` 32'h`DM_ADDR `` — the lexer stops the number at the base, and the + /// parser joins the pair back into one literal. + #[test] + fn a_macro_digit_number_is_one_primary_expression() { + let file = parse_ok("module m;\nlocalparam int A = 32'h`DM_ADDR;\nendmodule"); + let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected a module") }; + let ItemKind::ParamDecl(p) = &m.items[0].kind else { panic!("expected a localparam") }; + let init = p.declarators[0].init.as_ref().expect("a value"); + assert!( + matches!(&init.kind, ExprKind::Number(n) if n == "32'h`DM_ADDR"), + "got {:?}", + init.kind + ); + } + + /// A base with no digits and no macro after it stays an error: the macro + /// must be the very next token. + #[test] + fn a_base_only_number_without_a_macro_is_a_parse_error() { + let src = "module m;\nlocalparam int A = 32'h`ifdef;\nendmodule"; + let toks = tokenize(src).expect("lex error"); + assert!(parse(toks, src).is_err(), "a directive is not the number's digits"); + } + #[test] fn elaboration_tasks_stand_where_items_do() { let file = parse_ok( diff --git a/crates/vlog_parser/src/token.rs b/crates/vlog_parser/src/token.rs index 68bc262..321d736 100644 --- a/crates/vlog_parser/src/token.rs +++ b/crates/vlog_parser/src/token.rs @@ -91,6 +91,23 @@ impl Token { pub fn has_macro_args(&self) -> bool { self.is_macro() && self.text.contains('(') } + + /// True for a based number whose digits are missing because a macro + /// supplies them: the `32'h` of `` 32'h`DM_ADDR ``. The lexer emits one + /// only when the very next source character is the backtick, so the + /// macro token always follows immediately. + pub fn is_base_only_number(&self) -> bool { + if self.kind != TokenKind::Number { + return false; + } + let Some((_, tail)) = self.text.rsplit_once('\'') else { + return false; + }; + // The optional sign marker (`32'sh`) sits between the tick and base. + let base = tail.strip_prefix(['s', 'S']).unwrap_or(tail); + base.len() == 1 + && matches!(base.as_bytes()[0], b'd' | b'D' | b'b' | b'B' | b'o' | b'O' | b'h' | b'H') + } } /// Reserved words we treat as keywords. This covers Verilog-2001 plus the diff --git a/crates/vlog_parser/tests/spans.rs b/crates/vlog_parser/tests/spans.rs index 8265e27..4ab350e 100644 --- a/crates/vlog_parser/tests/spans.rs +++ b/crates/vlog_parser/tests/spans.rs @@ -875,6 +875,7 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) { check_expr(src, &a.expr, here); } } + ExprKind::New(source) => check_expr(src, source, here), ExprKind::Index { base, index } => { check_expr(src, base, here); check_expr(src, index, here); diff --git a/crates/vlog_semantic/src/bind.rs b/crates/vlog_semantic/src/bind.rs index aac5549..5497199 100644 --- a/crates/vlog_semantic/src/bind.rs +++ b/crates/vlog_semantic/src/bind.rs @@ -1058,6 +1058,8 @@ impl<'a> Binder<'a> { self.bind_expr(&a.expr, scope); } } + // `new src` — the source handle is an ordinary reference. + ExprKind::New(src) => self.bind_expr(src, scope), ExprKind::Index { base, index } => { self.bind_expr(base, scope); self.bind_expr(index, scope); diff --git a/docs/features/mop-up-2/README.md b/docs/features/mop-up-2/README.md new file mode 100644 index 0000000..e13dbaf --- /dev/null +++ b/docs/features/mop-up-2/README.md @@ -0,0 +1,255 @@ +# mop-up-2 + +## Goal + +Round-2 mop-up: the last *fixable* parse failures in the 820-file corpus. +Three unrelated shapes, four files, each one the whole file's blocker: + +1. **A macro statement that ends its line, followed by a line that starts + with a symbol** — `` `uvm_info(`gfn, "waiting for rst_n assertion...", + UVM_MEDIUM) `` ⏎ `@(negedge cfg.clk_rst_vif.rst_n);` (corpus + `ibex/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_vseq.sv:160`). + `Parser::at_macro_item` already knew that a macro which ends its line is a + finished macro item, but only when an *identifier* opened the next line; + a symbol still read as "the expression continues". +2. **A shallow copy in expression position** — `instr_h = new + instr_template[name];` (IEEE 1800 §8.12; corpus + `ibex/vendor/google_riscv-dv/src/isa/riscv_instr.sv:238`). `new` is not a + keyword, so the pair parsed as two adjacent names and the statement lost + its `;`. +3. **A based number whose digits come from a macro** — `32'h`DM_ADDR` + (corpus `ibex/dv/uvm/core_ibex/tb/core_ibex_tb_top.sv:75`) and + `((32'h`BOOT_ADDR & ~(32'h0000_00FF)) | 8'h80)` (corpus + `ibex/dv/uvm/core_ibex/tests/core_ibex_base_test.sv:142`). The lexer + refused it with "expected digits after number base", so the file never + reached the parser. + +A fourth shape was investigated and deliberately **not** implemented: see +"`X_EACH_CSR`" under Assumptions. + +## Assumptions + +- **A macro that ends its line is a complete macro item, whatever kind of + token opens the next line.** This is the standing `macro-items` assumption + (`docs/features/item-misc/README.md`) with the `TokenKind::Symbol` exception + removed. Guessing wrong still cannot corrupt code — both readings emit the + same tokens in the same order, so only line breaks differ — but it does move + where a *parse error* falls. Two shapes that used to parse now do not: + `` `T `` ⏎ `[3:0] x;` (a macro-named type whose packed dimension opens the + next line) and `` `MOD `` ⏎ `#(.W(8)) u ();`. Neither appears anywhere in the + corpus, nobody writes a type on one line and its dimensions on the next, and + the outcome is a clean exit-2 error with the input untouched, never a + rewrite. The same-line spellings (`` `T [3:0] x; ``, `` `MOD #(.W(8)) u + (); ``, `` `LVALUE(x) = 1; ``) are unchanged and pinned by cases and by the + pre-existing `macro_lookahead_leaves_declarations_alone`. +- **"Ends its line" means the invocation's *last* line.** The lexer hands a + whole invocation over as one token, so `` `PACKED(a, `` ⏎ `` b) [3:0] vec; `` + starts on one line and ends on another; the new `Parser::macro_end_line` + counts the newlines in the token's text so the `[` is correctly seen as + standing on the macro's own line. Without this the multi-line declaration + would have regressed. +- **`` `M `` ⏎ `(x)` is a macro item followed by a new construct**, not a + spaced macro call. `Parser::at_spaced_macro_call` already required the `(` + to be on the macro's line, and the lexer's + `bare_macro_does_not_swallow_the_next_line` agrees; the new rule just makes + the *item* reading fire first, which is the same answer. +- **A shallow copy is `new` followed by a plain identifier on `new`'s own + line.** `new` stays a non-keyword (`token.rs`'s `is_keyword` explains why), + so this is a two-token test on an ordinary name. Every other spelling is + followed by a *symbol* and keeps its old parse: `x = new;` is an `Ident`, + `x = new(a, b)` a `Call`, `x = new[N]` an `Index` (the reading + `docs/features/dynamic-types/README.md` pinned), and `new = 1;` is an + assignment to a variable that happens to be called `new`. The source handle + is parsed with `parse_postfix`, so `new pkg::t[i].h` works and `new a + b` + parses as `(new a) + b` — the §8.12 grammar's precedence. +- **The macro that supplies a number's digits must touch the base.** + `` 32'h `DM_ADDR `` (with a space) stays the "expected digits after number + base" lex error it always was: a space there is far more likely a typo than + this idiom, and the formatter could not print the accepted form back anyway + — `` 32'h `X `` does not re-lex as a number, so the safety net would reject + its own output. `` 32'h `` with a non-digit, non-backtick after it is + likewise still an error. +- **A number with macro digits is *two* tokens and one expression.** The + lexer emits `Number("32'h")` then the ordinary macro token; the parser joins + their text into one `ExprKind::Number`. Splitting in the lexer rather than + gluing there keeps the "how far does a macro invocation reach" question in + the one place that already answers it (`scan_macro_args`), and keeps the + invocation visible as a macro token to anything that walks the stream. +- **`` `X_EACH_CSR 1 `` (corpus + `ibex/dv/formal/check/peek/compare_helper.sv:69`) is not fixable and was not + attempted.** Confirmed the previous dev's conclusion: `` `X_EACH_CSR `` is + defined in `corpus/ibex/dv/formal/check/top.sv:206` as a chain of `` `X(...) + `` invocations, and the file-local `` `define X(c) ... && `` makes the + expansion end in a dangling `&&`, so `` `X_EACH_CSR 1 `` is one expression + only *after* preprocessing. vfmt deliberately does not read `` `define `` + bodies from other files, and the only rule that would accept the shape + without them — "a macro in expression position may be followed by an + operand" — would have to accept `` `A b `` everywhere, which is exactly the + `` `TYPE x; `` declaration this parser spends `at_macro_item` telling apart. + Left failing. +- **A comment written between `new` and its source handle is not preserved** + (`a = new /* c */ src;` fails verification, exit 2, input untouched). This + is not new behavior for this shape: `~ /* c */ x`, `foo /* c */ [3]` and + `foo /* c */ .bar` all do the same today. `ExprKind::New` deliberately does + not grow a comment slot none of its siblings has. + +## Handshakes + +**Consumed from `vlog_parser::lexer` (unchanged contracts):** `Token::line`, +`Token::text`, `Token::is_macro()`. `macro_end_line` newly depends on the +lexer's guarantee that a macro invocation's `text` is the raw source bytes, +newlines included (`scan_macro_args`) — if that ever changes to a normalized +text, the end-line count changes with it. + +**Changed in `vlog_parser::lexer`:** `lex_based_part` may now return a number +token that ends at the base, with no digits — and only ever when the next +source byte is a backtick. Anything that assumes a `TokenKind::Number` token +carries digits must handle it; `Token::is_base_only_number()` is the predicate +to test with. + +**New in `vlog_parser::token`:** `Token::is_base_only_number()`. + +**New AST variant `ExprKind::New(Box)`** — a §8.12 shallow copy. The +payload is the source handle, an ordinary postfix expression. + +**Exhaustive-match arms added elsewhere for that variant** (minimal, nothing +beyond what the variant needs): + +- `crates/vlog_formatter/src/format.rs` — prints `new ` then the payload. +- `crates/vlog_semantic/src/bind.rs` — `bind_expr` on the payload; the source + handle names a real variable. +- `crates/vlog_parser/tests/spans.rs` — `check_expr` on the payload. +- `crates/vlog_linter/src/visit.rs` needed **no** arm (it ends in a catch-all). + +**Not touched:** `crates/vlog_formatter/src/verify.rs`. Confirmed by reading +`lex_stream`/`normalize`: `normalize` passes a `TokenKind::Number` through +verbatim, and both sides of every construct here lex to the same stream, so no +normalization was added or widened. The two attack tests this feature adds pin +the one rewrite it could plausibly have wanted (a space between the base and +the macro, and gluing `new` to its handle) as *rejected*. + +**Requests to other features:** none. + +## Status / TODO + +- [x] Baseline `scripts/score.sh` captured before any change (796/820). +- [x] Shape 1 — line-aware `Parser::at_macro_item` for every token kind, with + `Parser::macro_end_line` for multi-line invocations. +- [x] Shape 2 — `Parser::at_shallow_copy` + `ExprKind::New`. +- [x] Shape 3 — `lex_based_part` stops at the base before a backtick; + `Token::is_base_only_number`; the parser rejoins the pair. +- [x] Shape 4 — investigated, confirmed unfixable without preprocessing, not + implemented. +- [x] Cases: 5 in `tests/cases/macros.cases` (shape 1, where the macro-item + cases live), 4 in `tests/cases/classes.cases` (shape 2, where the class + cases live), 3 in `tests/cases/expressions_2.cases` (shape 3, where the + literal/expression cases live). Negative and edge cases included: the + same-line spellings that must keep their old parse, a format fence, a + comment between the macro and the next statement, and the line-length + boundary. +- [x] Lexer unit tests (3, two of them negative), parser unit tests (5, two of + them negative). +- [x] Safety-net attack tests (2). +- [x] `cargo fmt --all`, `cargo clippy --all-targets`, `cargo test --workspace` + all clean. +- [x] Score re-run; passing set verified as a strict superset of the baseline. +- [x] `README.md` roadmap and `TODO.md` updated. + +## Work log + +### 2026-08-21 — dev + +**Baseline** (`cargo build --release && scripts/score.sh corpus/`): + +``` +{"passing":796,"total":820,"pct":97.1,"failures_by_category":{"directive-split":14,"invalid-or-fragment":3,"lex-macro-number":2,"macro-items":2,"other":2,"not-verilog":1}} +``` + +**After**: + +``` +{"passing":800,"total":820,"pct":97.6,"failures_by_category":{"directive-split":14,"invalid-or-fragment":3,"macro-items":1,"not-verilog":1,"other":1}} +``` + +**+4 files, 0 lost.** Verified as a set operation, not a count: `comm -23` on +the sorted `pass` columns of the before/after `.score-results.tsv` is empty. +The `lex-macro-number` bucket is gone. Scored after each shape landed +(797 → 798 → 800) so any regression would have been attributable. + +Gained: `dv_base_vseq.sv` (shape 1), `riscv_instr.sv` (shape 2), +`core_ibex_tb_top.sv` and `core_ibex_base_test.sv` (shape 3). + +**Decisions.** + +*Shape 1, hoisted rather than patched.* The line test now runs before the +`match` on the next token's kind instead of inside the `Ident` arm. That is +behavior-preserving for every arm but `Symbol` (a keyword, a macro, a +directive and EOF all already answered "the macro stands alone"), and it says +the rule once instead of twice. The `Symbol` arm keeps its old answer for +tokens on the macro's *own* line, which is what protects `` `TYPE [3:0] x; ``, +`` `MACRO(x) = y; `` and `` `MOD #(...) u(); ``. + +*Shape 1, end line not start line.* `at_macro_item` compared the next token's +line against `self.cur().line`, which for a macro whose argument list spans +lines is where the invocation *started*. With the rule now firing on symbols +too, that would have broken `` `PACKED(a, `` ⏎ `` b) [3:0] vec; ``, so +`macro_end_line` counts the newlines inside the token's text. The existing +`Ident` arm is unaffected either way (a multi-line invocation has arguments, so +`has_macro_args()` had already decided it). + +*Shape 2, parser not lexer, and `new` still not a keyword.* Promoting `new` +would have forced a keyword arm in every position it can appear +(`x = new;`, `super.new()`, `function new;`) for no gain; the whole shape is +one two-token test in `parse_primary`. The payload is parsed with +`parse_postfix`, not `parse_expr`, so `new` binds tighter than any operator — +which is both what §8.12 means and what keeps `new a + b` from swallowing the +addition. + +*Shape 3, split in the lexer, joined in the parser.* The alternative was to +have the lexer glue `` 32'h`DM_ADDR `` into one `Number` token. That needs no +parser change at all, but it makes the lexer answer "how far does the macro +invocation reach" a second time, in a second place, and it hides a macro usage +from anything that walks the token stream (the LSP's `` `define``-expansion +hover reads macro tokens). Splitting keeps both jobs where they already live. +The formatter prints the joined text, which is the only spelling that re-lexes +to the same pair — proven from the other side by the new attack test. + +*Shape 3, no `verify.rs` change, checked rather than assumed.* Read +`lex_stream` and `normalize` first: `normalize` returns a `Number`'s text +verbatim, and both sides lex to `Number("32'h")` + `Ident("`DM_ADDR")`. Better +than neutral, in fact — if the formatter ever put a space there, the *output* +would fail to lex and the net would refuse it, which is what +`spacing_out_a_macro_digit_number_is_rejected` pins. + +**Files changed.** + +- `crates/vlog_parser/src/lexer.rs` — `lex_based_part` stops at a base + followed by a backtick, + 3 tests. +- `crates/vlog_parser/src/token.rs` — `Token::is_base_only_number`. +- `crates/vlog_parser/src/parser.rs` — line-aware `at_macro_item`, + `macro_end_line`, `at_shallow_copy`, the two new `parse_primary` branches, + + 5 tests. +- `crates/vlog_parser/src/ast.rs` — `ExprKind::New(Box)`. +- `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` — 5 cases. +- `crates/vlog_formatter/tests/cases/classes.cases` — 4 cases. +- `crates/vlog_formatter/tests/cases/expressions_2.cases` — 3 cases. +- `README.md`, `TODO.md` — documentation. + +**Still failing, and why.** + +| file | category | reason | +|---|---|---| +| `corpus/ibex/dv/formal/check/peek/compare_helper.sv` | macro-items | `` `X_EACH_CSR 1 `` — needs the macro body, which lives in another file vfmt does not read. See Assumptions. Not mine to fix and not fixable. | +| `corpus/picorv32/scripts/smtbmc/mulcmp.v` | other | Not in this cluster's scope (deliberately unsupported). | + +**Gates.** `cargo fmt --all` clean; `cargo clippy --all-targets` clean (no new +`#[allow]`); `cargo test --workspace` green, 0 failed. No +`unwrap`/`expect`/`panic!` added outside tests. No `unsafe`. No new dependency. + +## QA log + +## Review