diff --git a/README.md b/README.md index 24d9f20..2f15392 100644 --- a/README.md +++ b/README.md @@ -363,7 +363,9 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset: `docs/features/classes/README.md` - Concurrent assertions (IEEE 1800 §16): `assert`/`assume`/`cover`/`restrict property ( ... )` with an optional `label:` prefix and an action block - (`else $error(...)`, `$info(...); else ...`, `else begin ... end`), wherever + (`else $error(...)`, `$info(...); else ...`, `else begin ... end`, and any + statement that nests blocks: `if (c) begin ... end else ...`, + `fork ... join_none`, `case ... endcase`), wherever a module item or a statement can appear — module and package bodies, generate regions, `begin`/`end`, and at file scope. Plus `sequence ... endsequence` and `property ... endproperty` declarations. All of it is diff --git a/TODO.md b/TODO.md index d7a8073..fd04197 100644 --- a/TODO.md +++ b/TODO.md @@ -111,6 +111,11 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both. instead of printing all comments then all attributes. Sweep 14 → 0; the exhaustive per-line sweep's survivors are the shapes parked above plus a comment before `else` — see `docs/features/comments-round-2/README.md`. + → QA round-1 follow-up closed three more shapes with no node of their + own: between `bind` and its target (and before the bound module name), + before a call's `(` / inside an empty `()`, and on either side of a + postfix `with`. Still parked: a comment before a procedural statement's + `;`, and one inside a `bind`'s `: instance, list`. - [x] **Two leading comments separated by one blank line come out separated by two** (format-fences QA find, pre-existing): `leading` pushes a HardLine after each comment and a BlankLine before the next. diff --git a/crates/vlog_formatter/src/format.rs b/crates/vlog_formatter/src/format.rs index 17fd603..1fced29 100644 --- a/crates/vlog_formatter/src/format.rs +++ b/crates/vlog_formatter/src/format.rs @@ -253,6 +253,18 @@ impl<'a> Fmt<'a> { Doc::Inline(raw.text.clone()) } + /// ` with ` — the head both postfix `with` forms share, with the + /// comments written on either side of the keyword printed back where they + /// were written. Anywhere else they would move across `with` and the + /// safety net would reject the output. + fn with_head(&self, base: &Expr, comments: &WithComments) -> Doc { + let mut docs = vec![self.expr(base)]; + self.inline_comments_spaced(&comments.before_kw, &mut docs); + docs.push(text("with")); + self.inline_comments_spaced(&comments.after_kw, &mut docs); + concat(docs) + } + /// A macro invocation standing as an item or a statement. The invocation /// itself is verbatim source — we do not expand macros, so re-spacing the /// argument list would be guesswork — and the trailing `;` is reproduced @@ -1640,11 +1652,18 @@ impl<'a> Fmt<'a> { /// instantiation written on its own would be. fn bind(&self, b: &BindDirective, depth: usize) -> Doc { let head = if b.instances.is_empty() { - format!("bind {} ", b.target) + b.target.clone() } else { - format!("bind {} : {} ", b.target, join_names(&b.instances)) + format!("{} : {}", b.target, join_names(&b.instances)) }; - concat(vec![text(head), self.instantiation(&b.inst, depth)]) + // The comments around the head have no node of their own; each prints + // back between the two tokens it was written between. + let mut docs = vec![text("bind")]; + self.inline_comments_spaced(&b.target_comments, &mut docs); + docs.push(text(head)); + self.inline_comments_spaced(&b.module_comments, &mut docs); + docs.push(self.instantiation(&b.inst, depth)); + concat(docs) } fn instantiation(&self, inst: &Instantiation, depth: usize) -> Doc { @@ -2781,8 +2800,22 @@ impl<'a> Fmt<'a> { } self.ternary_with_comments(cond, then, els, comments) } - ExprKind::Call { callee, args } => { - concat(vec![self.expr(callee), self.expr_list("(", args, ")")]) + ExprKind::Call { callee, args, comments } => { + if comments.is_empty() { + return concat(vec![self.expr(callee), self.expr_list("(", args, ")")]); + } + // A comment written around the brackets prints back between + // the same two tokens it was written between: after the + // callee, and inside the empty `()` that had nowhere else to + // put it. + let mut docs = vec![self.expr(callee)]; + if !comments.before_open.is_empty() { + self.inline_comments_spaced(&comments.before_open, &mut docs); + } + let items: Vec = + args.iter().map(|i| ListItem::from_meta(&i.meta, self.expr(&i.expr))).collect(); + docs.push(self.delimited_dangling("(", items, &comments.dangling, ")", false)); + concat(docs) } // `new src` — one space, never a break: the source handle is a // postfix expression that breaks internally if it must. @@ -2873,11 +2906,11 @@ impl<'a> Fmt<'a> { text("}"), ]), ExprKind::Postfix { expr, op } => concat(vec![self.expr(expr), text(op.clone())]), - ExprKind::With { base, arg } => { - concat(vec![self.expr(base), text(" with "), self.expr(arg)]) + ExprKind::With { base, arg, comments } => { + concat(vec![self.with_head(base, comments), self.expr(arg)]) } - ExprKind::WithConstraint { base, block } => { - concat(vec![self.expr(base), text(" with "), self.with_block(block)]) + ExprKind::WithConstraint { base, block, comments } => { + concat(vec![self.with_head(base, comments), self.with_block(block)]) } ExprKind::Inside { lhs, ranges } => { concat(vec![self.expr(lhs), text(" inside "), self.expr_list("{", ranges, "}")]) diff --git a/crates/vlog_formatter/src/printer.rs b/crates/vlog_formatter/src/printer.rs index 570600f..5c0ec52 100644 --- a/crates/vlog_formatter/src/printer.rs +++ b/crates/vlog_formatter/src/printer.rs @@ -134,12 +134,23 @@ impl Printer { let Some((mode, d)) = stack.pop() else { return true }; match d { Doc::Text(s) => width -= s.chars().count() as isize, - Doc::Inline(s) => match s.split_once('\n') { - // Only the first line shares the current line; if it - // fits, the rest of the group starts after a break. - Some((head, _)) => return width - head.chars().count() as isize >= 0, - None => width -= s.chars().count() as isize, - }, + Doc::Inline(s) => { + // Only the first line shares the current line, and it has + // to fit on it. What follows the text keeps writing on + // the line its *last* line ends on (that is what `print` + // does), so measuring continues from there rather than + // stopping here — otherwise a group whose tail overflows + // would be judged to fit. + if let Some((head, _)) = s.split_once('\n') { + if width < head.chars().count() as isize { + return false; + } + let last = s.rsplit_once('\n').map_or(0, |(_, l)| l.chars().count()); + width = self.max_width as isize - last as isize; + } else { + width -= s.chars().count() as isize; + } + } Doc::Concat(items) | Doc::Indent(items) => { for it in items.iter().rev() { stack.push((mode, it)); @@ -217,6 +228,32 @@ mod tests { assert_eq!(p(8, d), "foo(\n barbarbar\n)"); } + /// A multi-line `Inline` does not end the line: whatever follows it keeps + /// writing on the line its last line ends on, so the group's fit check has + /// to keep measuring past it — from that line's width, not from the + /// indent. QA round-1 finding. + fn inline_group(tail: &str) -> Doc { + group(vec![ + text("if ("), + Doc::Inline("with {\n x == 1;\n} ".into()), + indent(vec![Doc::SoftLine, text(tail)]), + text(")"), + ]) + } + + #[test] + fn group_stays_flat_when_the_tail_after_an_inline_fits() { + assert_eq!(p(20, inline_group("&& ok")), "if (with {\n x == 1;\n} && ok)"); + } + + #[test] + fn group_breaks_when_the_tail_after_an_inline_overflows() { + assert_eq!( + p(20, inline_group("&& far_too_long_to_fit")), + "if (with {\n x == 1;\n}\n && far_too_long_to_fit)" + ); + } + #[test] fn hard_line_forces_break() { let d = group(vec![text("a"), Doc::HardLine, text("b")]); diff --git a/crates/vlog_formatter/tests/cases/assertions.cases b/crates/vlog_formatter/tests/cases/assertions.cases index 6b78259..f0b1896 100644 --- a/crates/vlog_formatter/tests/cases/assertions.cases +++ b/crates/vlog_formatter/tests/cases/assertions.cases @@ -265,3 +265,52 @@ module m; assert property (@(posedge clk_i) disable iff (!rst_ni) some_very_long_signal_name_here |-> ##[1:3] another_quite_long_signal_name); endmodule ==== +# an action block whose pass statement is an `if` with a `begin ... end` +# body: the block -- and the `else` after it -- belong to the assertion, +# and the item after it survives +module m; + always @(posedge clk) + assert property (@(posedge clk) a |-> b) + if (cond) begin + x = 1; + end + else y = 2; + wire w; +endmodule +---- +module m; + always @(posedge clk) + assert property (@(posedge clk) a |-> b) + if (cond) begin + x = 1; + end + else y = 2; + wire w; +endmodule +==== +# an action block that is a `fork ... join_none`, `disable fork` inside it +# (which names the enclosing block rather than opening one) +module m; + always @(posedge clk) + assert property (a |-> b) + fork + begin + disable fork; + end + join_none + else $error("no"); + wire w; +endmodule +---- +module m; + always @(posedge clk) + assert property (a |-> b) + fork + begin + disable fork; + end + join_none + else $error("no"); + wire w; +endmodule +==== diff --git a/crates/vlog_formatter/tests/cases/bind.cases b/crates/vlog_formatter/tests/cases/bind.cases index 19b8750..56fb123 100644 --- a/crates/vlog_formatter/tests/cases/bind.cases +++ b/crates/vlog_formatter/tests/cases/bind.cases @@ -293,3 +293,27 @@ module m; end endmodule ==== +# comments written where the directive has no node to hang them on: between +# `bind` and the target, and between the target (or the instance list) and +# the module name +module m; + bind /*c1*/ dut /*c2*/ checker_mod c_inst (.clk(clk)); + bind dut : u_a, u_b /*c3*/ checker_mod c2_inst (.clk(clk)); +endmodule +---- +module m; + bind /*c1*/ dut /*c2*/ checker_mod c_inst (.clk(clk)); + bind dut : u_a, u_b /*c3*/ checker_mod c2_inst (.clk(clk)); +endmodule +==== +# a *line* comment after `bind` ends its line, so the target starts the next +module m; + bind // the target is the design under test + dut checker_mod c_inst (.clk(clk)); +endmodule +---- +module m; + bind // the target is the design under test + dut checker_mod c_inst (.clk(clk)); +endmodule +==== diff --git a/crates/vlog_formatter/tests/cases/dv_statements.cases b/crates/vlog_formatter/tests/cases/dv_statements.cases index 3a3cde1..2ac67ec 100644 --- a/crates/vlog_formatter/tests/cases/dv_statements.cases +++ b/crates/vlog_formatter/tests/cases/dv_statements.cases @@ -576,3 +576,66 @@ module m; initial x = 1; endmodule ==== +#a with-block condition whose tail still fits stays on the block's last line +class c; + task t; + if (req.randomize() with { + addr == 32'h1000; + } && cfg.enable_the_long_named_feature_flag && other_condition_name_goes_right_here) begin + z = 1; + end + endtask +endclass +---- +class c; + task t; + if (req.randomize() with { + addr == 32'h1000; + } && cfg.enable_the_long_named_feature_flag && other_condition_name_goes_right_here) begin + z = 1; + end + endtask +endclass +==== +#a with-block condition whose tail overflows wraps (printer fits() past a multi-line Inline) +class c; + task t; + if (req.randomize() with { + addr == 32'h1000; + } && cfg.enable_the_long_named_feature_flag && other_condition_name_goes_right_here_ok) begin + z = 1; + end + endtask +endclass +---- +class c; + task t; + if ( + req.randomize() with { + addr == 32'h1000; + } && cfg.enable_the_long_named_feature_flag && other_condition_name_goes_right_here_ok + ) begin + z = 1; + end + endtask +endclass +==== +# comments at every boundary of a `randomize() with { ... }` and of an +# array-method `with (expr)`: before the `(`, inside the empty `()`, before +# `with`, and between `with` and the block +class c; + task t; + y = x.randomize /*c1*/ ( /*c2*/ ) /*c3*/ with /*c4*/ {a == 1;}; + z = q.sum() /*c5*/ with /*c6*/ (item.w); + endtask +endclass +---- +class c; + task t; + y = x.randomize /*c1*/ ( + /*c2*/ + ) /*c3*/ with /*c4*/ {a == 1;}; + z = q.sum() /*c5*/ with /*c6*/ (item.w); + endtask +endclass +==== diff --git a/crates/vlog_parser/src/ast.rs b/crates/vlog_parser/src/ast.rs index cb1f76e..7f7eb01 100644 --- a/crates/vlog_parser/src/ast.rs +++ b/crates/vlog_parser/src/ast.rs @@ -771,9 +771,16 @@ pub struct BindDirective { /// the source may have written around the dots — the same caveat /// [`Instantiation::module_span`] carries for `::`. pub target_span: TextRange, + /// Comments written between `bind` and the target name. They have no node + /// of their own to hang on — the target is a bare string — so they are + /// kept here and printed back between the same two tokens. + pub target_comments: Vec, /// The `: u_a, u_b` instance list that narrows a module target to /// particular instances. Empty when the source wrote no `:`. pub instances: Vec, + /// Comments written between the target (or the instance list) and the + /// module name of the instantiation, for the same reason. + pub module_comments: Vec, /// The instantiation being bound, identical in shape to a standalone one. pub inst: Instantiation, } @@ -1343,6 +1350,10 @@ pub enum ExprKind { Call { callee: Box, args: Vec, + /// Boxed to keep `Expr` small, as for `TernaryComments`: a call with + /// comments written around its brackets is rare, and there is one + /// `Call` in every other line of real code. + comments: Box, }, /// 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 @@ -1441,6 +1452,8 @@ pub enum ExprKind { With { base: Box, arg: Box, + /// Boxed to keep `Expr` small, as for `TernaryComments`. + comments: Box, }, /// `expr with { ... }` — the inline constraint block of a `randomize` /// call (IEEE 1800 §18.7). The block is a `constraint` body written in an @@ -1449,6 +1462,8 @@ pub enum ExprKind { WithConstraint { base: Box, block: RawText, + /// Boxed to keep `Expr` small, as for `TernaryComments`. + comments: Box, }, /// A named call argument: the `.ptr(ral.ovrd)` of /// `csr_wr(.ptr(ral.ovrd), .value(x))`. `value` is [`ExprKind::Empty`] @@ -1506,6 +1521,36 @@ pub struct TernaryComments { pub after_colon: Vec, } +/// Comments written where a call's argument list has no element to carry +/// them: before the `(`, and inside an empty `()`. Both are kept so the +/// formatter can print them back between the same two tokens — dropped or +/// moved, the safety net rejects the output. +#[derive(Debug, Clone, Default)] +pub struct CallComments { + /// Between the callee and the `(` (`x.randomize /*c*/ ()`). + pub before_open: Vec, + /// Inside an empty argument list (`x.randomize(/*c*/)`). A list with + /// elements carries its own comments on them, so this is empty there. + pub dangling: Vec, +} + +impl CallComments { + /// True when nothing was written around the brackets — the common case. + pub fn is_empty(&self) -> bool { + self.before_open.is_empty() && self.dangling.is_empty() + } +} + +/// Comments written around the `with` of a postfix `with (expr)` or +/// `with { ... }`, kept per position for the reason [`TernaryComments`] gives. +#[derive(Debug, Clone, Default)] +pub struct WithComments { + /// Between the base expression and `with`. + pub before_kw: Vec, + /// Between `with` and the `(` or `{` that follows it. + pub after_kw: Vec, +} + impl TernaryComments { /// True when nothing was written inside the `? :` — the common case, laid /// out without any comment handling. diff --git a/crates/vlog_parser/src/parser.rs b/crates/vlog_parser/src/parser.rs index eddf91a..e28416c 100644 --- a/crates/vlog_parser/src/parser.rs +++ b/crates/vlog_parser/src/parser.rs @@ -138,6 +138,16 @@ const MEMBER_QUALIFIERS: &[&str] = &[ "var", ]; +/// Keywords that open a statement block [`Parser::skip_action_stmt`] skips as +/// one unit. `fork` counts only where it opens a block: `disable fork` and +/// `wait fork` name the enclosing one. +const BLOCK_OPENERS: &[&str] = &["begin", "fork", "case", "casex", "casez", "randcase"]; + +/// Keywords that close one of [`BLOCK_OPENERS`]. Which opener a closer belongs +/// to is not checked — the scan only counts — so unbalanced input runs to the +/// end of the file and reports a clean error there. +const BLOCK_CLOSERS: &[&str] = &["end", "join", "join_any", "join_none", "endcase"]; + const ASSIGN_OPS: &[&str] = &["=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", "<<<=", ">>>="]; @@ -1590,10 +1600,10 @@ impl<'a> Parser<'a> { /// second grammar (`dist`, `soft`, constraint `if`, `->`) that /// [`Parser::parse_constraint`] declines to model — so it gets exactly /// the same treatment: skip to the matching brace and copy the bytes out. - /// The `with` keyword itself is left outside the capture; the formatter - /// writes it back. + /// The `with` keyword itself is left outside the capture — the caller has + /// already consumed it, together with the comments written on either side + /// of it — and the formatter writes it back. fn parse_with_constraint(&mut self) -> PResult { - self.expect_kw("with")?; let start = self.here(); let col = self.cur().col; self.expect_sym("{")?; @@ -1677,27 +1687,22 @@ impl<'a> Parser<'a> { } /// One `statement_or_null` of an action block, skipped verbatim: a - /// `begin ... end` block, or everything through the next `;`. Brackets are - /// skipped as units so a `;` written inside one cannot end the scan early. + /// `begin ... end` block, or everything through the next `;`. + /// + /// Brackets *and* the block keywords ([`BLOCK_OPENERS`] / + /// [`BLOCK_CLOSERS`]) are skipped as units, so neither a `;` nor an `end` + /// written inside one ends the scan early: the pass statement of + /// `assert property (p) if (c) begin x = 1; end else y = 2;` is the whole + /// `if`, not `if (c) begin x = 1;`. A statement that ends with a block + /// ends *there* — no `;` follows one — unless an `else` continues it. + /// + /// The scan never runs past the end of the file and never stands still: + /// every arm consumes at least one token, and `at_eof` is checked on every + /// turn, so unbalanced input is a clean parse error. fn skip_action_stmt(&mut self) -> PResult<()> { - if self.cur().is_kw("begin") { - self.bump(); - let mut depth = 1usize; - while depth > 0 { - if self.at_eof() { - return self.error("expected `end`"); - } - let t = self.cur(); - if t.is_kw("begin") { - depth += 1; - } else if t.is_kw("end") { - depth -= 1; - } - self.bump(); - } - self.parse_label()?; - return Ok(()); - } + // How many block keywords are open. Zero means the scan is looking for + // the statement's own terminator. + let mut depth = 0usize; loop { if self.at_eof() { return self.error("expected `;`"); @@ -1712,7 +1717,30 @@ impl<'a> Parser<'a> { } else if t.is_sym("{") { self.bump(); self.skip_balanced("{", "}")?; - } else if self.eat_sym(";") { + } else if (t.is_kw("disable") || t.is_kw("wait")) && self.nth(1).is_kw("fork") { + // `disable fork` / `wait fork` name the enclosing block; they + // do not open one. + self.bump(); + self.bump(); + } else if BLOCK_OPENERS.iter().any(|k| t.is_kw(k)) { + depth += 1; + self.bump(); + } else if BLOCK_CLOSERS.iter().any(|k| t.is_kw(k)) { + if depth == 0 { + // A closer with nothing open: the action statement is + // missing its terminator and the scan has reached the end + // of the block the assertion itself sits in. + return self.error("expected `;`"); + } + depth -= 1; + self.bump(); + if depth == 0 { + self.parse_label()?; + if !self.eat_kw("else") { + return Ok(()); + } + } + } else if depth == 0 && self.eat_sym(";") { return Ok(()); } else { self.bump(); @@ -2643,6 +2671,10 @@ impl<'a> Parser<'a> { /// `bind [: , ...] [#(...)] (...);` fn parse_bind(&mut self) -> PResult { self.bump(); // `bind` + // The target is a bare string, so a comment written before it has no + // node to attach to: harvest it here, where source order is still + // known, rather than letting it drift onto the instance below. + let target_comments = self.take_dangling(); let start = self.here(); let mut target = self.expect_ident()?; while self.cur().is_sym(".") { @@ -2660,8 +2692,9 @@ impl<'a> Parser<'a> { } } } + let module_comments = self.take_dangling(); let inst = self.parse_instantiation()?; - Ok(BindDirective { target, target_span, instances, inst }) + Ok(BindDirective { target, target_comments, target_span, instances, module_comments, inst }) } fn parse_instantiation(&mut self) -> PResult { @@ -4180,6 +4213,12 @@ impl<'a> Parser<'a> { ); } } else if t.is_sym("(") { + // Comments written around the brackets have no element to + // attach to: before the `(`, and inside an empty `()`. + let mut comments = CallComments { + before_open: self.take_before_open("("), + ..CallComments::default() + }; self.bump(); let mut args = Vec::new(); if !self.cur().is_sym(")") { @@ -4200,22 +4239,42 @@ impl<'a> Parser<'a> { let first = ExprItem { meta, expr: first_expr, span: self.span_from(arg_start) }; args = self.parse_expr_list(first, ")")?; + } else { + comments.dangling = self.take_dangling(); } self.expect_sym(")")?; - expr = self.expr_at(start, ExprKind::Call { callee: Box::new(expr), args }); + expr = self.expr_at( + start, + ExprKind::Call { callee: Box::new(expr), args, comments: Box::new(comments) }, + ); } else if t.is_kw("with") { + let mut comments = + WithComments { before_kw: self.take_dangling(), ..WithComments::default() }; if self.nth(1).is_sym("{") { + self.expect_kw("with")?; + comments.after_kw = self.take_before_open("{"); let block = self.parse_with_constraint()?; - expr = self - .expr_at(start, ExprKind::WithConstraint { base: Box::new(expr), block }); + expr = self.expr_at( + start, + ExprKind::WithConstraint { + base: Box::new(expr), + block, + comments: Box::new(comments), + }, + ); } else { self.bump(); // with - // `( expression )` — an ordinary parenthesized primary, - // which is what IEEE 1800 §7.12 spells here. + comments.after_kw = self.take_before_open("("); + // `( expression )` — an ordinary parenthesized primary, + // which is what IEEE 1800 §7.12 spells here. let arg = self.parse_primary()?; expr = self.expr_at( start, - ExprKind::With { base: Box::new(expr), arg: Box::new(arg) }, + ExprKind::With { + base: Box::new(expr), + arg: Box::new(arg), + comments: Box::new(comments), + }, ); } } else if t.is_sym("'") && self.nth(1).is_sym("(") { @@ -4530,6 +4589,12 @@ mod tests { } } + /// The texts of a comment slot, for the tests that pin where a comment + /// with no node of its own was attached. + fn texts(comments: &[Comment]) -> Vec<&str> { + comments.iter().map(|c| c.text.as_str()).collect() + } + /// The message of the parse error `src` must produce. fn parse_err(src: &str) -> String { let toks = tokenize(src).expect("lex error"); @@ -4793,6 +4858,18 @@ mod tests { assert_eq!(b.inst.instances[0].name, "u"); } + #[test] + fn the_comments_around_a_binds_head_are_kept() { + // QA round-1: the target is a bare string, so these two positions had + // no node to attach to and the comments drifted onto the instance. + let file = parse_ok("module m;\n bind /*c1*/ dut /*c2*/ chk u (.*);\nendmodule\n"); + let ItemKind::Bind(b) = &module_of(&file).items[0].kind else { + panic!("expected a bind directive") + }; + assert_eq!(texts(&b.target_comments), ["/*c1*/"]); + assert_eq!(texts(&b.module_comments), ["/*c2*/"]); + } + #[test] fn bind_is_still_a_usable_identifier() { // `bind` is not in the lexer's keyword table, so a method called @@ -5844,6 +5921,56 @@ mod tests { assert!(matches!(items[1].kind, ItemKind::DataDecl(_)), "the next item was swallowed"); } + #[test] + fn an_action_block_keeps_a_nested_begin_end_whole() { + // QA round-1: the scan used to stop at the first `;` inside the + // nested block, leaving its `end` (and the `else`) behind. + let src = "module m;\n assert property (a |-> b)\n if (c) begin\n x = 1;\n end\n else y = 2;\n wire w;\nendmodule\n"; + let f = parse_ok(src); + let items = &module_of(&f).items; + let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") }; + assert_eq!( + raw.text, + "assert property (a |-> b)\n if (c) begin\n x = 1;\n end\n else y = 2;" + ); + assert!(matches!(items[1].kind, ItemKind::DataDecl(_)), "the next item was swallowed"); + } + + #[test] + fn an_action_block_may_be_a_fork_or_a_case() { + // `disable fork` / `wait fork` name the enclosing block rather than + // opening one, so neither may push the scan's block depth. + let fork = "fork\n x = 1;\n begin\n disable fork;\n wait fork;\n end\n join_none"; + let case = "case (s)\n 1: x = 1;\n default: begin\n y = 2;\n end\n endcase"; + for body in [fork, case] { + let src = + format!("module m;\n assert property (a)\n {body}\n wire w;\nendmodule\n"); + let f = parse_ok(&src); + let items = &module_of(&f).items; + let ItemKind::Verbatim(raw) = &items[0].kind else { + panic!("expected a verbatim block for {body}") + }; + assert_eq!(raw.text, format!("assert property (a)\n {body}")); + assert!(matches!(items[1].kind, ItemKind::DataDecl(_)), "the next item was swallowed"); + } + } + + #[test] + fn an_unbalanced_action_block_is_a_clean_error() { + // Never past the end of the file, never a loop. + assert_eq!( + parse_err( + "module m;\n assert property (a)\n if (c) begin\n x = 1;\nendmodule\n" + ), + "expected `;` (found \"\")" + ); + // A closer with nothing open ends the scan where it stands. + assert_eq!( + parse_err("module m;\n initial begin\n assert property (a)\n end\nendmodule\n"), + "expected `;` (found \"end\")" + ); + } + #[test] fn both_halves_of_an_action_block_are_captured() { let f = parse_ok( @@ -6510,7 +6637,7 @@ mod tests { let StmtKind::Assign { rhs, .. } = &initial_stmts(&f)[0].kind else { panic!("expected an assignment") }; - let ExprKind::WithConstraint { base, block } = &rhs.kind else { + let ExprKind::WithConstraint { base, block, .. } = &rhs.kind else { panic!("expected a with-constraint, got {:?}", rhs.kind) }; // The `with` keyword is outside the capture; the braces are inside. @@ -6526,13 +6653,46 @@ mod tests { let StmtKind::Assign { rhs, .. } = &initial_stmts(&f)[0].kind else { panic!("expected an assignment") }; - let ExprKind::With { base, arg } = &rhs.kind else { + let ExprKind::With { base, arg, .. } = &rhs.kind else { panic!("expected a with-expression, got {:?}", rhs.kind) }; assert!(matches!(base.kind, ExprKind::Call { .. })); assert!(matches!(arg.kind, ExprKind::Paren { .. })); } + #[test] + fn the_comments_around_a_calls_brackets_and_a_with_are_kept() { + // QA round-1: four positions with no node of their own — before the + // `(`, inside an empty `()`, before `with`, and after it. + let f = parse_ok( + "module m;\n initial begin\n x = o.randomize /*c1*/ ( /*c2*/ ) /*c3*/ with /*c4*/ {\n y > 1;\n };\n end\nendmodule\n", + ); + let StmtKind::Assign { rhs, .. } = &initial_stmts(&f)[0].kind else { + panic!("expected an assignment") + }; + let ExprKind::WithConstraint { base, comments, .. } = &rhs.kind else { + panic!("expected a with-constraint, got {:?}", rhs.kind) + }; + assert_eq!(texts(&comments.before_kw), ["/*c3*/"]); + assert_eq!(texts(&comments.after_kw), ["/*c4*/"]); + let ExprKind::Call { comments, .. } = &base.kind else { panic!("expected a call") }; + assert_eq!(texts(&comments.before_open), ["/*c1*/"]); + assert_eq!(texts(&comments.dangling), ["/*c2*/"]); + } + + #[test] + fn an_argument_carries_its_own_comments_and_the_call_carries_none() { + // A list with elements has somewhere to put them, so the call's own + // slots stay empty — two homes for one comment would print it twice. + let f = parse_ok("module m;\n initial begin\n f( /*c*/ a);\n end\nendmodule\n"); + let StmtKind::ExprStmt(e) = &initial_stmts(&f)[0].kind else { + panic!("expected an expression statement, got {:?}", initial_stmts(&f)[0].kind) + }; + let ExprKind::Call { args, comments, .. } = &e.kind else { panic!("expected a call") }; + assert!(comments.is_empty(), "the call kept comments the argument owns"); + assert_eq!(texts(&args[0].meta.leading), ["/*c*/"]); + } + #[test] fn a_with_that_opens_neither_a_paren_nor_a_brace_is_not_a_postfix_segment() { // The stream expression's `with [range]` is still unsupported, and diff --git a/crates/vlog_parser/tests/spans.rs b/crates/vlog_parser/tests/spans.rs index 4ab350e..5df1e22 100644 --- a/crates/vlog_parser/tests/spans.rs +++ b/crates/vlog_parser/tests/spans.rs @@ -847,11 +847,11 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) { check_expr(src, expr, here); } ExprKind::InsideMacro { lhs, .. } => check_expr(src, lhs, here), - ExprKind::With { base, arg } => { + ExprKind::With { base, arg, .. } => { check_expr(src, base, here); check_expr(src, arg, here); } - ExprKind::WithConstraint { base, block } => { + ExprKind::WithConstraint { base, block, .. } => { check_expr(src, base, here); assert_inside(src, "with constraint block", block.span, here); } @@ -868,7 +868,7 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) { check_expr(src, then, here); check_expr(src, els, here); } - ExprKind::Call { callee, args } => { + ExprKind::Call { callee, args, .. } => { check_expr(src, callee, here); for a in args { assert_inside(src, "argument", a.span, here); diff --git a/crates/vlog_semantic/src/bind.rs b/crates/vlog_semantic/src/bind.rs index 5497199..0c4905d 100644 --- a/crates/vlog_semantic/src/bind.rs +++ b/crates/vlog_semantic/src/bind.rs @@ -1052,7 +1052,7 @@ impl<'a> Binder<'a> { self.bind_expr(then, scope); self.bind_expr(els, scope); } - ExprKind::Call { callee, args } => { + ExprKind::Call { callee, args, .. } => { self.bind_expr(callee, scope); for a in args { self.bind_expr(&a.expr, scope); @@ -1113,7 +1113,7 @@ impl<'a> Binder<'a> { } // The set is a macro invocation this crate makes no claims about. ExprKind::InsideMacro { lhs, .. } => self.bind_expr(lhs, scope), - ExprKind::With { base, arg } => { + ExprKind::With { base, arg, .. } => { self.bind_expr(base, scope); self.bind_expr(arg, scope); } diff --git a/docs/features/assertions/README.md b/docs/features/assertions/README.md index e5dc375..c54a6d8 100644 --- a/docs/features/assertions/README.md +++ b/docs/features/assertions/README.md @@ -165,6 +165,10 @@ the same two grammar rules and cost nothing: workspace) all clean. - [x] Idempotency swept by hand over all 712 passing corpus files, not just the 13 new ones. +- [x] QA round-1: `skip_action_stmt` tracks `begin`/`end`, `fork`/`join*` and + `case`/`endcase` nesting, so an action block that is an `if` with a + `begin ... end` body (with or without `else`) is captured whole + (3 parser tests + 2 cases). - [ ] **Not done, deliberately:** canonical layout for property/sequence expressions; `expect property`; `cover sequence`; `default clocking` / `default disable iff` (interface cluster's). @@ -278,6 +282,56 @@ Files changed: - `README.md` — "Supported syntax" bullet, roadmap items 7/7b/8 - `docs/features/assertions/README.md` — this file +### 2026-08-21 — dev (response to QA round 1) + +The round-1 finding below — `skip_action_stmt`'s generic branch tracking +brackets but not `begin`/`end`, so an action block like `if (c) begin x = 1; +end else y = 2;` ended at the first `;` *inside* the nested block — is fixed. + +`skip_action_stmt` is now one loop with a block-keyword depth counter beside +the bracket skipping. It counts the openers `BLOCK_OPENERS` (`begin`, `fork`, +`case`/`casex`/`casez`/`randcase`) against the closers `BLOCK_CLOSERS` +(`end`, `join`/`join_any`/`join_none`, `endcase`), and: + +- a `;` ends the statement only at depth 0, so a `;` inside a nested block no + longer ends the scan; +- a statement that *ends* with a block ends there — no `;` follows one — and + the scan then reads the optional `end : label` and continues only if an + `else` follows, which is what makes the `if`/`else` shape whole; +- `disable fork` / `wait fork` are matched as a pair and skipped: they name + the enclosing block rather than opening one, and counting them would have + broken the very common UVM `fork ... join_none` + `disable fork` action + block; +- a closer at depth 0 (nothing open) is a clean `expected ';'` error where it + stands, which is both a better position than the old run-to-EOF and the + reason the counter can never underflow. + +The termination argument the QA log asked about still holds and is now in the +doc comment: `at_eof` is checked on every turn and every arm consumes at +least one token, so unbalanced input is a clean parse error, never a loop and +never a read past the end of the file. Both directions are pinned by +`an_unbalanced_action_block_is_a_clean_error`. + +Tests: three parser tests (`an_action_block_keeps_a_nested_begin_end_whole`, +`an_action_block_may_be_a_fork_or_a_case`, +`an_unbalanced_action_block_is_a_clean_error`) and two cases in +`assertions.cases` (the `if`/`begin`/`end`/`else` shape and a +`fork ... join_none` with `disable fork` inside), each with a following item +asserted to survive so a future over-greedy scan is caught. + +The old special case that required the pass statement's *first* token to be +`begin` is gone — it is now just depth 1 on the first token — so the previous +begin-block behaviour is unchanged, `begin`-first or not. + +Score unchanged before and after +(`{"passing":800,"total":820,"pct":97.6,...}`), passing set identical, all +800 passing files byte-identical against the pre-change binary, two-pass +idempotency sweep clean. + +Files changed: `crates/vlog_parser/src/parser.rs` (`skip_action_stmt`, the +two new consts, 3 tests), `crates/vlog_formatter/tests/cases/assertions.cases` +(2 cases). + ## QA log ### 2026-08-21 — round-1 adversarial QA diff --git a/docs/features/bind/README.md b/docs/features/bind/README.md index 810b656..b9c0887 100644 --- a/docs/features/bind/README.md +++ b/docs/features/bind/README.md @@ -105,6 +105,11 @@ instantiation too (`bind.cases`, "implicit named *parameter* overrides"). ### Promised / requested +- **`BindDirective::target_comments` / `::module_comments`** (QA round-1 fix): + the comments written between `bind` and the target, and between the target + (or the `: instance, list`) and the module name. Both are plain + `Vec` fields, so no consumer had to change; only `Fmt::bind` + reads them. - **New AST variant `ItemKind::Bind(BindDirective)`** in `crates/vlog_parser/src/ast.rs`. Two exhaustive matches in other crates needed an arm; both got the minimal one: @@ -149,6 +154,11 @@ instantiation too (`bind.cases`, "implicit named *parameter* overrides"). - [x] `cargo fmt --all`, `cargo clippy --all-targets`, `cargo test` all clean. - [x] Score after: 699/820 (85.2%), passing set a strict superset. - [x] `TODO.md` and `README.md` updated. +- [x] QA round-1: comments between `bind` and the target, and before the + module name, are preserved (2 cases + 1 parser test). +- [ ] A comment written *inside* the `: instance, list` is still a clean + exit-2 refusal — `instances: Vec` has no `Meta` and no corpus + file writes one. See the 2026-08-21 work log entry. ## Work log @@ -196,6 +206,47 @@ instantiation too (`bind.cases`, "implicit named *parameter* overrides"). from `counter_properties.sv:96`), so nothing in this category is left over; those files belong to the `assertions` owner. +### 2026-08-21 — dev (response to QA round 1) + +The round-1 finding below (a comment between `bind` and its target is dropped +internally and the file becomes unformattable) is fixed, together with its +sibling position (between the target — or the `: instance, list` — and the +module name of the instantiation). + +Both positions sit between two tokens that no node owns: the target is a bare +`String`, so a comment written there had nowhere to attach and drifted onto +the instance below, which moves it across tokens and `verify_equivalence` +rightly refused the output. `BindDirective` now carries `target_comments` and +`module_comments`, harvested in `parse_bind` with the same `take_dangling` +the rest of the parser uses, and `Fmt::bind` prints each back where it was +written (`Fmt::inline_comments_spaced`, so a *line* comment ends its line and +the target starts the next one). Both round-trip and are idempotent; two +cases in `bind.cases` pin them, plus a parser test +(`the_comments_around_a_binds_head_are_kept`). + +The QA note's "same class of gap ... after the module name / before the +instance name" turned out **not** to reproduce: `checker_mod /*c3*/ c_inst +/*c4*/ (.clk(clk));` already round-trips, because those two positions are the +instance's `meta.leading` and `conn_comments`, which `parse_instantiation` +has always harvested. + +**Still refused, deliberately:** a comment written *inside* the `: instance, +list` (`bind dut : /*x*/ u_a chk u (.*);`). `instances: Vec` has no +`Meta`, and giving one to a list nothing else needs — no corpus file writes a +comment there — is the abstraction-for-a-second-user-that-does-not-exist the +project rules forbid. It stays a clean exit-2 refusal with the input +untouched, not corruption. + +Score unchanged before and after +(`{"passing":800,"total":820,"pct":97.6,...}`), passing set identical, and +all 800 passing corpus files format to byte-identical output against the +pre-change binary; the two-pass idempotency sweep over them is clean. + +Files changed: `crates/vlog_parser/src/ast.rs` (two fields on +`BindDirective`), `crates/vlog_parser/src/parser.rs` (`parse_bind` + 1 test), +`crates/vlog_formatter/src/format.rs` (`Fmt::bind`), +`crates/vlog_formatter/tests/cases/bind.cases` (2 cases). + ## QA log ### 2026-08-21 — round-1 adversarial QA diff --git a/docs/features/dv-statements/README.md b/docs/features/dv-statements/README.md index 5d1e2f4..28ace23 100644 --- a/docs/features/dv-statements/README.md +++ b/docs/features/dv-statements/README.md @@ -129,9 +129,21 @@ its input bytes exactly is trivially token-equivalent. - **`Doc::Inline(String)`** (`vlog_formatter::doc`): verbatim text spliced into the *middle* of a line, newlines and all. Unlike `Doc::Verbatim` it does not force enclosing groups to break, and unlike `Doc::Text` the - printer measures it correctly (`fits` charges only its first line, `print` - resumes measuring from its last). `align::flat_width` returns `None` for it, - as it does for the other break-carrying docs. + printer measures it correctly: `fits` charges its first line against the + current width and then goes on measuring the rest of the group from the + width of its *last* line, which is where `print` resumes (QA round-1 fix — + the first version stopped measuring at the first line and let an + overflowing tail through). `align::flat_width` returns `None` for it, as it + does for the other break-carrying docs. + +- **Comment slots on three `ExprKind` variants** (QA round-1 fix): + `Call { comments: Box }` (before the `(`, and inside an empty + `()`), `With`/`WithConstraint { comments: Box }` (before + `with`, and between `with` and the `(` / `{`). Every consumer matched these + variants with named fields; `vlog_semantic::bind` and + `vlog_parser/tests/spans.rs` got a `..` in the pattern and nothing else. + The comments live outside the nodes' code extents, so no span invariant + changes. - **`token::is_keyword` gained `randcase` and `let`** — a lexer-level change shared with the `lexer-cleanup` feature. See Assumptions. @@ -190,6 +202,13 @@ another feature's region, so they are written here rather than made: - [x] 30 formatter cases in `crates/vlog_formatter/tests/cases/dv_statements.cases`, 14 parser unit tests, 1 linter case, 2 new span-invariant sources - [x] `cargo fmt` / `cargo clippy --all-targets` / `cargo test` clean +- [x] QA round-1: `fits()` keeps measuring past a multi-line `Doc::Inline`, + from its last line's width +- [x] QA round-1: comments before a call's `(`, inside an empty `()`, and on + either side of a postfix `with` +- [ ] comment between an expression statement and its `;` — not a `with` + gap (`y = a + 1 /*c*/;` refuses the same way); needs a slot on the + statement, and is the shape TODO.md already parks - [ ] `let` at *statement* position (a block item declaration, §11.12) — no corpus file writes one; it is an "unsupported statement starting with keyword `let`" error @@ -296,6 +315,63 @@ Files changed: - `crates/vlog_linter/tests/cases/case_missing_default.lint` — randcase case - `README.md`, `TODO.md` +### 2026-08-21 — dev (response to QA round 1) + +Two of the round-1 findings in the QA log below were this cluster's; both are +fixed. Score unchanged at `{"passing":800,"total":820,"pct":97.6,...}` before +and after, with the passing set identical (`comm` both ways empty) and — the +stronger check for a printer change — **every one of the 800 files formats to +exactly the same bytes as the pre-change binary** (built from `HEAD` in a +scratch tree and diffed file by file). The 800-file two-pass idempotency +sweep is clean. + +- **`fits()` vs a multi-line `Doc::Inline` (printer.rs).** Confirmed exactly + as reported: `fits` returned on the Inline's first line, so a group whose + tail continued on the block's *last* line was judged to fit however long + that tail was. `fits` now charges the first line, refuses the group if that + line alone overflows, then **resets the remaining width to + `max_width - ` and keeps measuring** the rest of the + group — which is precisely what `print` does when it resumes. The QA repro + now wraps at `--line-length 40`, and the control case (a short tail after + the same block) still comes out flat. Two printer unit tests pin both + directions (`group_stays_flat_when_the_tail_after_an_inline_fits`, + `group_breaks_when_the_tail_after_an_inline_overflows`) and two + `dv_statements.cases` entries pin it end to end at the default 100 columns + (`cases.rs` has no per-case config knob — every case runs on + `Config::default()` — so the cases are built to overflow at 100). +- **`align::flat_width` was checked and deliberately left alone.** It answers + `None` for *any* `Doc::Inline`, which makes the row unalignable; `row_of` + turns that into `None`, and `align_groups` treats a `None` row as a group + boundary whose plan stays `None`, so the row prints flush. That is + conservative but correct in the direction that matters (no row is ever + padded from a width nobody measured). The only pessimism is a *single-line* + Inline, which does have an honest flat width; no corpus file writes one + inside an alignable row, so under "simplicity first" it stays as it is + rather than growing a special case with no user. +- **Comments at the `randomize()`/`with` boundaries.** Four positions had no + node to attach to and so were rejected by the safety net: before a call's + `(`, inside an empty `()`, before `with`, and between `with` and the `(` / + `{`. `ExprKind::Call` gained `comments: Box` and both `with` + forms gained `comments: Box` — boxed for the reason + `TernaryComments` already gives — harvested with the existing + `take_before_open` / `take_dangling` helpers and printed back between the + same two tokens by `Fmt::with_head` and the `Call` arm. An argument list + with elements keeps carrying its own comments (a second home would print + one comment twice); a parser test pins that too. +- **Still refused, deliberately:** a comment between an expression statement + and its `;` (`y = x.randomize() with {a == 1;} /*c*/;`). It is not a + `with`-specific gap at all — `y = a + 1 /*c*/;` refuses identically — and + placing it needs a slot on the *statement*, not on `Expr`. It is the shape + TODO.md already parks as "a comment before a procedural statement's `;`". + +Files changed: `crates/vlog_formatter/src/printer.rs` (the `fits` arm + 2 +tests), `crates/vlog_parser/src/ast.rs` (`CallComments`, `WithComments`, the +three new fields), `crates/vlog_parser/src/parser.rs` (harvest points, +`parse_with_constraint` no longer eats its own `with`, 2 tests), +`crates/vlog_formatter/src/format.rs` (`with_head`, the `Call` arm), +`crates/vlog_semantic/src/bind.rs` + `crates/vlog_parser/tests/spans.rs` +(`..` in the three patterns), `tests/cases/dv_statements.cases` (3 cases). + ## QA log ### 2026-08-21 — round-1 adversarial QA