diff --git a/TODO.md b/TODO.md index 284d843..9900ba6 100644 --- a/TODO.md +++ b/TODO.md @@ -2337,7 +2337,7 @@ binds every sampled expression to the class scope. Files: the §20 set minus nothing (ast/parser/spans, format.rs + cases, verification.rs, bind/model/workspace/facts (FACTS 11 → 12), linter visit/signals, server kind arms, e2e), docs/features/covergroup-bodies/README.md. -- [ ] AST: `ItemKind::Covergroup(CovergroupDecl { name, args, sample: +- [x] AST: `ItemKind::Covergroup(CovergroupDecl { name, args, sample: Option, event: Option, items: Vec, end_label })`; `CoverItem::{ Coverpoint { label, expr, iff, bins: Option> }, Cross { label, items, @@ -2346,20 +2346,50 @@ server kind arms, e2e), docs/features/covergroup-bodies/README.md. array: Option, spec: BinSpec::{ Values(Vec), Transitions(Vec), Default, DefaultSequence, With(Expr), Binsof(Expr) }, iff }`. -- [ ] Parser with rewind fallback; `constraint_fallbacks` becomes a +- [x] Parser with rewind fallback; `constraint_fallbacks` becomes a per-construct census. -- [ ] Layout: `covergroup g @(posedge clk);` header (`with function +- [x] Layout: `covergroup g @(posedge clk);` header (`with function sample(...)` on the header), one cover item per line, `{ }` bin bodies like constraint sets, `endgroup : g` at the header column. -- [ ] Binder: `Covergroup` in the enclosing class/module scope with a +- [x] Binder: `Covergroup` in the enclosing class/module scope with a child scope holding `Coverpoint`/`Cross` symbols (so `cg.cp` and `cross a, b` bind); sampled expressions bind lexically; the `sample()` args declare TfArg-like symbols visible in the body. -- [ ] Pins mirroring §20's (rename of a sampled field, comments in +- [x] Pins mirroring §20's (rename of a sampled field, comments in every slot, `binsof … intersect`, transition bins `(a => b)`, `default sequence`, `with (item % 2)`, wildcard bins, option assignments, `iff`, macro-body and non-LRM fallbacks byte-exact). -- [ ] QA on opentitan DV (read-only): every `covergroup` under hw/dv +- [x] QA on opentitan DV (read-only): every `covergroup` under hw/dv and hw/ip/*/dv (the fpv/cov files) round-trips idempotently with comments preserved; sweep unchanged; structured-vs-fallback census; rename of a coverpoint operand. + +**Dev, 2026-09-02.** Done, `docs/features/covergroup-bodies/README.md`. +`ItemKind::Covergroup` with the `Rewind`-to-verbatim fallback; ten words +matched by text and `token.rs` untouched; canonical layout; `FACTS_FORMAT` +11 → 12 with `SymbolKind::Covergroup`/`Coverpoint`/`Cross` and +`ScopeKind::Covergroup`; `covergroup` left `on_type.rs`'s `OPAQUE`. The gap +fuzzer was written *first* this time and ships as a test (329 gaps, 52 +failing, every one classified against a non-covergroup analogue that fails +too — `docs/topo.md` §2.9-22). OpenTitan `hw`: **544 covergroups structured, +0 fallbacks**, failure set and per-file tolerant diagnostics identical to +v0.27.0, 81 files re-laid-out and verified, 87 DV covergroup files idempotent. +Corpus 813/820, 0 verification errors, +1 139 references of which 1 135 are +answered. `verify.rs` untouched; twelve new attack pairs anyway. + +**QA, 2026-09-02.** SHIP. All gates, the census (544/0 opentitan, 27/0 +corpus) and the corpus resolution column reproduced exactly. Both shared- +machinery guards (`at_postfix_segment`'s `[*/[->/[=` refusal, `no_with`) +attacked directly and hold, including outside a covergroup and against a +pathological nested `with ... with` (correctly falls back rather than +mis-parsing). Independent fuzzer re-derivation on 3 fresh fixtures (340 +gaps, 37 failing) found zero covergroup-bodies-specific regressions — all +nine failing shapes reproduce on v0.27.0. 87/87 DV files idempotent, 87/87 +comment streams equal (the one apparent mismatch is a pre-existing, +non-covergroup block-comment reflow identical to v0.27.0). OpenTitan `hw` +full sweep and this repo's `corpus/` both reproduced (13/13 and 7/7 failure +sets byte-identical; 81 and 10 files re-laid-out, all covergroup-only). +Gap found and closed: a dropped bin-array `[]` marker had no attack pin — +added `a_dropped_bin_array_marker_is_rejected`. `cargo test --workspace`: +43 binaries, 3 010 passed, 0 failed. + diff --git a/crates/lucisv_server/src/completion.rs b/crates/lucisv_server/src/completion.rs index 25ea834..d3b320c 100644 --- a/crates/lucisv_server/src/completion.rs +++ b/crates/lucisv_server/src/completion.rs @@ -1212,7 +1212,10 @@ fn completion_kind(kind: SymbolKind) -> CompletionItemKind { SymbolKind::EnumVariant => CompletionItemKind::ENUM_MEMBER, SymbolKind::Function | SymbolKind::Task => CompletionItemKind::FUNCTION, SymbolKind::Class => CompletionItemKind::CLASS, - SymbolKind::Constraint => CompletionItemKind::PROPERTY, + SymbolKind::Constraint | SymbolKind::Coverpoint | SymbolKind::Cross => { + CompletionItemKind::PROPERTY + } + SymbolKind::Covergroup => CompletionItemKind::CLASS, } } diff --git a/crates/lucisv_server/src/on_type.rs b/crates/lucisv_server/src/on_type.rs index 029350f..de2523a 100644 --- a/crates/lucisv_server/src/on_type.rs +++ b/crates/lucisv_server/src/on_type.rs @@ -136,7 +136,12 @@ fn indent_edit(doc: &Document, position: Position, indent_width: usize) -> Optio /// whatever the user wrote is what a whole-file run emits, so this model has no /// opinion there. `constraint c { ... }` needs no entry — its body is behind a /// brace, and any open bracket already silences this. -const OPAQUE: &[&str] = &["covergroup", "property", "sequence"]; +/// +/// `covergroup` **left** this list in the `covergroup-bodies` round: its items +/// are laid out from a real tree now, at one indent from the header, which is +/// exactly what an ordinary block frame computes. Its bins bodies are behind a +/// `{`, so they need no entry either, for the reason a constraint's do not. +const OPAQUE: &[&str] = &["property", "sequence"]; /// Keywords whose statement body follows them directly, after an optional /// `@(...)` event control or `#delay`. @@ -886,12 +891,25 @@ mod tests { #[test] fn a_verbatim_scope_has_no_indent_this_model_can_name() { - // A covergroup's body is emitted byte-for-byte, so whatever the user + // A property's body is emitted byte-for-byte, so whatever the user // wrote there is already what a whole-file run produces. - let text = "module m;\n covergroup cg;\n\n cp: coverpoint x;\n endgroup\nendmodule\n"; + let text = "module m;\n property p;\n\n a |-> b;\n endproperty\nendmodule\n"; assert_eq!(indent(text, 2), None); } + #[test] + fn a_covergroup_body_indents_like_any_other_block() { + // Since `covergroup-bodies` its items are laid out from a real tree, + // so the model has an answer where it used to have none. + let text = "module m;\n covergroup cg;\n\n cp: coverpoint x;\n endgroup\nendmodule\n"; + assert_eq!(indent(text, 2).as_deref(), Some(" ")); + // A bin body is behind a `{`, where an open bracket silences the + // model exactly as it does inside a constraint. + let text = + "module m;\n covergroup cg;\n cp: coverpoint x {\n\n }\n endgroup\nendmodule\n"; + assert_eq!(indent(text, 3), None); + } + #[test] fn an_assertion_statement_is_silent_for_as_long_as_it_runs() { // `assert (c) pass; else fail;` is verbatim, and its `else` runs past diff --git a/crates/lucisv_server/src/symbols.rs b/crates/lucisv_server/src/symbols.rs index a6b0a86..eb4aecd 100644 --- a/crates/lucisv_server/src/symbols.rs +++ b/crates/lucisv_server/src/symbols.rs @@ -31,6 +31,9 @@ pub fn kind_label(kind: SymbolKind) -> &'static str { SymbolKind::StructMember => "struct member", SymbolKind::Class => "class", SymbolKind::Constraint => "constraint", + SymbolKind::Covergroup => "covergroup", + SymbolKind::Coverpoint => "coverpoint", + SymbolKind::Cross => "cross", } } @@ -61,6 +64,12 @@ pub fn lsp_kind(kind: SymbolKind) -> LspKind { // LSP's `PROPERTY` is for; `FUNCTION` would promise a call site // that does not exist. SymbolKind::Constraint => LspKind::PROPERTY, + // A covergroup is a named container whose members are reached with a + // `.`, which is what `CLASS` means to an editor; a coverpoint and a + // cross are named members of it that hold a declaration rather than + // code, so they take `PROPERTY` for the reason a constraint does. + SymbolKind::Covergroup => LspKind::CLASS, + SymbolKind::Coverpoint | SymbolKind::Cross => LspKind::PROPERTY, } } diff --git a/crates/lucisv_server/src/tokens.rs b/crates/lucisv_server/src/tokens.rs index f20d07f..b5fb20a 100644 --- a/crates/lucisv_server/src/tokens.rs +++ b/crates/lucisv_server/src/tokens.rs @@ -249,7 +249,13 @@ fn symbol_type(kind: SymbolKind) -> Highlight { SymbolKind::EnumVariant => Highlight::EnumMember, SymbolKind::Param | SymbolKind::LocalParam | SymbolKind::TfArg => Highlight::Parameter, SymbolKind::Function | SymbolKind::Task => Highlight::Function, - SymbolKind::StructMember | SymbolKind::Constraint => Highlight::Property, + SymbolKind::StructMember + | SymbolKind::Constraint + | SymbolKind::Coverpoint + | SymbolKind::Cross => Highlight::Property, + // A covergroup is a type-like container, the way a class is, and the + // legend's indices are a wire contract that cannot gain a member. + SymbolKind::Covergroup => Highlight::Class, SymbolKind::Port | SymbolKind::Net | SymbolKind::Var diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index ba04eb0..d6254c1 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -6986,3 +6986,176 @@ fn renaming_a_rand_field_reaches_a_constraint_in_another_file() { let _ = std::fs::remove_dir_all(&dir); } + +/// TODO.md §21 round 2: a `rand` field sampled by a coverpoint is renamed +/// from its declaration, hover inside a bin expression says what the name is, +/// and `cg.cp` reaches the coverpoint the covergroup declares. +#[test] +fn renaming_a_rand_field_rewrites_its_coverpoint_uses() { + let dir = temp_dir("covergrouprename"); + let file = dir.join("cov.sv"); + let text = "\ +class item; + rand int user_id; + int limit; + covergroup cg_id; + cp_id: coverpoint user_id { + bins low = {[0:limit]}; + } + cr: cross cp_id, user_id; + endgroup +endclass +"; + std::fs::write(&file, text).expect("write"); + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", file.display()); + + // Line 1 col 11 is the declaration of `user_id`. + // Line 4 col 22 is its use as the sampled expression. + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(text).expect("json") + )), + // Hover inside the bin expression. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":5,"character":21}}}}}}"# + )), + // Definition from the sampled expression. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":4,"character":24}}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/rename","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":11}},"newName":"uid"}}}}"# + )), + // Hover on the covergroup's own name, and on a coverpoint label. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":3,"character":14}}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":6,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":4,"character":6}}}}}}"# + )), + // The cross operand reaches the coverpoint the covergroup declared. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":7,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":7,"character":14}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + let response = |id: u32| -> &serde_json::Value { + messages + .iter() + .find(|m| m["id"] == id) + .unwrap_or_else(|| panic!("no response {id} in {messages:#?}")) + }; + + let hover = response(2)["result"]["contents"]["value"].as_str().expect("hover markdown"); + assert!(hover.contains("int limit"), "the bin expression's name: got {hover}"); + + let definition = &response(3)["result"]; + let range = definition.get("range").unwrap_or(&definition[0]["range"]); + assert_eq!(range["start"]["line"], 1, "the property's declaration: {definition:#?}"); + + let edits = response(4)["result"]["changes"][&uri].as_array().expect("edits"); + let lines: Vec = + edits.iter().filter_map(|e| e["range"]["start"]["line"].as_i64()).collect(); + assert!(edits.iter().all(|e| e["newText"] == "uid"), "{edits:#?}"); + for line in [1, 4, 7] { + assert!(lines.contains(&line), "line {line} must be rewritten: {edits:#?}"); + } + + let covergroup_hover = + response(5)["result"]["contents"]["value"].as_str().expect("hover markdown"); + assert!(covergroup_hover.contains("**covergroup**"), "got {covergroup_hover}"); + let coverpoint_hover = + response(6)["result"]["contents"]["value"].as_str().expect("hover markdown"); + assert!(coverpoint_hover.contains("**coverpoint**"), "got {coverpoint_hover}"); + + let cross_operand = &response(7)["result"]; + let range = cross_operand.get("range").unwrap_or(&cross_operand[0]["range"]); + assert_eq!(range["start"]["line"], 4, "the coverpoint's label: {cross_operand:#?}"); + + let _ = std::fs::remove_dir_all(&dir); +} + +/// The cross-file half: the class is in one file, and a covergroup in another +/// class samples a property it inherits from it. Definition from the sampled +/// expression reaches the base class's property, and renaming from that +/// declaration rewrites the coverpoint too. +#[test] +fn renaming_a_rand_field_reaches_a_coverpoint_in_another_file() { + let dir = temp_dir("covergrouprenamecross"); + let decl = dir.join("base.sv"); + std::fs::write( + &decl, + "package base_pkg;\n class base_item;\n rand int user_id;\n endclass\nendpackage\n", + ) + .expect("write"); + let cov = dir.join("cov.sv"); + std::fs::write( + &cov, + "class my_item extends base_pkg::base_item;\n covergroup cg;\n cp: coverpoint user_id;\n endgroup\nendclass\n", + ) + .expect("write"); + let root = format!("file://{}", dir.display()); + let decl_uri = format!("file://{}", decl.display()); + let cov_uri = format!("file://{}", cov.display()); + let cov_text = std::fs::read_to_string(&cov).expect("read"); + let decl_text = std::fs::read_to_string(&decl).expect("read"); + + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{cov_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(&cov_text).expect("json") + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{cov_uri}"}},"position":{{"line":2,"character":20}}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{decl_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(&decl_text).expect("json") + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/rename","params":{{"textDocument":{{"uri":"{decl_uri}"}},"position":{{"line":2,"character":13}},"newName":"uid"}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + let response = |id: u32| -> &serde_json::Value { + messages + .iter() + .find(|m| m["id"] == id) + .unwrap_or_else(|| panic!("no response {id} in {messages:#?}")) + }; + + let definition = &response(2)["result"]; + let target = definition + .get("uri") + .or_else(|| definition[0].get("uri")) + .and_then(|u| u.as_str()) + .unwrap_or_default(); + assert_eq!(target, decl_uri, "the base class's property: {definition:#?}"); + + let changes = &response(3)["result"]["changes"]; + assert!(!changes[&decl_uri].is_null(), "the declaring file is edited: {changes:#?}"); + let in_cov = changes[&cov_uri].as_array().expect("the covergroup file is edited"); + assert_eq!(in_cov.len(), 1, "{in_cov:#?}"); + assert_eq!(in_cov[0]["newText"], "uid"); + assert_eq!(in_cov[0]["range"]["start"]["line"], 2, "inside the coverpoint"); + + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/vlog_formatter/src/format.rs b/crates/vlog_formatter/src/format.rs index da5acd3..6fe8f8b 100644 --- a/crates/vlog_formatter/src/format.rs +++ b/crates/vlog_formatter/src/format.rs @@ -1149,6 +1149,7 @@ impl<'a> Fmt<'a> { ItemKind::Modport(decls) => self.modport(decls), ItemKind::Clocking(c) => self.clocking(c), ItemKind::Constraint(c) => self.constraint(c), + ItemKind::Covergroup(c) => self.covergroup(c), ItemKind::Verbatim(raw) => self.raw_text(raw), // A null item is its `;`. Whether it keeps the previous item's // line or takes one of its own is `item_seq`'s call. @@ -2686,12 +2687,19 @@ impl<'a> Fmt<'a> { /// The `( cond )` of a constraint `if`, with the comments written just /// inside either parenthesis printed back where they were written. fn constraint_parens(&self, cond: &Expr, comments: &HeaderComments) -> Doc { - if comments.after_open.is_empty() && comments.before_close.is_empty() { - return self.parens(cond); + self.guard_parens(cond, &comments.after_open, &comments.before_close) + } + + /// `( expr )` with whatever was written just inside either parenthesis: + /// a constraint `if`'s condition, a covergroup `iff` guard, a bin's + /// `with ( ... )` filter. One place, so the three cannot drift apart. + fn guard_parens(&self, e: &Expr, after_open: &[Comment], before_close: &[Comment]) -> Doc { + if after_open.is_empty() && before_close.is_empty() { + return self.parens(e); } - let before: Vec<&Comment> = comments.after_open.iter().collect(); - let after: Vec<&Comment> = comments.before_close.iter().collect(); - self.paren_comments(cond, &before, &after) + let before: Vec<&Comment> = after_open.iter().collect(); + let after: Vec<&Comment> = before_close.iter().collect(); + self.paren_comments(e, &before, &after) } /// The `if` an `else` chains straight onto: the single item of an @@ -2741,25 +2749,31 @@ impl<'a> Fmt<'a> { /// A list with no brackets has nothing to open, so every comment prints /// where it was written and only a `//` costs a line break. fn plain_expr_list(&self, items: &[ExprItem]) -> Doc { + self.plain_list(items.iter().map(|i| (&i.meta, self.expr(&i.expr))).collect()) + } + + /// The same, over elements the caller has already rendered: a transition + /// bin's `(a => b), (c => d)` sets are laid out by exactly this rule. + fn plain_list(&self, items: Vec<(&Meta, Doc)>) -> Doc { let mut docs = Vec::new(); let last = items.len().saturating_sub(1); - for (i, item) in items.iter().enumerate() { - let leading: Vec<&Comment> = item.meta.leading.iter().collect(); + for (i, (meta, doc)) in items.into_iter().enumerate() { + let leading: Vec<&Comment> = meta.leading.iter().collect(); let mut ends_line = false; for c in leading { docs.push(self.comment(c)); docs.push(if is_line_comment(&c.text) { Doc::HardLine } else { text(" ") }); ends_line = is_line_comment(&c.text); } - docs.push(self.expr(&item.expr)); - ends_line = self.inline_comments(&item.meta.before_sep, &mut docs) || ends_line; + docs.push(doc); + ends_line = self.inline_comments(&meta.before_sep, &mut docs) || ends_line; if i < last { if ends_line { docs.push(Doc::HardLine); } docs.push(text(",")); } - if let Some(tr) = &item.meta.trailing { + if let Some(tr) = &meta.trailing { docs.push(text(" ")); docs.push(self.comment(tr)); if is_line_comment(&tr.text) { @@ -2799,6 +2813,419 @@ impl<'a> Fmt<'a> { concat(docs) } + // ------------------------------------------------------------------ + // Covergroups + // ------------------------------------------------------------------ + + /// `covergroup g (args) with function sample (args); ... endgroup : g`. + /// + /// A covergroup is a block, so it is laid out like one: the whole header + /// on the header line, every cover item on a line of its own at one + /// further indent, and `endgroup` back at the header's column with + /// whatever label the source wrote. + fn covergroup(&self, c: &CovergroupDecl) -> Doc { + let mut head = String::new(); + for q in &c.qualifiers { + head.push_str(q); + head.push(' '); + } + head.push_str("covergroup"); + let mut docs = vec![text(head)]; + self.inline_comments_spaced(&c.before_name, &mut docs); + docs.push(name_doc(&c.name.text)); + if let Some(args) = &c.args { + if !c.before_args.is_empty() { + self.inline_comments_spaced(&c.before_args, &mut docs); + } + docs.push(self.tf_args(args)); + } + match &c.event { + Some(CoverageEvent::Sample(s)) => { + self.inline_comments_spaced(&s.before_with, &mut docs); + docs.push(text("with")); + self.inline_comments_spaced(&s.after_with, &mut docs); + docs.push(text("function")); + self.inline_comments_spaced(&s.after_function, &mut docs); + docs.push(name_doc(&s.name.text)); + if s.has_parens { + if !s.before_args.is_empty() { + self.inline_comments_spaced(&s.before_args, &mut docs); + } + docs.push(self.tf_args(&s.args)); + } + } + Some(CoverageEvent::Clocking { before, sens }) => { + self.inline_comments_spaced(before, &mut docs); + docs.push(self.sens_list(sens)); + } + None => {} + } + if self.inline_comments(&c.before_semi, &mut docs) { + docs.push(Doc::HardLine); + } + docs.push(text(";")); + let mut body = Vec::new(); + if !c.items.is_empty() { + body.push(Doc::HardLine); + body.extend(self.cover_items(&c.items)); + } + body.extend(self.dangling(&c.dangling)); + docs.push(indent(body)); + docs.push(Doc::HardLine); + docs.push(match &c.end_label { + Some(l) => text(format!("endgroup : {}", named(&l.text))), + None => text("endgroup"), + }); + if c.end_semi { + if self.inline_comments(&c.before_end_semi, &mut docs) { + docs.push(Doc::HardLine); + } + docs.push(text(";")); + } + concat(docs) + } + + fn cover_items(&self, items: &[CoverItem]) -> Vec { + let mut docs = Vec::new(); + for (i, item) in items.iter().enumerate() { + if i > 0 { + docs.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); + } + docs.push(self.with_meta(&item.meta, self.cover_item(item))); + } + docs + } + + /// One cover item, and the `;` that ends it when its kind takes one — the + /// rule [`CoverItemKind::takes_semi`] is the single answer to, read here + /// and by the parser that consumed it. + fn cover_item(&self, item: &CoverItem) -> Doc { + let mut docs = vec![self.cover_item_kind(&item.kind)]; + if item.kind.takes_semi() { + if self.inline_comments(&item.before_semi, &mut docs) { + docs.push(Doc::HardLine); + } + docs.push(text(";")); + } + concat(docs) + } + + fn cover_item_kind(&self, kind: &CoverItemKind) -> Doc { + match kind { + CoverItemKind::Coverpoint(cp) => { + let mut head = Vec::new(); + self.cover_label(&cp.label, &mut head); + head.push(text("coverpoint")); + self.inline_comments_spaced(&cp.after_kw, &mut head); + head.push(self.expr(&cp.expr)); + self.cover_iff(&cp.iff, &mut head); + self.cover_body_as_body(concat(head), &cp.before_body, &cp.body) + } + CoverItemKind::Cross(cr) => { + let mut head = Vec::new(); + self.cover_label(&cr.label, &mut head); + head.push(text("cross")); + self.inline_comments_spaced(&cr.after_kw, &mut head); + head.push(self.plain_expr_list(&cr.items)); + self.cover_iff(&cr.iff, &mut head); + self.cover_body_as_body(concat(head), &cr.before_body, &cr.body) + } + CoverItemKind::Option(o) => self.option_assign(o), + CoverItemKind::Directive(raw) => self.raw_text(raw), + CoverItemKind::Empty => text(";"), + } + } + + /// The `name :` a coverpoint or a cross may be labelled with. + fn cover_label(&self, label: &Option, docs: &mut Vec) { + let Some(l) = label else { return }; + docs.push(name_doc(&l.name.text)); + if self.inline_comments(&l.comments.before, docs) { + docs.push(Doc::HardLine); + } + docs.push(text(":")); + self.inline_comments_spaced(&l.comments.after, docs); + } + + /// The ` iff ( expr )` guard of a coverpoint, a cross or a bin. + fn cover_iff(&self, iff: &Option>, docs: &mut Vec) { + let Some(i) = iff else { return }; + self.inline_comments_spaced(&i.before_kw, docs); + docs.push(text("iff")); + self.inline_comments_spaced(&i.after_kw, docs); + docs.push(self.guard_parens(&i.expr, &i.after_open, &i.before_close)); + } + + /// A coverpoint or cross header followed by its `{ bins }` body, or by + /// nothing at all — a body-less one ends in the `;` [`Fmt::cover_item`] + /// writes. + fn cover_body_as_body(&self, head: Doc, before: &[Comment], body: &Option) -> Doc { + let Some(body) = body else { return head }; + let mut docs = vec![head]; + if self.inline_comments(before, &mut docs) { + docs.push(Doc::HardLine); + } else { + docs.push(text(" ")); + } + docs.push(self.cover_block(body)); + concat(docs) + } + + /// The `{ ... }` of a coverpoint or cross body: one bin per line at one + /// further indent, the `}` back at the header's column — a constraint + /// set's layout, for a construct that reads the same way. + fn cover_block(&self, body: &CoverBody) -> Doc { + let mut inner = Vec::new(); + if !body.items.is_empty() { + inner.push(Doc::HardLine); + inner.extend(self.bin_items(&body.items)); + } + inner.extend(self.dangling(&body.dangling)); + if inner.is_empty() { + return text("{}"); + } + group(vec![text("{"), indent(inner), Doc::HardLine, text("}")]) + } + + fn bin_items(&self, items: &[BinItem]) -> Vec { + let mut docs = Vec::new(); + for (i, item) in items.iter().enumerate() { + if i > 0 { + docs.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); + } + docs.push(self.with_meta(&item.meta, self.bin_item(item))); + } + docs + } + + fn bin_item(&self, item: &BinItem) -> Doc { + let mut docs = vec![match &item.kind { + BinItemKind::Bin(b) => self.bin_decl(b), + BinItemKind::Option(o) => self.option_assign(o), + BinItemKind::Directive(raw) => self.raw_text(raw), + BinItemKind::Empty => text(";"), + }]; + if item.kind.takes_semi() { + if self.inline_comments(&item.before_semi, &mut docs) { + docs.push(Doc::HardLine); + } + docs.push(text(";")); + } + concat(docs) + } + + /// `option.per_instance = 1` / `type_option.weight = 5`. + fn option_assign(&self, o: &OptionAssign) -> Doc { + let mut docs = vec![self.expr(&o.target)]; + if self.inline_comments(&o.comments.before, &mut docs) { + docs.push(Doc::HardLine); + } else { + docs.push(text(" ")); + } + docs.push(text("=")); + self.inline_comments_spaced(&o.comments.after, &mut docs); + docs.push(self.expr(&o.value)); + concat(docs) + } + + /// `[wildcard ]bins name[4] = spec [with (expr)] [iff (expr)]`. + fn bin_decl(&self, b: &BinDecl) -> Doc { + let mut docs = Vec::new(); + if b.wildcard { + docs.push(text("wildcard")); + self.inline_comments_spaced(&b.after_wildcard, &mut docs); + } + docs.push(text(b.kind.as_str())); + self.inline_comments_spaced(&b.before_name, &mut docs); + docs.push(name_doc(&b.name.text)); + if let Some(a) = &b.array { + if !a.before.is_empty() { + self.inline_comments_spaced(&a.before, &mut docs); + } + docs.push(text("[")); + self.inline_comments(&a.comments.before, &mut docs); + if !a.comments.before.is_empty() { + docs.push(text(" ")); + } + if let Some(size) = &a.size { + docs.push(self.expr(size)); + } + if self.inline_comments(&a.comments.after, &mut docs) { + docs.push(Doc::HardLine); + } else if !a.comments.after.is_empty() { + docs.push(text(" ")); + } + docs.push(text("]")); + } + if self.inline_comments(&b.eq_comments.before, &mut docs) { + docs.push(Doc::HardLine); + } else { + docs.push(text(" ")); + } + docs.push(text("=")); + self.inline_comments_spaced(&b.eq_comments.after, &mut docs); + docs.push(self.bin_spec(&b.spec)); + if let Some(w) = &b.with_expr { + self.inline_comments_spaced(&w.before_kw, &mut docs); + docs.push(text("with")); + self.inline_comments_spaced(&w.after_kw, &mut docs); + docs.push(self.guard_parens(&w.expr, &w.after_open, &w.before_close)); + } + self.cover_iff(&b.iff, &mut docs); + concat(docs) + } + + fn bin_spec(&self, spec: &BinSpec) -> Doc { + match spec { + BinSpec::Values(items) => self.expr_list("{", items, "}"), + BinSpec::Transitions(sets) => self.trans_list(sets), + BinSpec::Default => text("default"), + BinSpec::DefaultSequence { comments } => { + let mut docs = vec![text("default")]; + self.inline_comments_spaced(comments, &mut docs); + docs.push(text("sequence")); + concat(docs) + } + BinSpec::Select(s) => self.select_expr(s), + } + } + + /// `(a => b), (c => d)` — the transition sets of a transition bin, joined + /// by the commas the source wrote. + fn trans_list(&self, sets: &[TransSet]) -> Doc { + self.plain_list(sets.iter().map(|s| (&s.meta, self.trans_set(s))).collect()) + } + + fn trans_set(&self, set: &TransSet) -> Doc { + let mut docs = vec![text("(")]; + for (i, r) in set.ranges.iter().enumerate() { + if i > 0 { + if self.inline_comments(&r.arrow_comments.before, &mut docs) { + docs.push(Doc::HardLine); + } else { + docs.push(text(" ")); + } + docs.push(text("=>")); + self.inline_comments_spaced(&r.arrow_comments.after, &mut docs); + } + docs.push(self.trans_range(r)); + } + if self.inline_comments(&set.dangling, &mut docs) { + docs.push(Doc::HardLine); + } else if !set.dangling.is_empty() { + docs.push(text(" ")); + } + docs.push(text(")")); + concat(docs) + } + + fn trans_range(&self, r: &TransRange) -> Doc { + let mut docs = vec![self.plain_expr_list(&r.items)]; + let Some(rep) = &r.repeat else { return concat(docs) }; + if !rep.before.is_empty() { + self.inline_comments_spaced(&rep.before, &mut docs); + } + docs.push(text("[")); + self.inline_comments(&rep.after_open, &mut docs); + if !rep.after_open.is_empty() { + docs.push(text(" ")); + } + docs.push(text(rep.op.clone())); + self.inline_comments(&rep.comments.before, &mut docs); + if !rep.comments.before.is_empty() { + docs.push(text(" ")); + } + docs.push(self.expr(&rep.lo)); + if let Some(hi) = &rep.hi { + self.inline_comments(&rep.colon_comments.before, &mut docs); + if !rep.colon_comments.before.is_empty() { + docs.push(text(" ")); + } + docs.push(text(":")); + self.inline_comments(&rep.colon_comments.after, &mut docs); + if !rep.colon_comments.after.is_empty() { + docs.push(text(" ")); + } + docs.push(self.expr(hi)); + } + if self.inline_comments(&rep.comments.after, &mut docs) { + docs.push(Doc::HardLine); + } else if !rep.comments.after.is_empty() { + docs.push(text(" ")); + } + docs.push(text("]")); + concat(docs) + } + + /// `binsof(a) intersect {0} && !binsof(b)` — a cross bin's select + /// expression, and the bare coverpoint name a coverpoint bin may name. + fn select_expr(&self, s: &SelectExpr) -> Doc { + match s { + SelectExpr::Binsof(b) => { + let mut docs = vec![text("binsof")]; + if !b.after_kw.is_empty() { + self.inline_comments_spaced(&b.after_kw, &mut docs); + } + docs.push(text("(")); + self.inline_comments(&b.after_open, &mut docs); + if !b.after_open.is_empty() { + docs.push(text(" ")); + } + docs.push(self.expr(&b.name)); + if self.inline_comments(&b.before_close, &mut docs) { + docs.push(Doc::HardLine); + } else if !b.before_close.is_empty() { + docs.push(text(" ")); + } + docs.push(text(")")); + if let Some(items) = &b.intersect { + self.inline_comments_spaced(&b.before_intersect, &mut docs); + docs.push(text("intersect")); + self.inline_comments_spaced(&b.after_intersect, &mut docs); + docs.push(self.expr_list("{", items, "}")); + } + concat(docs) + } + SelectExpr::Not { comments, expr } => { + let mut docs = vec![text("!")]; + if !comments.is_empty() { + self.inline_comments(comments, &mut docs); + docs.push(text(" ")); + } + docs.push(self.select_expr(expr)); + concat(docs) + } + SelectExpr::Binary { lhs, op, comments, rhs } => { + let mut docs = vec![self.select_expr(lhs)]; + if self.inline_comments(&comments.before, &mut docs) { + docs.push(Doc::HardLine); + } else { + docs.push(text(" ")); + } + docs.push(text(op.clone())); + self.inline_comments_spaced(&comments.after, &mut docs); + docs.push(self.select_expr(rhs)); + concat(docs) + } + SelectExpr::Paren { comments, expr } => { + let mut docs = vec![text("(")]; + self.inline_comments(&comments.before, &mut docs); + if !comments.before.is_empty() { + docs.push(text(" ")); + } + docs.push(self.select_expr(expr)); + if self.inline_comments(&comments.after, &mut docs) { + docs.push(Doc::HardLine); + } else if !comments.after.is_empty() { + docs.push(text(" ")); + } + docs.push(text(")")); + concat(docs) + } + SelectExpr::Expr(e) => self.expr(e), + } + } + // ------------------------------------------------------------------ // Statements // ------------------------------------------------------------------ diff --git a/crates/vlog_formatter/tests/cases/classes.cases b/crates/vlog_formatter/tests/cases/classes.cases index e709667..749799d 100644 --- a/crates/vlog_formatter/tests/cases/classes.cases +++ b/crates/vlog_formatter/tests/cases/classes.cases @@ -221,7 +221,8 @@ class item; } endclass ==== -# a covergroup is reproduced byte for byte too, endgroup label included +# a covergroup is laid out canonically since the covergroup-bodies round: the +# header on one line, one cover item per line, the endgroup label kept class cov; covergroup branch_dest_cg with function sample (bit [31:0] addr); coverpoint addr { @@ -232,10 +233,10 @@ class cov; endclass ---- class cov; - covergroup branch_dest_cg with function sample (bit [31:0] addr); + covergroup branch_dest_cg with function sample(bit [31:0] addr); coverpoint addr { - bins zero = { 0 }; - bins mid = default; + bins zero = {0}; + bins mid = default; } endgroup : branch_dest_cg endclass diff --git a/crates/vlog_formatter/tests/cases/covergroups.cases b/crates/vlog_formatter/tests/cases/covergroups.cases new file mode 100644 index 0000000..f713498 --- /dev/null +++ b/crates/vlog_formatter/tests/cases/covergroups.cases @@ -0,0 +1,616 @@ +# Covergroup bodies (IEEE 1800 §19) — the canonical layout the +# covergroup-bodies round introduced. See +# docs/features/covergroup-bodies/README.md. +# +# A covergroup is a block and is laid out like one: the whole header on the +# header line, one cover item per line at one further indent, and `endgroup` +# back at the header's column with whatever label the source wrote. A +# coverpoint or cross body is laid out like a constraint set, one bin per +# line. A covergroup the grammar does not recognise rewinds to the +# byte-for-byte verbatim capture covergroups had before this round. + +# a covergroup is a block: the header on one line, one cover item per line, +# `endgroup` back at the header's column +class cov; +covergroup cg; +coverpoint addr; +endgroup +endclass +---- +class cov; + covergroup cg; + coverpoint addr; + endgroup +endclass +==== +# the whole header on one line: formals, the sample function, the end label +class cov; + covergroup cg (bit [3:0] a, int n) with function sample (bit [31:0] addr, bit rw); + cp_addr : coverpoint addr { + bins lo = { [0:9] }; + bins hi = {[10:$]}; + } + endgroup : cg +endclass +---- +class cov; + covergroup cg(bit [3:0] a, int n) with function sample(bit [31:0] addr, bit rw); + cp_addr: coverpoint addr { + bins lo = {[0:9]}; + bins hi = {[10:$]}; + } + endgroup : cg +endclass +==== +# a clocking event header, and the option assignments a covergroup body may hold +module m; +covergroup cg @(posedge clk); +option.per_instance = 1; +option.name = "cg"; +type_option.weight = 5; +coverpoint x; +endgroup +endmodule +---- +module m; + covergroup cg @(posedge clk); + option.per_instance = 1; + option.name = "cg"; + type_option.weight = 5; + coverpoint x; + endgroup +endmodule +==== +# every bin shape: wildcard, the three keywords, defaults, transitions with +# their three repetitions, a `with` filter and a per-bin `iff` +class c; +covergroup cg; +cp : coverpoint a iff (en) { +wildcard bins w[4] = {4'b1??1}; +ignore_bins ig = {2, 3}; +illegal_bins bad = default; +bins seq = default sequence; +bins t = (0 => 1, 2 => 3), (4 => 5); +bins r = (1'b0[*1:10] => 1'b1[->2] => 1'b0[=1]); +bins e[] = cp_x with (item % 2 == 0); +bins v = {[0:$]} with ($countones(item) != 1); +bins g = {1} iff (en); +} +endgroup : cg +endclass +---- +class c; + covergroup cg; + cp: coverpoint a iff (en) { + wildcard bins w[4] = {4'b1??1}; + ignore_bins ig = {2, 3}; + illegal_bins bad = default; + bins seq = default sequence; + bins t = (0 => 1, 2 => 3), (4 => 5); + bins r = (1'b0[*1:10] => 1'b1[->2] => 1'b0[=1]); + bins e[] = cp_x with (item % 2 == 0); + bins v = {[0:$]} with ($countones(item) != 1); + bins g = {1} iff (en); + } + endgroup : cg +endclass +==== +# a cross body: `binsof ... intersect`, the boolean operators, a nested paren +class c; +covergroup cg; +cr : cross cp_a, cp_b { +bins sel = binsof(cp_a.x) intersect {0, [1:2]} && !binsof(cp_b); +bins two = (binsof(cp_a) || binsof(cp_b)) && binsof(cp_c) intersect {1}; +option.weight = 0; +} +endgroup : cg +endclass +---- +class c; + covergroup cg; + cr: cross cp_a, cp_b { + bins sel = binsof(cp_a.x) intersect {0, [1:2]} && !binsof(cp_b); + bins two = (binsof(cp_a) || binsof(cp_b)) && binsof(cp_c) intersect {1}; + option.weight = 0; + } + endgroup : cg +endclass +==== +# an empty body prints `{}`, a null item and a stray `;` after `endgroup` are +# both reproduced +class c; +covergroup cg; +cp: coverpoint a { +} +cr: cross a, b; +; +endgroup; +endclass +---- +class c; + covergroup cg; + cp: coverpoint a {} + cr: cross a, b; + ; + endgroup; +endclass +==== +# every header and bin comment slot prints back where it was written +class c; + covergroup /*a*/ cg /*b*/ (int n) /*c*/ with /*d*/ function /*e*/ sample /*f*/ (int x) /*g*/ ; + cp /*h*/ : /*i*/ coverpoint /*j*/ x /*k*/ iff /*l*/ ( /*m*/ en /*n*/ ) /*o*/ { + wildcard /*p*/ bins /*q*/ v /*r*/ [ /*s*/ 4 /*t*/ ] /*u*/ = /*v*/ {1} /*w*/ with /*x*/ ( /*y*/ item /*z*/ ) /*A*/ iff /*B*/ ( /*C*/ en /*D*/ ) /*E*/ ; + } + endgroup : cg /*F*/ ; +endclass +---- +class c; + covergroup /*a*/ cg /*b*/ (int n) /*c*/ with /*d*/ function /*e*/ sample /*f*/ (int x) /*g*/; + cp /*h*/: /*i*/ coverpoint /*j*/ x /*k*/ iff /*l*/ ( + /*m*/ + en /*n*/ + ) /*o*/ { + wildcard /*p*/ bins /*q*/ v /*r*/ [ /*s*/ 4 /*t*/ ] /*u*/ = /*v*/ {1} /*w*/ with /*x*/ ( + /*y*/ + item /*z*/ + ) /*A*/ iff /*B*/ ( + /*C*/ + en /*D*/ + ) /*E*/; + } + endgroup : cg /*F*/; +endclass +==== +# leading, trailing and dangling comments in a covergroup body +class c; +covergroup cg; +// a leading comment +cp: coverpoint a { // trailing +// inside +bins v = {1}; // after +// dangling +} + +cr: cross a, b; +// last +endgroup +endclass +---- +class c; + covergroup cg; + // a leading comment + cp: coverpoint a { + // trailing + // inside + bins v = {1}; // after + // dangling + } + + cr: cross a, b; + // last + endgroup +endclass +==== +# both arms of an `ifdef stand as ordinary cover items +class c; +covergroup cg; +`ifdef FOO +cp: coverpoint a; +`else +cp: coverpoint b; +`endif +endgroup +endclass +---- +class c; + covergroup cg; + `ifdef FOO + cp: coverpoint a; + `else + cp: coverpoint b; + `endif + endgroup +endclass +==== +# a long sample-function list breaks like a port list; a long value list breaks +# like every other braced list +class c; +covergroup cg_with_a_really_long_name_here with function sample (bit [31:0] address_value, bit read_write_flag, int unsigned index); +cp: coverpoint address_value { +bins many = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22}; +} +endgroup +endclass +---- +class c; + covergroup cg_with_a_really_long_name_here with function sample( + bit [31:0] address_value, + bit read_write_flag, + int unsigned index + ); + cp: coverpoint address_value { + bins many = { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22 + }; + } + endgroup +endclass +==== +# a macro supplying a coverpoint's whole bin body rewinds to the byte-for-byte +# verbatim capture covergroups had before this round +class c; +covergroup cg; +cp: coverpoint a `GPR_BIN_TYPES +endgroup : cg +endclass +---- +class c; + covergroup cg; + cp: coverpoint a `GPR_BIN_TYPES + endgroup : cg +endclass +==== +# a macro standing where a cover item belongs is passed through, the way one +# standing where an item or a statement belongs is +class c; +covergroup cg; +`MY_CP(a, b) +cp: coverpoint a; +endgroup +endclass +---- +class c; + covergroup cg; + `MY_CP(a, b) + cp: coverpoint a; + endgroup +endclass +==== +# a covergroup at package scope +package p; +covergroup cg; +coverpoint x; +endgroup +endpackage +---- +package p; + covergroup cg; + coverpoint x; + endgroup +endpackage +==== +# the member qualifiers a covergroup may carry +class c; +local covergroup cg; +coverpoint x; +endgroup +static covergroup cg2; +coverpoint y; +endgroup +endclass +---- +class c; + local covergroup cg; + coverpoint x; + endgroup + static covergroup cg2; + coverpoint y; + endgroup +endclass +==== +# every name goes through `name_doc`: an escaped identifier keeps its +# terminating space +class c; +covergroup \cg-1 ; +\cp-1 : coverpoint \a-1 { +bins \b-1 = {1}; +} +endgroup : \cg-1 +endclass +---- +class c; + covergroup \cg-1 ; + \cp-1 : coverpoint \a-1 { + bins \b-1 = {1}; + } + endgroup : \cg-1 +endclass +==== +# a covergroup with no items at all +class c; +covergroup cg; +endgroup +endclass +---- +class c; + covergroup cg; + endgroup +endclass +==== +# a blank line between two cover items is kept +class c; +covergroup cg; +cp1: coverpoint a; + +cp2: coverpoint b; +endgroup +endclass +---- +class c; + covergroup cg; + cp1: coverpoint a; + + cp2: coverpoint b; + endgroup +endclass +==== +# the unsized `[]` array spelling, on both a value and a default bin +class c; +covergroup cg with function sample(bit a); +cp: coverpoint a { +bins v[] = {[0:$]}; +bins w[] = default; +} +endgroup +endclass +---- +class c; + covergroup cg with function sample(bit a); + cp: coverpoint a { + bins v[] = {[0:$]}; + bins w[] = default; + } + endgroup +endclass +==== +# a bare `@ev` event keeps its lack of parentheses; an `or` list keeps its +# spelling +module m; +covergroup cg @ev; +coverpoint x; +endgroup +covergroup cg2 @(a or b); +coverpoint y; +endgroup +endmodule +---- +module m; + covergroup cg @ev; + coverpoint x; + endgroup + covergroup cg2 @(a or b); + coverpoint y; + endgroup +endmodule +==== +# a concatenation as the sampled expression, and an `iff` guard on it +class c; +covergroup cg; +cp: coverpoint {a, b, (c != d)} iff (!rst) { +bins z = {0}; +} +endgroup +endclass +---- +class c; + covergroup cg; + cp: coverpoint {a, b, (c != d)} iff (!rst) { + bins z = {0}; + } + endgroup +endclass +==== +# a `{` written on its own line cuddles onto the header +class c; +covergroup cg; +cp: coverpoint a +{ +bins v = {1}; +} +endgroup +endclass +---- +class c; + covergroup cg; + cp: coverpoint a { + bins v = {1}; + } + endgroup +endclass +==== +# a covergroup whose `endgroup` label is missing keeps none +class c; +covergroup cg; +cp: coverpoint a; +endgroup +endclass +---- +class c; + covergroup cg; + cp: coverpoint a; + endgroup +endclass +==== +# `option` and `type_option` inside a coverpoint body, beside its bins +class c; +covergroup cg; +cp: coverpoint a { +option.weight = 3; +type_option.merge_instances = 1; +bins v = {1}; +} +endgroup +endclass +---- +class c; + covergroup cg; + cp: coverpoint a { + option.weight = 3; + type_option.merge_instances = 1; + bins v = {1}; + } + endgroup +endclass +==== +# an unlabelled coverpoint and an unlabelled cross +class c; +covergroup cg; +coverpoint a; +cross a, b; +endgroup +endclass +---- +class c; + covergroup cg; + coverpoint a; + cross a, b; + endgroup +endclass +==== +# a transition bin whose ranges carry value ranges of their own +class c; +covergroup cg; +cp: coverpoint a { +bins any2any[] = ([None:Bidir] => [None:Bidir]); +bins two = (Read, Write => RStart); +} +endgroup +endclass +---- +class c; + covergroup cg; + cp: coverpoint a { + bins any2any[] = ([None:Bidir] => [None:Bidir]); + bins two = (Read, Write => RStart); + } + endgroup +endclass +==== +# a scope-qualified name in a bin value and in a `with` filter +class c; +covergroup cg; +cp: coverpoint a { +bins on = {lc_ctrl_pkg::On}; +bins bad = {[0:$]} with (!(item inside {lc_ctrl_pkg::Off, lc_ctrl_pkg::On})); +} +endgroup +endclass +---- +class c; + covergroup cg; + cp: coverpoint a { + bins on = {lc_ctrl_pkg::On}; + bins bad = {[0:$]} with (!(item inside {lc_ctrl_pkg::Off, lc_ctrl_pkg::On})); + } + endgroup +endclass +==== +# a covergroup nested in a class that also carries a constraint: both bodies +# are laid out, and neither reaches into the other +class item; +rand int addr; +constraint c_addr { addr < 64; } +covergroup cg_addr with function sample (int a); +cp: coverpoint a { bins lo = {[0:31]}; } +endgroup +endclass +---- +class item; + rand int addr; + constraint c_addr { + addr < 64; + } + covergroup cg_addr with function sample(int a); + cp: coverpoint a { + bins lo = {[0:31]}; + } + endgroup +endclass +==== +# a comment written where the `;` of an item was not written belongs to the +# item that follows it +class c; +covergroup cg; +cp: coverpoint x { +} +// why +cr: cross a, b; +endgroup +endclass +---- +class c; + covergroup cg; + cp: coverpoint x {} + // why + cr: cross a, b; + endgroup +endclass +==== +# a coverpoint bin's `( ... )` is a transition list even with no arrow; a +# cross bin's is a parenthesized select expression +class c; +covergroup cg; +cp: coverpoint a { +bins zero_delay_5 = (1'b1[*5]); +bins stall_long = (1'b0[*5:10] => 1'b1); +} +cr: cross a, b { +bins any = (binsof(a) || binsof(b)) && !binsof(c); +} +endgroup +endclass +---- +class c; + covergroup cg; + cp: coverpoint a { + bins zero_delay_5 = (1'b1[*5]); + bins stall_long = (1'b0[*5:10] => 1'b1); + } + cr: cross a, b { + bins any = (binsof(a) || binsof(b)) && !binsof(c); + } + endgroup +endclass +==== +# a call may stand as a bin spec, and a concatenation may stand as a +# transition item +class c; +covergroup cg; +cp: coverpoint a { +bins single_exc[] = single_masks(num_hw_apps); +bins req_before_done = ({1'b1, pkg::False} => {1'b1, pkg::True}); +} +endgroup +endclass +---- +class c; + covergroup cg; + cp: coverpoint a { + bins single_exc[] = single_masks(num_hw_apps); + bins req_before_done = ({1'b1, pkg::False} => {1'b1, pkg::True}); + } + endgroup +endclass +==== diff --git a/crates/vlog_formatter/tests/verification.rs b/crates/vlog_formatter/tests/verification.rs index 0cc6438..fcf36d8 100644 --- a/crates/vlog_formatter/tests/verification.rs +++ b/crates/vlog_formatter/tests/verification.rs @@ -798,14 +798,13 @@ fn an_instantiation_list_directive_may_still_be_reindented() { // Class-scope blocks (`docs/features/classes/README.md`, // `docs/features/constraint-bodies/README.md`). // -// A `covergroup` body is still copied out of the source by span; a -// `constraint` body is laid out from a real tree since the -// `constraint-bodies` round, and a body the grammar does not know still -// falls back to the byte-for-byte capture. Either way the net must see every -// token inside the block. `verify.rs` was **not** widened for this round — -// nothing in it knows constraints exist — and these are the invariant-#4 -// tests that say so: each pair is a change a re-layout could plausibly be -// mistaken for, asserted refused. +// Both a `constraint` body and a `covergroup` body are laid out from a real +// tree since rounds 1 and 2 of this wave, and a body the grammar does not +// know still falls back to the byte-for-byte capture. Either way the net must +// see every token inside the block. `verify.rs` was **not** widened for +// either round — nothing in it knows constraints or covergroups exist — and +// these are the invariant-#4 tests that say so: each pair is a change a +// re-layout could plausibly be mistaken for, asserted refused. // ---------------------------------------------------------------------- #[test] @@ -975,6 +974,154 @@ fn a_dropped_covergroup_label_is_rejected() { expect_divergence(input, output); } +/// A covergroup body wrapped in the class the corpus always writes it in. +fn covergroup_pair(before: &str, after: &str) -> (String, String) { + let wrap = |body: &str| format!("class c;\n covergroup g;\n{body}\n endgroup\nendclass\n"); + (wrap(before), wrap(after)) +} + +#[test] +fn a_covergroup_may_be_relaid_out() { + // The point of round 2: the body is re-spaced and re-indented, cover + // items and bins move to lines of their own, and the net still calls it + // the same token stream. + let input = "class c;\n covergroup g;cp:coverpoint a{bins z={0,1};bins w=default;}\n endgroup : g\nendclass\n"; + let output = format_source(input, &Config::default()).expect("must format"); + verify_equivalence(input, &output).expect("a re-layout is not a change"); + let again = format_source(&output, &Config::default()).expect("must format again"); + verify_convergence(&output, &again).expect("and it is a fixed point"); +} + +#[test] +fn a_dropped_bins_qualifier_is_rejected() { + // `ignore_bins` and `illegal_bins` mean different things from `bins`, and + // `wildcard` changes which values a bin matches. None may be normalized. + let (input, output) = covergroup_pair( + " cp: coverpoint a { ignore_bins z = {0}; }", + " cp: coverpoint a { bins z = {0}; }", + ); + expect_divergence(&input, &output); + let (input, output) = covergroup_pair( + " cp: coverpoint a { wildcard bins z = {4'b1??1}; }", + " cp: coverpoint a { bins z = {4'b1??1}; }", + ); + expect_divergence(&input, &output); +} + +#[test] +fn a_dropped_bin_array_marker_is_rejected() { + // `bins b[] = {0, 1};` declares one auto-sized bin *per value*; `bins b = + // {0, 1};` declares one bin covering both values. Dropping the `[]` + // changes what the covergroup counts, so it may not be normalized away. + let (input, output) = covergroup_pair( + " cp: coverpoint a { bins z[] = {0, 1}; }", + " cp: coverpoint a { bins z = {0, 1}; }", + ); + expect_divergence(&input, &output); + // And a fixed array size silently widened is the same class of change. + let (input, output) = covergroup_pair( + " cp: coverpoint a { bins z[2] = {0, 1}; }", + " cp: coverpoint a { bins z[4] = {0, 1}; }", + ); + expect_divergence(&input, &output); +} + +#[test] +fn a_reversed_transition_arrow_is_rejected() { + let (input, output) = covergroup_pair( + " cp: coverpoint a { bins t = (0 => 1); }", + " cp: coverpoint a { bins t = (1 => 0); }", + ); + expect_divergence(&input, &output); +} + +#[test] +fn a_changed_transition_repetition_is_rejected() { + // `[*3]`, `[->3]` and `[=3]` are three different bins. + let (input, output) = covergroup_pair( + " cp: coverpoint a { bins t = (1'b0[*3] => 1'b1); }", + " cp: coverpoint a { bins t = (1'b0[->3] => 1'b1); }", + ); + expect_divergence(&input, &output); +} + +#[test] +fn a_dropped_binsof_negation_is_rejected() { + let (input, output) = covergroup_pair( + " cr: cross a, b { bins s = binsof(a) && !binsof(b); }", + " cr: cross a, b { bins s = binsof(a) && binsof(b); }", + ); + expect_divergence(&input, &output); + // And a dropped `intersect` set. + let (input, output) = covergroup_pair( + " cr: cross a, b { bins s = binsof(a) intersect {0}; }", + " cr: cross a, b { bins s = binsof(a); }", + ); + expect_divergence(&input, &output); +} + +#[test] +fn a_dropped_covergroup_iff_is_rejected() { + let (input, output) = + covergroup_pair(" cp: coverpoint a iff (en);", " cp: coverpoint a;"); + expect_divergence(&input, &output); + let (input, output) = covergroup_pair( + " cp: coverpoint a { bins z = {0} iff (en); }", + " cp: coverpoint a { bins z = {0}; }", + ); + expect_divergence(&input, &output); +} + +#[test] +fn a_moved_coverpoint_label_is_rejected() { + let (input, output) = covergroup_pair( + " cp_a: coverpoint a;\n cp_b: coverpoint b;", + " cp_b: coverpoint a;\n cp_a: coverpoint b;", + ); + expect_divergence(&input, &output); +} + +#[test] +fn a_comment_moved_across_a_covergroup_brace_is_rejected() { + let (input, output) = covergroup_pair( + " cp: coverpoint a {\n bins z = {0};\n // why\n }", + " cp: coverpoint a {\n bins z = {0};\n }\n // why", + ); + expect_divergence(&input, &output); +} + +#[test] +fn a_dropped_option_assignment_is_rejected() { + let (input, output) = + covergroup_pair(" option.per_instance = 1;\n coverpoint a;", " coverpoint a;"); + expect_divergence(&input, &output); + // And `option` swapped for `type_option`, which is a different setting. + let (input, output) = covergroup_pair(" option.weight = 1;", " type_option.weight = 1;"); + expect_divergence(&input, &output); +} + +#[test] +fn a_default_sequence_flattened_to_a_default_is_rejected() { + let (input, output) = covergroup_pair( + " cp: coverpoint a { bins d = default sequence; }", + " cp: coverpoint a { bins d = default; }", + ); + expect_divergence(&input, &output); +} + +#[test] +fn a_dropped_covergroup_sample_argument_is_rejected() { + let input = "class c;\n covergroup g with function sample (int a, int b);\n coverpoint a;\n endgroup\nendclass\n"; + let output = "class c;\n covergroup g with function sample (int a);\n coverpoint a;\n endgroup\nendclass\n"; + expect_divergence(input, output); +} + +#[test] +fn a_reordered_cross_operand_list_is_rejected() { + let (input, output) = covergroup_pair(" cr: cross a, b, c;", " cr: cross a, c, b;"); + expect_divergence(&input, &output); +} + #[test] fn a_changed_parameterized_type_argument_is_rejected() { let input = "class c;\n port_t #(bit [31:0]) p;\nendclass\n"; @@ -1790,3 +1937,268 @@ fn escaped_identifiers_survive_a_real_format_run() { assert!(out.ends_with("endmodule : \\my-mod\n"), "{out}"); assert!(!out.contains(" \n"), "no trailing whitespace: {out}"); } + +// ---------------------------------------------------------------------- +// The covergroup gap fuzzer +// +// A comment the AST does not keep is a comment the formatter cannot print, +// and `format_source`'s own token check then refuses the whole file — hard +// invariant #3 by way of #1. Guessing at a list of slots is how the seventh +// one ships, so `covergroup-bodies` asked the question exhaustively from day +// one, the way `constraint-bodies` learned to after its QA rework: put a +// `/*C*/` in **every** inter-token gap of every fixture and demand +// `format_source` succeed and be idempotent for each. +// +// See `docs/features/covergroup-bodies/README.md` for the classification of +// the gaps that still fail: every one of them is in shared name or expression +// machinery that fails identically outside a covergroup, filed as +// `docs/topo.md` §2.9-22. +// ---------------------------------------------------------------------- + +/// The covergroup sub-grammar, comment-free, one shape per fixture. +const COVERGROUP_FIXTURES: &[&str] = &[ + "class c;\n covergroup cg;\n coverpoint a;\n endgroup\nendclass\n", + "class c;\n covergroup cg (bit [3:0] a, int n) with function sample (bit [31:0] addr);\n cp: coverpoint addr;\n endgroup : cg\nendclass\n", + "module m;\n covergroup cg @(posedge clk);\n coverpoint x;\n endgroup\nendmodule\n", + "class c;\n covergroup cg;\n cp: coverpoint a iff (en) {\n wildcard bins w[4] = {4'b1??1};\n ignore_bins ig = {2, 3};\n illegal_bins bad = default;\n }\n endgroup\nendclass\n", + "class c;\n covergroup cg;\n cp: coverpoint a {\n bins seq = default sequence;\n bins t = (0 => 1, 2 => 3), (4 => 5);\n }\n endgroup\nendclass\n", + "class c;\n covergroup cg;\n cp: coverpoint a {\n bins r = (1'b0[*1:10] => 1'b1[->2] => 1'b0[=1]);\n }\n endgroup\nendclass\n", + "class c;\n covergroup cg;\n cr: cross cp_a, cp_b {\n bins sel = binsof(cp_a) intersect {0, [1:2]} && !binsof(cp_b);\n }\n endgroup\nendclass\n", + "class c;\n covergroup cg;\n option.per_instance = 1;\n type_option.weight = 5;\n coverpoint x;\n endgroup\nendclass\n", + "class c;\n covergroup cg;\n cp: coverpoint a {\n bins e[] = cp_x with (item % 2 == 0);\n bins v = {[0:$]} iff (en);\n }\n endgroup\nendclass\n", + "class c;\n local covergroup cg;\n cp: coverpoint a;\n cr: cross a, b;\n ;\n endgroup : cg;\nendclass\n", +]; + +/// Every byte offset a comment may be written at: the start of each token, +/// plus the end of the last one. +fn gaps(src: &str) -> Vec { + let tokens = vlog_parser::tokenize(src).expect("the fixture lexes"); + let mut out: Vec = Vec::new(); + let mut last = 0usize; + for t in &tokens { + if t.text.is_empty() && t.span.start == t.span.end { + continue; + } + out.push(t.span.start as usize); + last = t.span.end as usize; + } + out.push(last); + out.sort_unstable(); + out.dedup(); + out +} + +/// The fixtures with a `/*C*/` in one gap each, and whether that one formats +/// and round-trips. +fn failing_gaps() -> Vec { + let mut failed = Vec::new(); + for src in COVERGROUP_FIXTURES { + for at in gaps(src) { + let mut probed = String::with_capacity(src.len() + 8); + probed.push_str(&src[..at]); + probed.push_str(" /*C*/ "); + probed.push_str(&src[at..]); + let ok = match format_source(&probed, &Config::default()) { + Ok(out) => format_source(&out, &Config::default()).is_ok_and(|two| two == out), + Err(_) => false, + }; + if !ok { + failed.push(format!("{:?} … {:?}", &probed[..at + 7], &probed[at + 7..])); + } + } + } + failed +} + +#[test] +fn a_comment_in_every_covergroup_gap_still_formats() { + let total: usize = COVERGROUP_FIXTURES.iter().map(|s| gaps(s).len()).sum(); + let failed = failing_gaps(); + // The bar, stated out loud: of the fixtures' inter-token gaps, exactly + // these fail, every one of them in shared machinery that fails + // identically outside a covergroup (`docs/topo.md` §2.9-22) — the + // qualifier run, `[` index expressions, `class`/`package` headers, + // declarator dimensions and `parse_value_range`. A change that adds one + // fails here with the offending source printed. + assert_eq!( + (total, failed.len()), + (EXPECTED_GAPS, EXPECTED_FAILING_GAPS), + "the covergroup gap fuzzer moved:\n{}", + failed.join("\n") + ); +} + +/// Inter-token gaps across [`COVERGROUP_FIXTURES`]. +const EXPECTED_GAPS: usize = 329; + +/// How many of them a `/*C*/` still breaks. Every one is classified by +/// [`shared_machinery_analogues`], whose sources are the same slots written +/// **outside** a covergroup — and which fail identically there: +/// +/// | shape | n | owner | +/// |---|---|---| +/// | `class /*C*/ c` / `class c /*C*/ ;` | 18 | the class header | +/// | `module /*C*/ m` / `module m /*C*/ ;` | 2 | the module header | +/// | a `tf_port_list` type, its dimensions and its name | 13 | `parse_tf_ports` | +/// | `endgroup /*C*/ : g` / `endgroup : /*C*/ g` | 4 | `parse_label` | +/// | `@ /*C*/ (` / `@(posedge /*C*/ clk)` | 2 | `parse_sens_list` | +/// | `[ /*C*/ 0 : 3 /*C*/ ]` | 8 | `parse_value_range` | +/// | `option /*C*/ . /*C*/ per_instance` | 4 | member expressions | +/// | `local /*C*/ covergroup` | 1 | `take_member_prefix` | +const EXPECTED_FAILING_GAPS: usize = 52; + +/// The same slots, written outside any covergroup. +/// +/// Every one of them is a *pre-existing* comment-drop in shared name, +/// declaration or expression machinery — `docs/topo.md` §2.9-22 — and none of +/// it is this round's to fix. This test is the classification, written down: +/// if one of these starts working, the fuzzer's count above moves in the same +/// commit, and both are updated together. +const SHARED_MACHINERY_ANALOGUES: &[(&str, &str)] = &[ + ( + "class /*C*/ c", + "class /*C*/ c; +endclass +", + ), + ( + "class c /*C*/ ;", + "class c /*C*/ ; +endclass +", + ), + ( + "module /*C*/ m", + "module /*C*/ m; +endmodule +", + ), + ( + "module m /*C*/ ;", + "module m /*C*/ ; +endmodule +", + ), + ( + "a tf port's type", + "class c; + function void f(bit /*C*/ [3:0] a); + endfunction +endclass +", + ), + ( + "a tf port's dimension", + "class c; + function void f(bit [ /*C*/ 3:0] a); + endfunction +endclass +", + ), + ( + "a tf port's name", + "class c; + function void f(bit [3:0] /*C*/ a); + endfunction +endclass +", + ), + ( + "an untyped tf port's name", + "class c; + function void f(int /*C*/ n); + endfunction +endclass +", + ), + ( + "endfunction /*C*/ : f", + "class c; + function void f(); + endfunction /*C*/ : f +endclass +", + ), + ( + "endfunction : /*C*/ f", + "class c; + function void f(); + endfunction : /*C*/ f +endclass +", + ), + ( + "always @ /*C*/ (", + "module m; + always @ /*C*/ (posedge clk) x <= 1; +endmodule +", + ), + ( + "always @(posedge /*C*/ clk)", + "module m; + always @(posedge /*C*/ clk) x <= 1; +endmodule +", + ), + ( + "a value range's open", + "module m; + assign y = a inside {[ /*C*/ 0:3]}; +endmodule +", + ), + ( + "a value range's colon", + "module m; + assign y = a inside {[0 /*C*/ :3]}; +endmodule +", + ), + ( + "a value range's close", + "module m; + assign y = a inside {[0:3 /*C*/ ]}; +endmodule +", + ), + ( + "a member access's dot", + "module m; + assign y = a /*C*/ .b; +endmodule +", + ), + ( + "a member access's name", + "module m; + assign y = a. /*C*/ b; +endmodule +", + ), + ( + "a member qualifier run", + "class c; + local /*C*/ function void f(); + endfunction +endclass +", + ), +]; + +#[test] +fn the_gaps_the_fuzzer_still_fails_fail_outside_a_covergroup_too() { + let working: Vec<&str> = SHARED_MACHINERY_ANALOGUES + .iter() + .filter(|(_, src)| { + format_source(src, &Config::default()) + .is_ok_and(|out| format_source(&out, &Config::default()).is_ok_and(|t| t == out)) + }) + .map(|(name, _)| *name) + .collect(); + assert!( + working.is_empty(), + "these shared-machinery slots now keep their comment, so the covergroup \ + fuzzer's expected count above is stale: {working:?}" + ); +} diff --git a/crates/vlog_linter/src/signals.rs b/crates/vlog_linter/src/signals.rs index 8cf31d9..d0acae1 100644 --- a/crates/vlog_linter/src/signals.rs +++ b/crates/vlog_linter/src/signals.rs @@ -401,7 +401,13 @@ impl Scanner { // verbatim leaf — would now throw that away. A body that fell // back to a verbatim capture is still an `ItemKind::Verbatim` // and keeps the opaque posture below. - ItemKind::Constraint(_) => {} + // A covergroup samples its operands and drives nothing, so it + // records nothing here either: since `covergroup-bodies` the + // names inside it are ordinary resolved references, which + // `finish` counts as reads. A covergroup that fell back to a + // verbatim capture is still an `ItemKind::Verbatim` and keeps the + // opaque posture below. + ItemKind::Constraint(_) | ItemKind::Covergroup(_) => {} // Nothing here can be read: a macro is not expanded, a directive // is not evaluated, a verbatim block is not modelled, and an // error leaf did not parse. Every name they mention is dropped. diff --git a/crates/vlog_linter/src/visit.rs b/crates/vlog_linter/src/visit.rs index 80fa770..b8db729 100644 --- a/crates/vlog_linter/src/visit.rs +++ b/crates/vlog_linter/src/visit.rs @@ -45,6 +45,13 @@ fn items(list: &[Item], f: &mut dyn FnMut(&Item)) { // name in the body. Recorded as its own arm rather than left to // the catch-all so the next reader does not re-derive it. ItemKind::Constraint(_) => {} + // A covergroup body holds cover items — coverpoints, crosses, + // bins, options — and neither an `Item` nor a `Stmt`, so there is + // nothing here for an item or statement walk to descend into + // either. The rules that need to see inside read the reference + // table, which since `covergroup-bodies` reaches every name a + // covergroup samples. + ItemKind::Covergroup(_) => {} ItemKind::GenFor(gen_for) => gen_block(&gen_for.body, f), ItemKind::GenCase(gen_case) => { for case_item in &gen_case.items { diff --git a/crates/vlog_linter/tests/cases/covergroups.lint b/crates/vlog_linter/tests/cases/covergroups.lint new file mode 100644 index 0000000..a1c1da2 --- /dev/null +++ b/crates/vlog_linter/tests/cases/covergroups.lint @@ -0,0 +1,49 @@ +# The linter's posture on covergroup bodies, after TODO.md §21 gave them a +# real AST. See docs/features/covergroup-bodies/README.md. + +# undriven-net now sees a read written inside a covergroup: the sampled +# expression is an ordinary resolved reference, so a net read only there is no +# longer invisible. Before the covergroup-bodies round the whole block was an +# opaque span and `w` had zero reads, so it was skipped. +#select undriven-net +module m; + wire w; +//^ 8 undriven-net + covergroup cg; + cp: coverpoint w; + endgroup +endmodule +==== +# a covergroup the grammar does not know is opaque again: the names inside it +# bind nothing, exactly as they did before the round +#select undriven-net +module m; + wire w; + covergroup cg; + cp: coverpoint w `GPR_BIN_TYPES + endgroup +endmodule +==== +# empty-item does not fire on a null *cover* item, nor on a null bin item: a +# `;` inside a covergroup body is a CoverItemKind::Empty, not an ItemKind::Empty +#select empty-item +module m; + covergroup cg; + cp: coverpoint a { + bins v = {1}; + ; + } + ; + endgroup +endmodule +==== +# an item walk still reaches a class body past a covergroup +#select explicit-parameter-storage-type +class item; + rand int n; + covergroup cg; + cp: coverpoint n; + endgroup + localparam B = 2; +//^ 14 explicit-parameter-storage-type +endclass diff --git a/crates/vlog_parser/src/ast.rs b/crates/vlog_parser/src/ast.rs index 22c7610..cdf5a0f 100644 --- a/crates/vlog_parser/src/ast.rs +++ b/crates/vlog_parser/src/ast.rs @@ -173,6 +173,13 @@ pub struct SourceFile { /// and nothing in the tree depends on it. See /// `docs/features/constraint-bodies/README.md`. pub constraint_fallbacks: u32, + /// How many `covergroup` declarations were parsed into a + /// [`ItemKind::Covergroup`], and how many did not fit the covergroup + /// grammar and were captured verbatim instead. The pair is the census + /// `docs/features/covergroup-bodies/README.md` reports: diagnostic only, + /// and nothing in the tree depends on either. + pub covergroups: u32, + pub covergroup_fallbacks: u32, } #[derive(Debug)] @@ -256,13 +263,22 @@ pub enum ItemKind { /// since the `classes` round, byte for byte. See /// `docs/features/constraint-bodies/README.md`. Constraint(ConstraintDecl), + /// `covergroup g ... endgroup` and everything inside it (IEEE 1800 §19.3). + /// + /// A body the covergroup grammar does not recognise never reaches this + /// variant: [`Parser::parse_covergroup`](crate::parser::Parser) rewinds + /// and produces the [`ItemKind::Verbatim`] leaf covergroups had before + /// this round, byte for byte. See + /// `docs/features/covergroup-bodies/README.md`. + Covergroup(Box), /// A block lucisv deliberately does not model, kept byte-for-byte: - /// a `covergroup ... endgroup`, a concurrent assertion + /// a concurrent assertion /// (`assert property ( ... );`), a `property`/`sequence` declaration — - /// and a `constraint` whose body did not fit the grammar. See - /// `docs/features/classes/README.md`, - /// `docs/features/assertions/README.md` and - /// `docs/features/constraint-bodies/README.md` for why each one is + /// and a `constraint` or a `covergroup` whose body did not fit the + /// grammar. See `docs/features/classes/README.md`, + /// `docs/features/assertions/README.md`, + /// `docs/features/constraint-bodies/README.md` and + /// `docs/features/covergroup-bodies/README.md` for why each one is /// verbatim. Verbatim(RawText), Defparam(Vec<(Expr, Expr)>), @@ -1882,3 +1898,408 @@ pub struct DistItem { /// Code extent of the element. pub span: TextRange, } + +// ---------------------------------------------------------------------- +// Covergroups (IEEE 1800 §19) +// ---------------------------------------------------------------------- + +/// A `covergroup g (args) with function sample (args); ... endgroup : g` +/// declaration and everything inside it (IEEE 1800 §19.3). +#[derive(Debug)] +pub struct CovergroupDecl { + /// The member qualifiers written before the keyword (`local`, `static`, + /// `protected`), in source order. + pub qualifiers: Vec, + /// Comments written between the `covergroup` keyword and the name. + pub before_name: Vec, + pub name: Name, + /// Comments written between the name and the `(` of the formal list. + /// Claimed only when that `(` was really written. + pub before_args: Vec, + /// The `(bit [3:0] a)` formal argument list. `None` when the source wrote + /// no parens at all — printing an empty `()` back would be a token-stream + /// change the safety net refuses. + pub args: Option>, + /// The `coverage_event` of the header. IEEE 1800 §19.3 makes the two + /// spellings alternatives, so one field holds whichever was written. + pub event: Option, + /// Comments written between the header's last token and its `;`. + pub before_semi: Vec, + pub items: Vec, + /// Comments written after the last item and before `endgroup`. + pub dangling: Vec, + /// The label of `endgroup : g`. + pub end_label: Option, + /// Comments written between `endgroup` (or its label) and a stray `;`. + pub before_end_semi: Vec, + /// A stray `;` written after `endgroup`. Both spellings occur in real + /// code, so the formatter reproduces whichever was written. + pub end_semi: bool, +} + +/// The `coverage_event` of a covergroup header (IEEE 1800 §19.3). +#[derive(Debug)] +pub enum CoverageEvent { + /// `with function sample ( tf_port_list )` — the covergroup is sampled by + /// an explicit call rather than by an event. + Sample(Box), + /// `@(posedge clk)`, `@ev` — an ordinary clocking event, read by the very + /// parser an `always @(...)` uses. + Clocking { + /// Comments written between the header and the `@`. + before: Vec, + sens: SensList, + }, +} + +/// The `with function sample (...)` half of a covergroup header. +/// +/// `sample` is matched **by text**, not reserved: see +/// `docs/features/covergroup-bodies/README.md`. +#[derive(Debug)] +pub struct SampleFn { + /// Comments written between the header and the `with`. + pub before_with: Vec, + /// Comments written between `with` and `function`. + pub after_with: Vec, + /// Comments written between `function` and `sample`. + pub after_function: Vec, + /// The word `sample`, with its span — a method of the covergroup, so it + /// gets a name of its own. + pub name: Name, + /// Comments written between `sample` and the `(`. + pub before_args: Vec, + /// True when the source wrote `( ... )` at all. + pub has_parens: bool, + pub args: Vec, +} + +/// One `coverage_spec_or_option` of a covergroup body. +#[derive(Debug)] +pub struct CoverItem { + pub meta: Meta, + pub kind: CoverItemKind, + /// Comments written between the item's last token and the `;` that ends + /// it. Always empty for a kind [`CoverItemKind::takes_semi`] is false for. + pub before_semi: Vec, + /// Code extent of the item, its `;` or `}` included. + pub span: TextRange, +} + +#[derive(Debug)] +pub enum CoverItemKind { + Coverpoint(Box), + Cross(Box), + /// `option.per_instance = 1;` / `type_option.weight = 5;` + Option(Box), + /// A compiler directive, or a macro invocation, standing where a cover + /// item belongs — the same posture directives keep at item and statement + /// position: passed through, never evaluated. + Directive(RawText), + /// A lone `;`. + Empty, +} + +impl CoverItemKind { + /// True for the items a `;` terminates. + /// + /// A coverpoint or a cross that wrote a `{ ... }` body ends at the brace; + /// one that did not ends at a `;`. One answer, read by the parser (which + /// consumes the `;`) and by the formatter (which writes it back), so the + /// two can never disagree about who owns it — the rule + /// [`ConstraintItemKind::takes_semi`] states for constraints. + pub fn takes_semi(&self) -> bool { + match self { + CoverItemKind::Coverpoint(cp) => cp.body.is_none(), + CoverItemKind::Cross(c) => c.body.is_none(), + CoverItemKind::Option(_) => true, + CoverItemKind::Directive(_) | CoverItemKind::Empty => false, + } + } +} + +/// `[label :] coverpoint expr [iff (expr)] [{ bins }]` (IEEE 1800 §19.5). +#[derive(Debug)] +pub struct CoverpointDecl { + /// The `cp_name :` label. `None` for an unlabelled coverpoint, which + /// declares nothing. + pub label: Option, + /// Comments written between the `coverpoint` keyword and the expression. + pub after_kw: Vec, + pub expr: Expr, + pub iff: Option>, + /// Comments written between the header and the `{` of a body. + pub before_body: Vec, + pub body: Option, +} + +/// `[label :] cross a, b [iff (expr)] [{ bins }]` (IEEE 1800 §19.6). +#[derive(Debug)] +pub struct CrossDecl { + pub label: Option, + /// Comments written between the `cross` keyword and the first operand. + pub after_kw: Vec, + /// The crossed coverpoints, named or written as expressions. + pub items: Vec, + pub iff: Option>, + /// Comments written between the header and the `{` of a body. + pub before_body: Vec, + pub body: Option, +} + +/// The `name :` in front of a coverpoint or a cross — the name the covergroup +/// declares for it, and what `cg.cp` reaches. +#[derive(Debug)] +pub struct CoverLabel { + pub name: Name, + /// Comments written on either side of the `:`. + pub comments: Box, +} + +/// The `iff ( expr )` guard a coverpoint, a cross or a bin may carry. +#[derive(Debug)] +pub struct CoverIff { + /// Comments written between the construct and the `iff`. + pub before_kw: Vec, + /// Comments written between `iff` and the `(`. + pub after_kw: Vec, + /// Comments written just inside the `(`. + pub after_open: Vec, + /// Comments written just before the `)`. + pub before_close: Vec, + pub expr: Expr, +} + +/// The `{ ... }` body of a coverpoint or a cross: bins and options. +#[derive(Debug)] +pub struct CoverBody { + pub items: Vec, + /// Comments written after the last item and before the closing `}`. + pub dangling: Vec, + /// Code extent of the body, its braces included. + pub span: TextRange, +} + +/// One `bins_or_options` of a coverpoint or cross body. +#[derive(Debug)] +pub struct BinItem { + pub meta: Meta, + pub kind: BinItemKind, + /// Comments written between the item's last token and its `;`. + pub before_semi: Vec, + /// Code extent of the item, its `;` included. + pub span: TextRange, +} + +#[derive(Debug)] +pub enum BinItemKind { + Bin(Box), + Option(Box), + Directive(RawText), + Empty, +} + +impl BinItemKind { + /// True for the items a `;` terminates — everything but a directive, + /// which carries none, and a null item, which *is* its `;`. + pub fn takes_semi(&self) -> bool { + matches!(self, BinItemKind::Bin(_) | BinItemKind::Option(_)) + } +} + +/// `option.per_instance = 1;` / `type_option.weight = 5;` (IEEE 1800 §19.7). +/// +/// The target is kept as the expression it is written as, rather than split +/// into a keyword and a path: an option name resolves to nothing lucisv +/// models, and the expression printer already writes a dotted chain back +/// exactly as it was written. See `docs/features/covergroup-bodies/README.md`. +#[derive(Debug)] +pub struct OptionAssign { + /// `option.per_instance` / `type_option.weight`, as written. + pub target: Expr, + /// Comments written on either side of the `=`. + pub comments: Box, + pub value: Expr, +} + +/// `[wildcard] bins name[[expr]] = spec [with (expr)] [iff (expr)];` +/// (IEEE 1800 §19.5.1) — and the `bins name = select_expression` of a cross +/// body (§19.6.1), which differs only in what the spec may be. +#[derive(Debug)] +pub struct BinDecl { + pub wildcard: bool, + /// Comments written between `wildcard` and the bins keyword. + pub after_wildcard: Vec, + pub kind: BinKind, + /// Comments written between the bins keyword and the name. + pub before_name: Vec, + pub name: Name, + /// The `[]` or `[expr]` written after the name — an array of bins. + pub array: Option>, + /// Comments written on either side of the `=`. + pub eq_comments: Box, + pub spec: BinSpec, + /// `with ( expr )` written after the spec. + pub with_expr: Option>, + pub iff: Option>, +} + +/// Which of the three bins keywords was written. They mean different things, +/// so they are never normalized into each other. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BinKind { + Bins, + IgnoreBins, + IllegalBins, +} + +impl BinKind { + /// The keyword as written. + pub fn as_str(self) -> &'static str { + match self { + BinKind::Bins => "bins", + BinKind::IgnoreBins => "ignore_bins", + BinKind::IllegalBins => "illegal_bins", + } + } +} + +/// The `[]` or `[expr]` after a bin name: an array of bins, sized or not. +#[derive(Debug)] +pub struct BinArray { + /// Comments written between the bin name and the `[`. + pub before: Vec, + /// Comments written just inside the `[` and just before the `]`. + pub comments: Box, + /// `None` for the unsized `[]` spelling. + pub size: Option, +} + +/// What a bin is defined as. +#[derive(Debug)] +pub enum BinSpec { + /// `= { 0, [1:3], $ }` — a covergroup range list. + Values(Vec), + /// `= (a => b), (c => d)` — one or more transition sets + /// (IEEE 1800 §19.5.1.2). + Transitions(Vec), + /// `= default`. + Default, + /// `= default sequence`. + DefaultSequence { + /// Comments written between `default` and `sequence`. + comments: Vec, + }, + /// `= cp_name`, and the `binsof(a) intersect {0} && !binsof(b)` select + /// expression of a cross body (IEEE 1800 §19.6.1). + Select(SelectExpr), +} + +/// The `with ( expr )` filter written after a bin's values +/// (IEEE 1800 §19.5.1.1). `item` inside it is the implicit iteration +/// variable, which declares nothing. +#[derive(Debug)] +pub struct BinWith { + /// Comments written between the spec and the `with`. + pub before_kw: Vec, + /// Comments written between `with` and the `(`. + pub after_kw: Vec, + /// Comments written just inside the `(`. + pub after_open: Vec, + /// Comments written just before the `)`. + pub before_close: Vec, + pub expr: Expr, +} + +/// One `( trans_set )` of a transition bin: `(a => b, c => d)`. +#[derive(Debug)] +pub struct TransSet { + pub meta: Meta, + /// The `=>`-separated ranges. Always at least one. + pub ranges: Vec, + /// Comments written after the last range and before the `)`. + pub dangling: Vec, + /// Code extent of the set, its parens included. + pub span: TextRange, +} + +/// One `trans_range_list` of a [`TransSet`]: a comma-separated value list +/// with an optional repetition. +#[derive(Debug)] +pub struct TransRange { + /// Comments written before the `=>` that introduces this range, and after + /// it. Both empty on the first range of a set, which no `=>` precedes. + pub arrow_comments: Box, + pub items: Vec, + pub repeat: Option>, +} + +/// `[* 3]`, `[* 1:$]`, `[-> 2]`, `[= 1]` — a transition's repetition +/// (IEEE 1800 §19.5.1.2). The three operators mean different things, so each +/// is printed back exactly as written. +#[derive(Debug)] +pub struct TransRepeat { + /// Comments written between the range and the `[`. + pub before: Vec, + /// Comments written just inside the `[`, in front of the operator. + pub after_open: Vec, + /// `*`, `->` or `=`, without the brackets. + pub op: String, + /// Comments written just after that operator (`before`) and just before + /// the `]` (`after`). + pub comments: Box, + pub lo: Expr, + /// The `hi` of a `[* lo:hi]` range. + pub hi: Option, + /// Comments written on either side of the `:` of that range. + pub colon_comments: Box, +} + +/// A cross bin's `select_expression` (IEEE 1800 §19.6.1). +#[derive(Debug)] +pub enum SelectExpr { + /// `binsof ( name ) [ intersect { ranges } ]`. + Binsof(Box), + /// `! select_condition`. + Not { + /// Comments written between the `!` and its operand. + comments: Vec, + expr: Box, + }, + /// `a && b`, `a || b`. Read left-associatively with one precedence + /// level: lucisv evaluates neither operator and prints no parentheses of + /// its own, so the shape of the tree cannot reach the output. + Binary { + lhs: Box, + op: String, + /// Comments written on either side of the operator. + comments: Box, + rhs: Box, + }, + /// `( select_expression )`. + Paren { + /// Comments written just inside either paren. + comments: Box, + expr: Box, + }, + /// A plain coverpoint name: the `= cp_name` spelling of a coverpoint bin, + /// and a cross bin's bare cross-set expression. + Expr(Expr), +} + +/// `binsof ( name ) [ intersect { ranges } ]` — one `select_condition`. +#[derive(Debug)] +pub struct BinsofSel { + /// Comments written between `binsof` and the `(`. + pub after_kw: Vec, + /// Comments written just inside the `(`. + pub after_open: Vec, + /// Comments written just before the `)`. + pub before_close: Vec, + pub name: Expr, + /// Comments written between the `)` and `intersect`. + pub before_intersect: Vec, + /// Comments written between `intersect` and its `{`. + pub after_intersect: Vec, + pub intersect: Option>, +} diff --git a/crates/vlog_parser/src/parser.rs b/crates/vlog_parser/src/parser.rs index b9c2f41..cdf3760 100644 --- a/crates/vlog_parser/src/parser.rs +++ b/crates/vlog_parser/src/parser.rs @@ -277,14 +277,25 @@ pub struct Parser<'a> { /// Constraint bodies that did not fit the constraint grammar and were /// captured verbatim instead; see [`SourceFile::constraint_fallbacks`]. constraint_fallbacks: u32, + /// Covergroups parsed into a [`ItemKind::Covergroup`], and covergroups + /// that did not fit the grammar and were captured verbatim instead; see + /// [`SourceFile::covergroups`]. + covergroups: u32, + covergroup_fallbacks: u32, + /// While a covergroup bin's spec is being read, a postfix `with ( ... )` + /// is the **bin's** own filter (IEEE 1800 §19.5.1.1), not an array + /// method's iterator argument, so the expression parser must stop in + /// front of it. Set and cleared around that one operand, and never left + /// set on an error path. + no_with: bool, } /// Everything a speculative parse may move, so that a failed one can be put /// back exactly where it started. /// -/// Only [`Parser::parse_constraint`] and [`Parser::parse_with_constraint`] -/// use it, and only to retry the *same* bytes down the pre-existing verbatim -/// path. The token vector's own `leading` buckets are deliberately not +/// Only [`Parser::parse_constraint`], [`Parser::parse_with_constraint`] and +/// [`Parser::parse_covergroup`] use it, and only to retry the *same* bytes +/// down the pre-existing verbatim path. The token vector's own `leading` buckets are deliberately not /// snapshotted: a retry that drained one has already decided to swallow those /// bytes whole, and `verbatim_since` drops every comment that falls inside /// the captured span. @@ -346,7 +357,14 @@ pub(crate) fn error_file(source: &str) -> SourceFile { let span = TextRange::new(0, source.len() as u32); let raw = RawText { text: source.to_string(), col: 1, span }; let item = Item { meta: Meta::default(), kind: ItemKind::Error(raw), span }; - SourceFile { items: vec![item], dangling: Vec::new(), span, constraint_fallbacks: 0 } + SourceFile { + items: vec![item], + dangling: Vec::new(), + span, + constraint_fallbacks: 0, + covergroups: 0, + covergroup_fallbacks: 0, + } } /// True when `t` is one of the strength keywords a drive strength names. @@ -376,6 +394,20 @@ fn word_at(t: &Token, word: &str) -> bool { t.kind == TokenKind::Ident && t.text == word } +/// Which of the three bins keywords `t` spells, if any. All three are matched +/// by text rather than reserved, for the reason [`word_at`] gives. +fn bin_kind_at(t: &Token) -> Option { + if t.kind != TokenKind::Ident { + return None; + } + match t.text.as_str() { + "bins" => Some(BinKind::Bins), + "ignore_bins" => Some(BinKind::IgnoreBins), + "illegal_bins" => Some(BinKind::IllegalBins), + _ => None, + } +} + /// The word a compiler-directive token spells, without its backtick and /// without its argument: `` `ifndef FOO `` is `"ifndef"`. The empty string for /// anything that is not a directive token. @@ -531,6 +563,9 @@ impl<'a> Parser<'a> { source, diagnostics: Vec::new(), constraint_fallbacks: 0, + covergroups: 0, + covergroup_fallbacks: 0, + no_with: false, } } @@ -1432,7 +1467,14 @@ impl<'a> Parser<'a> { // The cursor is on the EOF token, whose empty span sits at the end of // the source, so this covers the whole file. let span = TextRange::new(0, self.cur().span.end); - Ok(SourceFile { items, dangling, span, constraint_fallbacks: self.constraint_fallbacks }) + Ok(SourceFile { + items, + dangling, + span, + constraint_fallbacks: self.constraint_fallbacks, + covergroups: self.covergroups, + covergroup_fallbacks: self.covergroup_fallbacks, + }) } /// Items nest through generate blocks and package bodies. Gated. @@ -1597,7 +1639,7 @@ impl<'a> Parser<'a> { "class" => self.parse_class().map(ItemKind::Class), "let" => self.parse_let().map(ItemKind::Let), "constraint" => self.parse_constraint(), - "covergroup" => self.parse_covergroup().map(ItemKind::Verbatim), + "covergroup" => self.parse_covergroup(), "assert" | "assume" | "cover" if self.at_concurrent_assertion() => { self.parse_concurrent_assertion().map(ItemKind::Verbatim) } @@ -1612,7 +1654,7 @@ impl<'a> Parser<'a> { "function" => self.parse_function().map(ItemKind::Function), "task" => self.parse_task().map(ItemKind::Task), "constraint" => self.parse_constraint(), - "covergroup" => self.parse_covergroup().map(ItemKind::Verbatim), + "covergroup" => self.parse_covergroup(), _ => self.parse_data_decl().map(ItemKind::DataDecl), } } @@ -2450,10 +2492,38 @@ impl<'a> Parser<'a> { Ok(ConstraintBody::Verbatim(self.verbatim_since(start, col))) } - /// `covergroup name ... endgroup [: label]`, kept as verbatim source, for - /// the same reason constraints are: coverpoints, bins and crosses are a - /// separate grammar with nothing to gain from canonical layout. - fn parse_covergroup(&mut self) -> PResult { + /// `[qualifiers] covergroup name [(args)] [coverage_event]; ... endgroup + /// [: label]` (IEEE 1800 §19.3). + /// + /// The body is **parsed**, exactly as a constraint's is since round 1 of + /// this wave: coverpoints, crosses, bins and options become real nodes, so + /// a rename of a sampled property reaches `coverpoint addr` and `cg.cp` is + /// a name that resolves. A covergroup that does not fit the grammar + /// rewinds and is captured exactly as every covergroup was before this + /// round — the flat token scan to `endgroup`, source bytes copied out by + /// span, an [`ItemKind::Verbatim`] leaf whose `col` re-indent contract the + /// formatter already honours. See + /// `docs/features/covergroup-bodies/README.md`. + fn parse_covergroup(&mut self) -> PResult { + let mark = self.rewind_mark(); + match self.parse_covergroup_decl() { + Ok(decl) => { + self.covergroups += 1; + Ok(ItemKind::Covergroup(Box::new(decl))) + } + Err(_) => { + self.rewind_to(mark); + self.covergroup_fallbacks += 1; + self.parse_covergroup_verbatim().map(ItemKind::Verbatim) + } + } + } + + /// The pre-`covergroup-bodies` capture, unchanged, byte for byte: the + /// fallback [`Parser::parse_covergroup`] rewinds into, and the reason a + /// covergroup the grammar does not know still parses, formats and + /// round-trips exactly as it did in v0.27.0. + fn parse_covergroup_verbatim(&mut self) -> PResult { let start = self.here(); let col = self.cur().col; self.take_member_prefix(); @@ -2467,6 +2537,543 @@ impl<'a> Parser<'a> { Ok(self.verbatim_since(start, col)) } + /// A covergroup body. Gated, like every other body. + fn parse_covergroup_decl(&mut self) -> PResult { + self.enter()?; + let out = self.parse_covergroup_decl_inner(); + self.leave(); + out + } + + fn parse_covergroup_decl_inner(&mut self) -> PResult { + let qualifiers = self.take_member_prefix(); + self.expect_kw("covergroup")?; + let before_name = self.take_gap(); + let name = self.expect_name()?; + let before_args = self.take_before_open("("); + let args = if self.cur().is_sym("(") { Some(self.parse_tf_ports()?) } else { None }; + let event = self.parse_coverage_event()?; + let before_semi = self.gap_before(";"); + self.expect_sym(";")?; + let mut items = Vec::new(); + while !self.cur().is_kw("endgroup") { + if self.at_eof() { + return self.error("expected `endgroup`"); + } + items.push(self.parse_cover_item()?); + } + let dangling = self.take_dangling(); + // Strict, not [`Parser::expect_closer`]: an unclosed covergroup must + // *fail* here so the rewind puts the old flat scan back, which is what + // records the tolerant diagnostic — one message, from one place, and + // the same one v0.27.0 wrote. + self.expect_kw("endgroup")?; + let end_label = self.parse_label()?; + let before_end_semi = self.gap_before(";"); + let end_semi = self.eat_sym(";"); + Ok(CovergroupDecl { + qualifiers, + before_name, + name, + before_args, + args, + event, + before_semi, + items, + dangling, + end_label, + before_end_semi, + end_semi, + }) + } + + /// The `coverage_event` of a covergroup header: `with function sample + /// (...)` or a clocking event. `sample` is matched by text, for the + /// reason `soft` and `dist` are. + fn parse_coverage_event(&mut self) -> PResult> { + if self.cur().is_kw("with") { + let before_with = self.take_gap(); + self.bump(); + let after_with = self.take_gap(); + self.expect_kw("function")?; + let after_function = self.take_gap(); + if !word_at(self.cur(), "sample") { + return self.error("expected `sample`"); + } + let name = Name { text: self.cur().text.clone(), span: self.cur().span }; + self.bump(); + let before_args = self.take_before_open("("); + let has_parens = self.cur().is_sym("("); + let args = self.parse_tf_ports()?; + return Ok(Some(CoverageEvent::Sample(Box::new(SampleFn { + before_with, + after_with, + after_function, + name, + before_args, + has_parens, + args, + })))); + } + if self.cur().is_sym("@") { + let before = self.take_gap(); + self.bump(); + let sens = self.parse_sens_list()?; + return Ok(Some(CoverageEvent::Clocking { before, sens })); + } + Ok(None) + } + + fn parse_cover_item(&mut self) -> PResult { + let start = self.here(); + let mut meta = self.take_meta(); + let kind = self.parse_cover_item_kind()?; + // One place owns the terminating `;`, so one place owns the gap in + // front of it — the rule `parse_constraint_item` states. + let mut before_semi = Vec::new(); + if kind.takes_semi() { + before_semi = self.take_gap(); + self.expect_sym(";")?; + } + let span = self.span_from(start); + if meta.trailing.is_none() { + meta.trailing = self.take_trailing(); + } + Ok(CoverItem { meta, kind, before_semi, span }) + } + + fn parse_cover_item_kind(&mut self) -> PResult { + if self.cur().kind == TokenKind::Directive || self.at_macro_item() { + return Ok(CoverItemKind::Directive(self.take_raw_text())); + } + if self.eat_sym(";") { + return Ok(CoverItemKind::Empty); + } + if self.at_option_assign() { + return Ok(CoverItemKind::Option(Box::new(self.parse_option_assign()?))); + } + // `name : coverpoint ...` / `name : cross ...`. Neither word is + // reserved, so the label is only a label when one of them follows the + // `:`; anything else is not a cover item and the covergroup falls back. + let label = if self.cur().kind == TokenKind::Ident + && self.nth(1).is_sym(":") + && (word_at(self.nth(2), "coverpoint") || word_at(self.nth(2), "cross")) + { + let name = Name { text: self.cur().text.clone(), span: self.cur().span }; + self.bump(); + let before = self.take_gap(); + self.bump(); // : + let after = self.take_gap(); + Some(CoverLabel { name, comments: Box::new(BinaryComments { before, after }) }) + } else { + None + }; + if word_at(self.cur(), "coverpoint") { + return Ok(CoverItemKind::Coverpoint(Box::new(self.parse_coverpoint(label)?))); + } + if word_at(self.cur(), "cross") { + return Ok(CoverItemKind::Cross(Box::new(self.parse_cross(label)?))); + } + self.error("expected a coverpoint, a cross or an option") + } + + fn parse_coverpoint(&mut self, label: Option) -> PResult { + self.bump(); // coverpoint + let after_kw = self.take_gap(); + let expr = self.parse_expr()?; + let iff = self.parse_cover_iff()?; + let before_body = self.gap_before("{"); + let body = if self.cur().is_sym("{") { Some(self.parse_cover_body(false)?) } else { None }; + Ok(CoverpointDecl { label, after_kw, expr, iff, before_body, body }) + } + + fn parse_cross(&mut self, label: Option) -> PResult { + self.bump(); // cross + let after_kw = self.take_gap(); + let mut items: Vec = Vec::new(); + loop { + let start = self.here(); + let mut meta = self.take_meta(); + let expr = self.parse_expr()?; + let span = self.span_from(start); + self.take_before_sep(&mut meta, ","); + let more = self.eat_sym(","); + if more { + meta.trailing = self.take_trailing(); + } + items.push(ExprItem { meta, expr, span }); + if !more { + break; + } + } + let iff = self.parse_cover_iff()?; + let before_body = self.gap_before("{"); + let body = if self.cur().is_sym("{") { Some(self.parse_cover_body(true)?) } else { None }; + Ok(CrossDecl { label, after_kw, items, iff, before_body, body }) + } + + /// The `iff ( expr )` guard of a coverpoint, a cross or a bin. The gap in + /// front of `iff` is claimed only when the keyword was really written. + fn parse_cover_iff(&mut self) -> PResult>> { + if !self.cur().is_kw("iff") { + return Ok(None); + } + let before_kw = self.take_gap(); + self.bump(); + let after_kw = self.take_gap(); + self.expect_sym("(")?; + let after_open = self.take_gap(); + let expr = self.parse_expr()?; + let before_close = self.gap_before(")"); + self.expect_sym(")")?; + Ok(Some(Box::new(CoverIff { before_kw, after_kw, after_open, before_close, expr }))) + } + + /// The `{ bins_or_options }` body of a coverpoint or a cross. Gated, like + /// every other body. + fn parse_cover_body(&mut self, in_cross: bool) -> PResult { + self.enter()?; + let out = self.parse_cover_body_inner(in_cross); + self.leave(); + out + } + + fn parse_cover_body_inner(&mut self, in_cross: bool) -> PResult { + let start = self.here(); + self.expect_sym("{")?; + let mut items = Vec::new(); + while !self.cur().is_sym("}") { + if self.at_eof() { + return self.error("expected `}`"); + } + items.push(self.parse_bin_item(in_cross)?); + } + let dangling = self.take_dangling(); + self.expect_sym("}")?; + Ok(CoverBody { items, dangling, span: self.span_from(start) }) + } + + fn parse_bin_item(&mut self, in_cross: bool) -> PResult { + let start = self.here(); + let mut meta = self.take_meta(); + let kind = self.parse_bin_item_kind(in_cross)?; + let mut before_semi = Vec::new(); + if kind.takes_semi() { + before_semi = self.take_gap(); + self.expect_sym(";")?; + } + let span = self.span_from(start); + if meta.trailing.is_none() { + meta.trailing = self.take_trailing(); + } + Ok(BinItem { meta, kind, before_semi, span }) + } + + fn parse_bin_item_kind(&mut self, in_cross: bool) -> PResult { + if self.cur().kind == TokenKind::Directive || self.at_macro_item() { + return Ok(BinItemKind::Directive(self.take_raw_text())); + } + if self.eat_sym(";") { + return Ok(BinItemKind::Empty); + } + if self.at_option_assign() { + return Ok(BinItemKind::Option(Box::new(self.parse_option_assign()?))); + } + Ok(BinItemKind::Bin(Box::new(self.parse_bin_decl(in_cross)?))) + } + + /// True when the cursor opens `option.x = v` / `type_option.x = v`. + /// Both words are matched by text and both demand the `.`, so a signal + /// named `option` compared to something else is not one. + fn at_option_assign(&self) -> bool { + (word_at(self.cur(), "option") || word_at(self.cur(), "type_option")) + && self.nth(1).is_sym(".") + } + + fn parse_option_assign(&mut self) -> PResult { + let target = self.parse_expr()?; + let before = self.gap_before("="); + self.expect_sym("=")?; + let after = self.take_gap(); + let value = self.parse_expr()?; + Ok(OptionAssign { target, comments: Box::new(BinaryComments { before, after }), value }) + } + + /// `[wildcard] bins name[[expr]] = spec [with (expr)] [iff (expr)]`. + /// + /// `wildcard`, `bins`, `ignore_bins` and `illegal_bins` are matched **by + /// text**, not reserved as keywords, for the reason `soft` and `dist` are: + /// reserving them would stop a file that spells one as an identifier from + /// parsing at all. Inside a coverpoint body their position leaves no other + /// reading. See `docs/features/covergroup-bodies/README.md`. + fn parse_bin_decl(&mut self, in_cross: bool) -> PResult { + let wildcard = word_at(self.cur(), "wildcard") && bin_kind_at(self.nth(1)).is_some(); + let mut after_wildcard = Vec::new(); + if wildcard { + self.bump(); + after_wildcard = self.take_gap(); + } + let Some(kind) = bin_kind_at(self.cur()) else { + return self.error("expected `bins`, `ignore_bins` or `illegal_bins`"); + }; + self.bump(); + let before_name = self.take_gap(); + let name = self.expect_name()?; + let array = self.parse_bin_array()?; + let before = self.gap_before("="); + self.expect_sym("=")?; + let after = self.take_gap(); + let spec = self.parse_bin_spec(in_cross)?; + let with_expr = self.parse_bin_with()?; + let iff = self.parse_cover_iff()?; + Ok(BinDecl { + wildcard, + after_wildcard, + kind, + before_name, + name, + array, + eq_comments: Box::new(BinaryComments { before, after }), + spec, + with_expr, + iff, + }) + } + + /// The `[]` / `[expr]` written after a bin name. + fn parse_bin_array(&mut self) -> PResult>> { + if !self.cur().is_sym("[") { + return Ok(None); + } + let before = self.take_gap(); + self.bump(); + let inner_before = self.take_gap(); + let size = if self.cur().is_sym("]") { None } else { Some(self.parse_expr()?) }; + let inner_after = self.gap_before("]"); + self.expect_sym("]")?; + Ok(Some(Box::new(BinArray { + before, + comments: Box::new(BinaryComments { before: inner_before, after: inner_after }), + size, + }))) + } + + /// What a bin is defined as. `in_cross` says which grammar applies: a + /// coverpoint bin's `( ... )` is a **transition list** (IEEE 1800 + /// §19.5.1.2) and a cross bin's is a parenthesized **select expression** + /// (§19.6.1). The two are told apart by where they are written, which is + /// what the LRM does — asking whether a `=>` happens to be inside gets + /// `bins b = (1'b1[*5]);` wrong. + fn parse_bin_spec(&mut self, in_cross: bool) -> PResult { + if self.cur().is_kw("default") { + self.bump(); + // `sequence` really is a lexer keyword (a `sequence ... endsequence` + // declaration), so this one is not matched by text. + if self.cur().is_kw("sequence") { + let comments = self.take_gap(); + self.bump(); + return Ok(BinSpec::DefaultSequence { comments }); + } + return Ok(BinSpec::Default); + } + if self.cur().is_sym("{") { + return Ok(BinSpec::Values(self.parse_constraint_expr_set()?)); + } + if self.cur().is_sym("(") && !in_cross { + return Ok(BinSpec::Transitions(self.parse_trans_list()?)); + } + Ok(BinSpec::Select(self.parse_select_expr()?)) + } + + /// `( trans_set ) [ , ( trans_set ) ]*` (IEEE 1800 §19.5.1.2). + fn parse_trans_list(&mut self) -> PResult> { + let mut sets: Vec = Vec::new(); + loop { + let start = self.here(); + let mut meta = self.take_meta(); + self.expect_sym("(")?; + let mut ranges = Vec::new(); + let mut arrow = BinaryComments::default(); + loop { + ranges.push(self.parse_trans_range(Box::new(arrow))?); + if !self.cur().is_sym("=>") { + break; + } + let before = self.take_gap(); + self.bump(); + let after = self.take_gap(); + arrow = BinaryComments { before, after }; + } + let dangling = self.gap_before(")"); + self.expect_sym(")")?; + let span = self.span_from(start); + self.take_before_sep(&mut meta, ","); + let more = self.eat_sym(","); + if more { + meta.trailing = self.take_trailing(); + } + sets.push(TransSet { meta, ranges, dangling, span }); + if !more { + break; + } + } + Ok(sets) + } + + fn parse_trans_range(&mut self, arrow_comments: Box) -> PResult { + let mut items: Vec = Vec::new(); + loop { + let start = self.here(); + let mut meta = self.take_meta(); + let expr = self.parse_range_or_expr()?; + let span = self.span_from(start); + self.take_before_sep(&mut meta, ","); + let more = self.eat_sym(","); + if more { + meta.trailing = self.take_trailing(); + } + items.push(ExprItem { meta, expr, span }); + if !more { + break; + } + } + let repeat = self.parse_trans_repeat()?; + Ok(TransRange { arrow_comments, items, repeat }) + } + + /// `[* 3]`, `[* 1:$]`, `[-> 2]`, `[= 1]` — the repetition a transition + /// range may carry. + fn parse_trans_repeat(&mut self) -> PResult>> { + if !self.at_repeat_bracket() { + return Ok(None); + } + let before = self.take_gap(); + self.bump(); // [ + let after_open = self.take_gap(); + let op = self.bump().text; + let inner_before = self.take_gap(); + let lo = self.parse_expr()?; + let mut colon = BinaryComments::default(); + let mut hi = None; + if self.cur().is_sym(":") { + colon.before = self.take_gap(); + self.bump(); + colon.after = self.take_gap(); + hi = Some(self.parse_expr()?); + } + let inner_after = self.gap_before("]"); + self.expect_sym("]")?; + Ok(Some(Box::new(TransRepeat { + before, + after_open, + op, + comments: Box::new(BinaryComments { before: inner_before, after: inner_after }), + lo, + hi, + colon_comments: Box::new(colon), + }))) + } + + /// A cross bin's `select_expression` (IEEE 1800 §19.6.1), and the bare + /// coverpoint name a coverpoint bin may be defined as. + fn parse_select_expr(&mut self) -> PResult { + let mut lhs = self.parse_select_primary()?; + while self.cur().is_sym("&&") || self.cur().is_sym("||") { + let before = self.take_gap(); + let op = self.bump().text; + let after = self.take_gap(); + let rhs = self.parse_select_primary()?; + lhs = SelectExpr::Binary { + lhs: Box::new(lhs), + op, + comments: Box::new(BinaryComments { before, after }), + rhs: Box::new(rhs), + }; + } + Ok(lhs) + } + + fn parse_select_primary(&mut self) -> PResult { + if self.cur().is_sym("!") { + self.bump(); + let comments = self.take_gap(); + let expr = self.parse_select_primary()?; + return Ok(SelectExpr::Not { comments, expr: Box::new(expr) }); + } + if self.cur().is_sym("(") { + self.bump(); + let before = self.take_gap(); + let expr = self.parse_select_expr()?; + let after = self.gap_before(")"); + self.expect_sym(")")?; + return Ok(SelectExpr::Paren { + comments: Box::new(BinaryComments { before, after }), + expr: Box::new(expr), + }); + } + if word_at(self.cur(), "binsof") && self.nth(1).is_sym("(") { + return Ok(SelectExpr::Binsof(Box::new(self.parse_binsof()?))); + } + // A bare spec is a coverpoint name, possibly reached through a handle + // (`cfg.vif.x`), an index, or a call (`single_masks(n)`, which tools + // accept and the LRM does not). Read at the **postfix** level, so it + // stops in front of `&&`, `||` and everything else this grammar reads + // itself — and, with `no_with` set, in front of the bin's own + // `with ( ... )` filter, which is not an array method's iterator + // argument. + if self.cur().kind != TokenKind::Ident { + return self.error("expected a select expression"); + } + self.no_with = true; + let out = self.parse_postfix(); + self.no_with = false; + Ok(SelectExpr::Expr(out?)) + } + + fn parse_binsof(&mut self) -> PResult { + self.bump(); // binsof + let after_kw = self.take_gap(); + self.expect_sym("(")?; + let after_open = self.take_gap(); + let name = self.parse_expr()?; + let before_close = self.gap_before(")"); + self.expect_sym(")")?; + let mut before_intersect = Vec::new(); + let mut after_intersect = Vec::new(); + let mut intersect = None; + if word_at(self.cur(), "intersect") { + before_intersect = self.take_gap(); + self.bump(); + after_intersect = self.take_gap(); + intersect = Some(self.parse_constraint_expr_set()?); + } + Ok(BinsofSel { + after_kw, + after_open, + before_close, + name, + before_intersect, + after_intersect, + intersect, + }) + } + + /// The `with ( expr )` filter written after a bin's values. + fn parse_bin_with(&mut self) -> PResult>> { + if !(self.cur().is_kw("with") && self.nth(1).is_sym("(")) { + return Ok(None); + } + let before_kw = self.take_gap(); + self.bump(); + let after_kw = self.take_gap(); + self.expect_sym("(")?; + let after_open = self.take_gap(); + let expr = self.parse_expr()?; + let before_close = self.gap_before(")"); + self.expect_sym(")")?; + Ok(Some(Box::new(BinWith { before_kw, after_kw, after_open, before_close, expr }))) + } + /// True when the cursor opens a concurrent assertion (IEEE 1800 §16.14): /// `[label :] assert|assume|cover|restrict property ( ... )`. /// @@ -5670,7 +6277,7 @@ impl<'a> Parser<'a> { let t = self.cur(); t.is_sym(".") || t.is_sym("::") - || t.is_sym("[") + || (t.is_sym("[") && !self.at_repeat_bracket()) || t.is_sym("(") || (t.is_sym("'") && self.nth(1).is_sym("(")) // `ty'{...}` — a cast over an assignment pattern. Only a base @@ -5684,7 +6291,27 @@ impl<'a> Parser<'a> { // postfix spellings of `with`; the delimiter tells them apart and // demanding one keeps the `with [range]` of a stream expression, // which lucisv does not model, out of this path. - || (t.is_kw("with") && (self.nth(1).is_sym("(") || self.nth(1).is_sym("{"))) + || (t.is_kw("with") + && !self.no_with + && (self.nth(1).is_sym("(") || self.nth(1).is_sym("{"))) + } + + /// True when the `[` at the cursor opens a transition repetition — + /// `[* 3]`, `[-> 2]`, `[= 1]` (IEEE 1800 §19.5.1.2) — rather than an + /// index or a part select. + /// + /// No index expression can start with `*`, `->` or `=`, so this needs no + /// context: it says "that `[` is not an index" everywhere, which was + /// already true and is now acted on. Without it `1'b0[*1:10]` would send + /// the whole covergroup down the verbatim fallback, because + /// [`Parser::parse_postfix_inner`] would take the `[` and then fail on + /// the `*`. + fn at_repeat_bracket(&self) -> bool { + if !self.cur().is_sym("[") { + return false; + } + let next = self.nth(1); + next.kind == TokenKind::Symbol && matches!(next.text.as_str(), "*" | "->" | "=") } /// Postfix segments are parsed by a loop, but each one wraps the @@ -7645,12 +8272,14 @@ mod tests { } #[test] - fn a_covergroup_is_still_captured_verbatim() { - let src = "class c;\n covergroup g;\n coverpoint a;\n endgroup : g\nendclass\n"; + fn a_property_declaration_is_still_captured_verbatim() { + // What is left in the verbatim bucket after two rounds of this wave: + // a `property`/`sequence` declaration and a concurrent assertion. + let src = "class c;\n property p;\n a |-> b;\n endproperty : p\nendclass\n"; let f = parse_ok(src); let items = &class_of(&f).items; let ItemKind::Verbatim(b) = &items[0].kind else { panic!("expected a verbatim block") }; - assert_eq!(b.text, "covergroup g;\n coverpoint a;\n endgroup : g"); + assert_eq!(b.text, "property p;\n a |-> b;\n endproperty : p"); assert_eq!(b.text, src[b.span.as_range()]); } @@ -7659,7 +8288,7 @@ mod tests { // The comment is written past the block's last token, so it must not // be swallowed by the capture *or* dropped from the plumbing. let f = parse_ok( - "class c;\n covergroup g;\n coverpoint a;\n endgroup // why\n int b;\nendclass\n", + "class c;\n property p;\n a |-> b;\n endproperty // why\n int b;\nendclass\n", ); let items = &class_of(&f).items; let ItemKind::Verbatim(raw) = &items[0].kind else { panic!("expected a verbatim block") }; @@ -7667,6 +8296,16 @@ mod tests { assert_eq!(items[0].meta.trailing.as_ref().expect("the comment survived").text, "// why"); } + #[test] + fn a_comment_after_a_covergroup_stays_outside_it_too() { + let f = parse_ok( + "class c;\n covergroup g;\n coverpoint a;\n endgroup // why\n int b;\nendclass\n", + ); + let items = &class_of(&f).items; + assert!(matches!(items[0].kind, ItemKind::Covergroup(_))); + assert_eq!(items[0].meta.trailing.as_ref().expect("the comment survived").text, "// why"); + } + // ------------------------------------------------------------------ // Constraint bodies (`docs/features/constraint-bodies/README.md`) // ------------------------------------------------------------------ @@ -10306,4 +10945,527 @@ mod tests { ["a.b", "plain"] ); } + + // ------------------------------------------------------------------ + // Covergroup bodies (`docs/features/covergroup-bodies/README.md`) + // ------------------------------------------------------------------ + + fn covergroup_of(f: &SourceFile) -> &CovergroupDecl { + match &class_of(f).items[0].kind { + ItemKind::Covergroup(c) => c, + other => panic!("expected a covergroup, got {other:?}"), + } + } + + /// A covergroup body wrapped in the class the corpus always writes it in. + fn cg(body: &str) -> SourceFile { + parse_ok(&format!("class c;\n covergroup g;\n{body}\n endgroup\nendclass\n")) + } + + fn cover_items(f: &SourceFile) -> &[CoverItem] { + &covergroup_of(f).items + } + + fn coverpoint_of(f: &SourceFile) -> &CoverpointDecl { + match &cover_items(f)[0].kind { + CoverItemKind::Coverpoint(cp) => cp, + other => panic!("expected a coverpoint, got {other:?}"), + } + } + + fn cross_of(f: &SourceFile) -> &CrossDecl { + match &cover_items(f)[0].kind { + CoverItemKind::Cross(c) => c, + other => panic!("expected a cross, got {other:?}"), + } + } + + /// The bins of the first coverpoint or cross in `f`. + fn bins_of(f: &SourceFile) -> &[BinItem] { + let body = match &cover_items(f)[0].kind { + CoverItemKind::Coverpoint(cp) => cp.body.as_ref(), + CoverItemKind::Cross(c) => c.body.as_ref(), + other => panic!("expected a coverpoint or a cross, got {other:?}"), + }; + &body.expect("the body was parsed").items + } + + fn bin_of(f: &SourceFile) -> &BinDecl { + match &bins_of(f)[0].kind { + BinItemKind::Bin(b) => b, + other => panic!("expected a bin, got {other:?}"), + } + } + + #[test] + fn a_covergroup_header_keeps_its_name_its_args_and_its_end_label() { + let f = parse_ok( + "class c;\n covergroup g (bit [3:0] a, int n);\n coverpoint a;\n endgroup : g\nendclass\n", + ); + let g = covergroup_of(&f); + assert_eq!(g.name.text, "g"); + assert_eq!(&f.span.as_range().start, &0); + let args = g.args.as_ref().expect("the formal list was parsed"); + assert_eq!(args.iter().map(|a| a.name.as_str()).collect::>(), ["a", "n"]); + assert_eq!(g.end_label.as_ref().expect("the label was kept").text, "g"); + assert!(!g.end_semi); + assert_eq!(f.covergroups, 1); + assert_eq!(f.covergroup_fallbacks, 0); + } + + #[test] + fn a_header_with_no_parens_records_none_rather_than_an_empty_list() { + // Printing an invented `()` back would change the token stream. + let f = cg(" coverpoint a;"); + assert!(covergroup_of(&f).args.is_none()); + let f = parse_ok("class c;\n covergroup g ();\n coverpoint a;\n endgroup\nendclass\n"); + assert_eq!(covergroup_of(&f).args.as_ref().map(Vec::len), Some(0)); + } + + #[test] + fn a_sample_function_header_keeps_the_word_and_its_arguments() { + let f = parse_ok( + "class c;\n covergroup g (string n) with function sample (bit [31:0] addr, bit rw);\n coverpoint addr;\n endgroup\nendclass\n", + ); + let Some(CoverageEvent::Sample(s)) = &covergroup_of(&f).event else { + panic!("expected a sample function") + }; + assert_eq!(s.name.text, "sample"); + assert!(s.has_parens); + assert_eq!(s.args.iter().map(|a| a.name.as_str()).collect::>(), ["addr", "rw"]); + } + + #[test] + fn a_clocking_event_header_is_read_by_the_always_at_parser() { + let f = parse_ok( + "class c;\n covergroup g @(posedge clk);\n coverpoint a;\n endgroup\nendclass\n", + ); + let Some(CoverageEvent::Clocking { sens: SensList::List(items), .. }) = + &covergroup_of(&f).event + else { + panic!("expected a clocking event") + }; + assert_eq!(items.len(), 1); + assert_eq!(items[0].edge.as_deref(), Some("posedge")); + // The bare `@ev` spelling keeps its lack of parentheses. + let f = + parse_ok("class c;\n covergroup g @ev;\n coverpoint a;\n endgroup\nendclass\n"); + let Some(CoverageEvent::Clocking { sens: SensList::Bare(_), .. }) = + &covergroup_of(&f).event + else { + panic!("expected a bare event name") + }; + } + + #[test] + fn a_coverpoint_keeps_its_label_its_expression_and_its_iff() { + let f = cg(" cp_a: coverpoint a + 1 iff (en);"); + let cp = coverpoint_of(&f); + assert_eq!(cp.label.as_ref().expect("a label").name.text, "cp_a"); + assert!(matches!(cp.expr.kind, ExprKind::Binary { .. })); + assert!(cp.iff.is_some()); + assert!(cp.body.is_none()); + // An unlabelled coverpoint declares nothing and says so. + let f = cg(" coverpoint a;"); + assert!(coverpoint_of(&f).label.is_none()); + } + + #[test] + fn a_cross_keeps_every_operand_in_order() { + let f = cg(" cr: cross cp_a, cp_b, cp_c;"); + let cr = cross_of(&f); + assert_eq!(cr.label.as_ref().expect("a label").name.text, "cr"); + assert_eq!(cr.items.len(), 3); + assert!(cr.iff.is_none()); + } + + #[test] + fn an_option_assignment_is_its_own_item_in_both_places() { + let f = cg(" option.per_instance = 1;\n type_option.weight = 5;\n cp: coverpoint a { option.weight = 2; }"); + let items = cover_items(&f); + assert!(matches!(items[0].kind, CoverItemKind::Option(_))); + assert!(matches!(items[1].kind, CoverItemKind::Option(_))); + let CoverItemKind::Coverpoint(cp) = &items[2].kind else { panic!("expected a coverpoint") }; + let body = cp.body.as_ref().expect("the body was parsed"); + assert!(matches!(body.items[0].kind, BinItemKind::Option(_))); + } + + #[test] + fn every_bin_keyword_and_the_wildcard_prefix_are_kept_apart() { + let f = cg( + " cp: coverpoint a {\n bins one = {1};\n wildcard bins w = {4'b1??1};\n ignore_bins ig = {2};\n illegal_bins bad = {3};\n }", + ); + let bins = bins_of(&f); + let kinds: Vec<(BinKind, bool)> = bins + .iter() + .map(|b| match &b.kind { + BinItemKind::Bin(b) => (b.kind, b.wildcard), + other => panic!("expected a bin, got {other:?}"), + }) + .collect(); + assert_eq!( + kinds, + [ + (BinKind::Bins, false), + (BinKind::Bins, true), + (BinKind::IgnoreBins, false), + (BinKind::IllegalBins, false), + ] + ); + } + + #[test] + fn a_bin_array_keeps_the_sized_and_unsized_spellings_apart() { + let f = cg(" cp: coverpoint a {\n bins sized[4] = {1};\n bins open[] = {2};\n bins plain = {3};\n }"); + let bins = bins_of(&f); + let arrays: Vec> = bins + .iter() + .map(|b| match &b.kind { + BinItemKind::Bin(b) => b.array.as_ref().map(|a| a.size.is_some()), + other => panic!("expected a bin, got {other:?}"), + }) + .collect(); + assert_eq!(arrays, [Some(true), Some(false), None]); + } + + #[test] + fn a_value_bin_keeps_its_ranges_and_the_dollar_bound() { + let f = cg(" cp: coverpoint a {\n bins v = {0, [1:3], [4:$]};\n }"); + let BinSpec::Values(items) = &bin_of(&f).spec else { panic!("expected values") }; + assert_eq!(items.len(), 3); + assert!(matches!(items[1].expr.kind, ExprKind::ValueRange { .. })); + assert!(matches!(items[2].expr.kind, ExprKind::ValueRange { .. })); + } + + #[test] + fn the_two_default_spellings_are_never_normalized_into_each_other() { + let f = cg(" cp: coverpoint a {\n bins d = default;\n bins s = default sequence;\n }"); + let bins = bins_of(&f); + let specs: Vec<&str> = bins + .iter() + .map(|b| match &b.kind { + BinItemKind::Bin(b) => match &b.spec { + BinSpec::Default => "default", + BinSpec::DefaultSequence { .. } => "default sequence", + other => panic!("expected a default, got {other:?}"), + }, + other => panic!("expected a bin, got {other:?}"), + }) + .collect(); + assert_eq!(specs, ["default", "default sequence"]); + } + + #[test] + fn a_transition_bin_keeps_every_arrow_comma_and_repetition() { + let f = cg(" cp: coverpoint a {\n bins t = (0 => 1, 2 => 3), (4 => 5);\n bins r = (1'b0[*1:10] => 1'b1[->2] => 1'b0[=1]);\n }"); + let bins = bins_of(&f); + let BinItemKind::Bin(first) = &bins[0].kind else { panic!("expected a bin") }; + let BinSpec::Transitions(sets) = &first.spec else { panic!("expected transitions") }; + assert_eq!(sets.len(), 2); + assert_eq!(sets[0].ranges.len(), 3, "`0 => 1, 2 => 3` is three ranges"); + assert_eq!(sets[0].ranges[1].items.len(), 2, "`1, 2` is one range of two items"); + assert_eq!(sets[1].ranges.len(), 2); + let BinItemKind::Bin(second) = &bins[1].kind else { panic!("expected a bin") }; + let BinSpec::Transitions(sets) = &second.spec else { panic!("expected transitions") }; + let ops: Vec<&str> = sets[0] + .ranges + .iter() + .map(|r| r.repeat.as_ref().expect("a repetition").op.as_str()) + .collect(); + assert_eq!(ops, ["*", "->", "="]); + let first = sets[0].ranges[0].repeat.as_ref().expect("a repetition"); + assert!(first.hi.is_some(), "`[*1:10]` has both bounds"); + } + + #[test] + fn a_single_transition_set_needs_no_arrow_to_be_one() { + // opentitan `hw/ip/rom_ctrl/dv/cov/rom_ctrl_cov_if.sv`: + // `bins zero_delay_5 = (1'b1[*5]);` is a transition list of one range + // with a repetition, not a parenthesized select expression. Which + // grammar a `(` opens is decided by *where it is written* — a + // coverpoint bin or a cross bin — exactly as the LRM decides it. + let f = cg(" cp: coverpoint a {\n bins z = (1'b1[*5]);\n }"); + let BinSpec::Transitions(sets) = &bin_of(&f).spec else { panic!("expected transitions") }; + assert_eq!(sets.len(), 1); + assert_eq!(sets[0].ranges.len(), 1); + assert_eq!(sets[0].ranges[0].repeat.as_ref().expect("a repetition").op, "*"); + // The same parentheses in a *cross* bin are a select expression. + let f = cg(" cr: cross a, b {\n bins z = (binsof(a) || binsof(b));\n }"); + assert!(matches!(bin_of(&f).spec, BinSpec::Select(SelectExpr::Paren { .. }))); + } + + #[test] + fn a_call_may_stand_as_a_bin_spec() { + // opentitan `hw/ip/csrng/dv/cov/csrng_cov_if.sv`: + // `bins single_exc[] = single_masks(num_hw_apps);`. Tools accept it; + // the LRM does not spell it, and reading it costs nothing. + let f = cg(" cp: coverpoint a {\n bins v[] = single_masks(n);\n }"); + let BinSpec::Select(SelectExpr::Expr(e)) = &bin_of(&f).spec else { + panic!("expected a call") + }; + assert!(matches!(e.kind, ExprKind::Call { .. })); + } + + #[test] + fn a_bins_with_filter_is_never_read_as_an_array_method() { + // `with (` is a postfix segment everywhere else in the language; in a + // bin spec it introduces the bin's own filter, and the expression + // parser has to stop in front of it. The flag that says so must not + // survive the operand. + let f = cg(" cp: coverpoint a {\n bins v[] = cp_x with (item > 0);\n }"); + let b = bin_of(&f); + assert!(matches!(b.spec, BinSpec::Select(SelectExpr::Expr(_)))); + assert!(b.with_expr.is_some(), "the `with` is the bin's, not the expression's"); + // And an array method's `with` still parses as one, in the same file. + let f = parse_ok( + "class c;\n covergroup g;\n cp: coverpoint a { bins v[] = cp_x with (item > 0); }\n endgroup\n function int f();\n return q.find with (item > 0);\n endfunction\nendclass\n", + ); + assert!(matches!(class_of(&f).items[1].kind, ItemKind::Function(_))); + } + + #[test] + fn a_with_filter_and_a_coverpoint_name_spec_are_both_read() { + let f = cg(" cp: coverpoint a {\n bins e[] = cp_x with (item % 2 == 0);\n bins v = {[0:$]} with ($countones(item) != 1);\n }"); + let bins = bins_of(&f); + let BinItemKind::Bin(first) = &bins[0].kind else { panic!("expected a bin") }; + assert!(matches!(first.spec, BinSpec::Select(SelectExpr::Expr(_)))); + assert!(first.with_expr.is_some()); + let BinItemKind::Bin(second) = &bins[1].kind else { panic!("expected a bin") }; + assert!(matches!(second.spec, BinSpec::Values(_))); + assert!(second.with_expr.is_some()); + } + + #[test] + fn a_cross_bin_reads_binsof_intersect_and_the_boolean_operators() { + let f = cg(" cr: cross a, b {\n bins sel = binsof(a.x) intersect {0, [1:2]} && !binsof(b);\n }"); + let BinSpec::Select(SelectExpr::Binary { lhs, op, rhs, .. }) = &bin_of(&f).spec else { + panic!("expected a select expression") + }; + assert_eq!(op, "&&"); + let SelectExpr::Binsof(b) = lhs.as_ref() else { panic!("expected a binsof") }; + assert_eq!(b.intersect.as_ref().expect("an intersect set").len(), 2); + let SelectExpr::Not { expr, .. } = rhs.as_ref() else { panic!("expected a negation") }; + assert!(matches!(**expr, SelectExpr::Binsof(_))); + } + + #[test] + fn a_bin_may_carry_its_own_iff() { + let f = cg(" cp: coverpoint a {\n bins v = {1} iff (en);\n }"); + assert!(bin_of(&f).iff.is_some()); + } + + #[test] + fn a_directive_and_a_null_item_stand_where_a_cover_item_belongs() { + let f = cg(" `ifdef FOO\n cp: coverpoint a;\n `endif\n ;"); + let items = cover_items(&f); + assert!(matches!(items[0].kind, CoverItemKind::Directive(_))); + assert!(matches!(items[1].kind, CoverItemKind::Coverpoint(_))); + assert!(matches!(items[2].kind, CoverItemKind::Directive(_))); + assert!(matches!(items[3].kind, CoverItemKind::Empty)); + // And inside a coverpoint body too. + let f = cg(" cp: coverpoint a {\n `ifdef FOO\n bins v = {1};\n `endif\n ;\n }"); + let bins = bins_of(&f); + assert!(matches!(bins[0].kind, BinItemKind::Directive(_))); + assert!(matches!(bins[2].kind, BinItemKind::Directive(_))); + assert!(matches!(bins[3].kind, BinItemKind::Empty)); + } + + #[test] + fn an_unrecognised_covergroup_rewinds_to_exactly_the_old_capture() { + // A macro supplying a coverpoint's whole bin body, `;` included — + // opentitan `hw/ip/otbn/dv/uvm/env/otbn_env_cov.sv`. Irreducible + // without expanding macros, and the shape the fallback exists for. + let src = "class c;\n covergroup g;\n cp: coverpoint a `GPR_BIN_TYPES\n endgroup : g\nendclass\n"; + let f = parse_ok(src); + let item = &class_of(&f).items[0]; + let ItemKind::Verbatim(b) = &item.kind else { panic!("expected a verbatim block") }; + assert_eq!(b.text, "covergroup g;\n cp: coverpoint a `GPR_BIN_TYPES\n endgroup : g"); + assert_eq!(b.text, src[b.span.as_range()], "the capture slices back to its span"); + assert_eq!(b.col, 3, "the re-indent column is the covergroup's own"); + assert_eq!(f.covergroups, 0); + assert_eq!(f.covergroup_fallbacks, 1); + } + + #[test] + fn a_covergroup_fallback_keeps_the_comments_written_around_it() { + // The speculative parse harvests comments into nodes it then throws + // away; the rewind must put both pending buckets back. + let f = parse_ok( + "class k;\n // head\n covergroup g;\n cp: coverpoint a `GPR_BINS\n endgroup // tail\n int b;\nendclass\n", + ); + let item = &class_of(&f).items[0]; + assert!(matches!(item.kind, ItemKind::Verbatim(_))); + assert_eq!(item.meta.leading[0].text, "// head"); + assert_eq!(item.meta.trailing.as_ref().expect("trailing").text, "// tail"); + } + + #[test] + fn a_covergroup_with_no_endgroup_falls_back_and_reports_it_once() { + let src = "class c;\n covergroup g;\n coverpoint a;\n"; + let (f, diags) = parse_tolerant(tokenize(src).expect("lex error"), src); + assert_eq!(f.covergroups, 0); + assert_eq!(f.covergroup_fallbacks, 1); + assert_eq!( + diags.iter().filter(|d| d.message.contains("endgroup")).count(), + 1, + "one diagnostic, from the verbatim path: {diags:?}" + ); + } + + #[test] + fn a_stray_semicolon_after_endgroup_is_reproduced() { + let f = + parse_ok("class c;\n covergroup g;\n coverpoint a;\n endgroup : g;\nendclass\n"); + let g = covergroup_of(&f); + assert_eq!(g.end_label.as_ref().expect("a label").text, "g"); + assert!(g.end_semi); + } + + #[test] + fn a_repeat_bracket_never_steals_an_ordinary_index() { + // The `[`-guard `at_repeat_bracket` installs must not change how any + // other expression parses. + let f = parse_ok("module m;\n assign y = q[3] + r[a:b] + s[i +: 2];\nendmodule\n"); + assert!(matches!(f.items[0].kind, ItemKind::Module(_))); + } + + /// Every comment text a covergroup at the head of `src`'s class holds, + /// in one flat list — what the slot pins assert against. + fn covergroup_comments(src: &str) -> Vec { + let f = parse_ok(src); + let g = covergroup_of(&f); + let mut out: Vec = Vec::new(); + macro_rules! push { + ($cs:expr) => { + out.extend($cs.iter().map(|c| c.text.clone())) + }; + } + push!(&g.before_name); + push!(&g.before_args); + match &g.event { + Some(CoverageEvent::Sample(s)) => { + push!(&s.before_with); + push!(&s.after_with); + push!(&s.after_function); + push!(&s.before_args); + } + Some(CoverageEvent::Clocking { before, .. }) => push!(before), + None => {} + } + push!(&g.before_semi); + push!(&g.before_end_semi); + for item in &g.items { + push!(&item.before_semi); + match &item.kind { + CoverItemKind::Coverpoint(cp) => { + if let Some(l) = &cp.label { + push!(&l.comments.before); + push!(&l.comments.after); + } + push!(&cp.after_kw); + push_iff(&mut out, cp.iff.as_deref()); + push!(&cp.before_body); + push_body(&mut out, cp.body.as_ref()); + } + CoverItemKind::Cross(cr) => { + if let Some(l) = &cr.label { + push!(&l.comments.before); + push!(&l.comments.after); + } + push!(&cr.after_kw); + push_iff(&mut out, cr.iff.as_deref()); + push!(&cr.before_body); + push_body(&mut out, cr.body.as_ref()); + } + CoverItemKind::Option(o) => { + push!(&o.comments.before); + push!(&o.comments.after); + } + CoverItemKind::Directive(_) | CoverItemKind::Empty => {} + } + } + out + } + + fn push_iff(out: &mut Vec, iff: Option<&CoverIff>) { + let Some(i) = iff else { return }; + for cs in [&i.before_kw, &i.after_kw, &i.after_open, &i.before_close] { + out.extend(cs.iter().map(|c| c.text.clone())); + } + } + + fn push_body(out: &mut Vec, body: Option<&CoverBody>) { + let Some(body) = body else { return }; + for item in &body.items { + out.extend(item.before_semi.iter().map(|c| c.text.clone())); + let BinItemKind::Bin(b) = &item.kind else { continue }; + for cs in + [&b.after_wildcard, &b.before_name, &b.eq_comments.before, &b.eq_comments.after] + { + out.extend(cs.iter().map(|c| c.text.clone())); + } + if let Some(a) = &b.array { + for cs in [&a.before, &a.comments.before, &a.comments.after] { + out.extend(cs.iter().map(|c| c.text.clone())); + } + } + if let BinSpec::DefaultSequence { comments } = &b.spec { + out.extend(comments.iter().map(|c| c.text.clone())); + } + if let Some(w) = &b.with_expr { + for cs in [&w.before_kw, &w.after_kw, &w.after_open, &w.before_close] { + out.extend(cs.iter().map(|c| c.text.clone())); + } + } + push_iff(out, b.iff.as_deref()); + } + } + + #[test] + fn every_covergroup_header_slot_keeps_its_comment() { + let got = covergroup_comments( + "class c;\n covergroup /*a*/ g /*b*/ (int n) /*c*/ with /*d*/ function /*e*/ sample /*f*/ (int x) /*g*/ ;\n coverpoint x;\n endgroup : g /*h*/ ;\nendclass\n", + ); + assert_eq!(got, ["/*a*/", "/*b*/", "/*c*/", "/*d*/", "/*e*/", "/*f*/", "/*g*/", "/*h*/"]); + } + + #[test] + fn every_coverpoint_slot_keeps_its_comment() { + let got = covergroup_comments( + "class c;\n covergroup g;\n cp /*a*/ : /*b*/ coverpoint /*c*/ x /*d*/ iff /*e*/ ( /*f*/ en /*g*/ ) /*h*/ {\n }\n endgroup\nendclass\n", + ); + assert_eq!(got, ["/*a*/", "/*b*/", "/*c*/", "/*d*/", "/*e*/", "/*f*/", "/*g*/", "/*h*/"]); + } + + #[test] + fn every_bin_slot_keeps_its_comment() { + let got = covergroup_comments( + "class c;\n covergroup g;\n cp: coverpoint x {\n wildcard /*a*/ bins /*b*/ v /*c*/ [ /*d*/ 4 /*e*/ ] /*f*/ = /*g*/ {1} /*h*/ with /*i*/ ( /*j*/ item /*k*/ ) /*l*/ iff /*m*/ ( /*n*/ en /*o*/ ) /*p*/ ;\n }\n endgroup\nendclass\n", + ); + assert_eq!( + got, + [ + "/*p*/", "/*a*/", "/*b*/", "/*f*/", "/*g*/", "/*c*/", "/*d*/", "/*e*/", "/*h*/", + "/*i*/", "/*j*/", "/*k*/", "/*l*/", "/*m*/", "/*n*/", "/*o*/" + ] + ); + } + + #[test] + fn the_option_assignment_slots_keep_their_comments() { + let got = covergroup_comments( + "class c;\n covergroup g;\n option.per_instance /*a*/ = /*b*/ 1 /*c*/ ;\n endgroup\nendclass\n", + ); + assert_eq!(got, ["/*c*/", "/*a*/", "/*b*/"]); + } + + #[test] + fn the_gap_before_a_cover_items_semicolon_that_was_not_written_belongs_to_what_follows() { + // A comment on the line after a coverpoint's `}` is the *next* + // item's leading comment, not the closed item's `before_semi`. + let f = cg(" cp: coverpoint x {\n }\n // why\n cr: cross a, b;"); + let items = cover_items(&f); + assert!(items[0].before_semi.is_empty()); + assert_eq!(items[1].meta.leading[0].text, "// why"); + } } diff --git a/crates/vlog_parser/tests/census.rs b/crates/vlog_parser/tests/census.rs new file mode 100644 index 0000000..1d628ba --- /dev/null +++ b/crates/vlog_parser/tests/census.rs @@ -0,0 +1,54 @@ +//! A read-only sweep probe: set CENSUS to a directory and this prints the +//! covergroup structured/fallback counts and the tolerant diagnostics over +//! every `.sv`/`.svh` under it. Ignored; run by hand for the feature README. +use std::path::{Path, PathBuf}; + +fn collect(dir: &Path, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + for e in entries.flatten() { + let p = e.path(); + if p.is_dir() { + collect(&p, out); + } else if matches!(p.extension().and_then(|s| s.to_str()), Some("sv") | Some("svh")) { + out.push(p); + } + } +} + +#[test] +#[ignore] +fn census() { + std::thread::Builder::new() + .stack_size(vlog_parser::PARSE_STACK_SIZE) + .spawn(run) + .expect("spawn") + .join() + .expect("join"); +} + +fn run() { + let root = std::env::var("CENSUS").expect("CENSUS"); + let mut files = Vec::new(); + collect(Path::new(&root), &mut files); + files.sort(); + let (mut cg, mut fb, mut cf, mut diags, mut with_diags) = (0u64, 0u64, 0u64, 0u64, 0u64); + for p in &files { + let Ok(src) = std::fs::read_to_string(p) else { continue }; + let (file, ds) = vlog_parser::parse_source_tolerant(&src); + cg += u64::from(file.covergroups); + fb += u64::from(file.covergroup_fallbacks); + cf += u64::from(file.constraint_fallbacks); + if file.covergroup_fallbacks > 0 { + println!("FALLBACK {} {}", p.display(), file.covergroup_fallbacks); + } + if !ds.is_empty() { + with_diags += 1; + println!("DIAGS {} {}", p.display(), ds.len()); + } + diags += ds.len() as u64; + } + println!( + "files={} covergroups={cg} covergroup_fallbacks={fb} constraint_fallbacks={cf} diagnostics={diags} files_with_diagnostics={with_diags}", + files.len() + ); +} diff --git a/crates/vlog_parser/tests/spans.rs b/crates/vlog_parser/tests/spans.rs index b22f8a5..476c6f6 100644 --- a/crates/vlog_parser/tests/spans.rs +++ b/crates/vlog_parser/tests/spans.rs @@ -71,6 +71,12 @@ const SOURCES: &[&str] = &[ "virtual class base #(parameter int W = 8) extends pkg::top #(.A(1), b) implements i, j;\n rand bit [W-1:0] v;\n local int n;\n virtual my_if h;\n pure virtual function void f();\n extern task t(int x);\nendclass : base\n", "class c;\n port_t #(bit [3:0]) p;\n constraint x {\n a == 0; // why\n } // after\n covergroup g;\n coverpoint a;\n endgroup : g\n function new(string name);\n super.new(name);\n x = db#(virtual bus_if)::get(this);\n endfunction : new\nendclass\n", "typedef class fwd;\npackage p;\n class inner extends fwd;\n endclass\nendpackage\nfunction void inner::configure(int x);\nendfunction\n", + // Covergroup bodies: the header's two argument lists, labels, an `iff`, + // every bin spec, a cross with a select expression, and the end label. + "class cov;\n covergroup cg (int seed) with function sample (bit [3:0] a, int n);\n option.per_instance = 1;\n cp_a: coverpoint a iff (n > 0) {\n wildcard bins w[4] = {4'b1??1};\n ignore_bins ig = {2, [3:seed]};\n illegal_bins bad = default;\n bins s = default sequence;\n bins t = (0 => 1, 2), (3 => 4);\n bins r = (1'b0[*1:10] => 1'b1[->2]);\n bins e[] = cp_x with (item % 2 == 0);\n }\n cr: cross cp_a, n {\n bins sel = binsof(cp_a) intersect {0, [1:2]} && !binsof(n);\n }\n endgroup : cg\nendclass\n", + // A covergroup at module scope with a clocking event, and one that falls + // back to the verbatim capture. + "module m;\n covergroup cg @(posedge clk);\n coverpoint x;\n endgroup\n covergroup broken;\n cp: coverpoint x `GPR_BIN_TYPES\n endgroup\nendmodule\n", // Out-of-block constraints: the verbatim leaf reached from item position, // at file scope and inside a package, with a scope chain and a stray `;`. "class c;\n extern constraint x;\nendclass\nconstraint c::x {\n a == 0; // why\n}; // after\npackage p;\n constraint q::inner::deep_c { b < 4; }\nendpackage\n", @@ -614,6 +620,7 @@ fn check_item(src: &str, item: &Item, parent: TextRange) { check_constraint_set(src, set, here); } } + ItemKind::Covergroup(c) => check_covergroup(src, c, here), // A `covergroup` block, or a `constraint` whose body did not fit the // grammar: one verbatim leaf whose span is the item's own, checked // above. A null item is a leaf too — its span is the `;`, which the @@ -1220,6 +1227,145 @@ fn a_label_and_its_end_label_get_separate_spans() { /// A `constraint` body or nested constraint set: every item inside the set, /// every expression inside the item, and every `foreach` loop variable. +fn check_covergroup(src: &str, c: &CovergroupDecl, here: TextRange) { + check_name(src, "covergroup name", &c.name.text, c.name.span, here); + for a in c.args.iter().flatten() { + assert_inside(src, "covergroup argument", a.span, here); + check_name(src, "covergroup argument name", &a.name, a.name_span, a.span); + } + match &c.event { + Some(CoverageEvent::Sample(s)) => { + check_name(src, "sample method name", &s.name.text, s.name.span, here); + for a in &s.args { + assert_inside(src, "sample argument", a.span, here); + check_name(src, "sample argument name", &a.name, a.name_span, a.span); + } + } + // A clocking event's own spans are the statement `always @(...)` + // machinery's, checked where that is. + Some(CoverageEvent::Clocking { .. }) => {} + None => {} + } + if let Some(l) = &c.end_label { + check_name(src, "endgroup label", &l.text, l.span, here); + } + for item in &c.items { + assert_inside(src, "cover item", item.span, here); + let at = item.span; + match &item.kind { + CoverItemKind::Coverpoint(cp) => { + check_cover_label(src, cp.label.as_ref(), at); + check_expr(src, &cp.expr, at); + check_cover_iff(src, cp.iff.as_deref(), at); + check_cover_body(src, cp.body.as_ref(), at); + } + CoverItemKind::Cross(cr) => { + check_cover_label(src, cr.label.as_ref(), at); + for e in &cr.items { + assert_inside(src, "cross operand", e.span, at); + check_expr(src, &e.expr, e.span); + } + check_cover_iff(src, cr.iff.as_deref(), at); + check_cover_body(src, cr.body.as_ref(), at); + } + CoverItemKind::Option(o) => { + check_expr(src, &o.target, at); + check_expr(src, &o.value, at); + } + CoverItemKind::Directive(raw) => assert_inside(src, "raw text", raw.span, at), + CoverItemKind::Empty => {} + } + } +} + +fn check_cover_label(src: &str, label: Option<&CoverLabel>, parent: TextRange) { + if let Some(l) = label { + check_name(src, "cover label", &l.name.text, l.name.span, parent); + } +} + +fn check_cover_iff(src: &str, iff: Option<&CoverIff>, parent: TextRange) { + if let Some(i) = iff { + check_expr(src, &i.expr, parent); + } +} + +fn check_cover_body(src: &str, body: Option<&CoverBody>, parent: TextRange) { + let Some(body) = body else { return }; + assert_inside(src, "cover body", body.span, parent); + for item in &body.items { + assert_inside(src, "bin item", item.span, body.span); + let at = item.span; + match &item.kind { + BinItemKind::Bin(b) => { + check_name(src, "bin name", &b.name.text, b.name.span, at); + if let Some(a) = &b.array { + check_opt_expr(src, a.size.as_ref(), at); + } + check_bin_spec(src, &b.spec, at); + if let Some(w) = &b.with_expr { + check_expr(src, &w.expr, at); + } + check_cover_iff(src, b.iff.as_deref(), at); + } + BinItemKind::Option(o) => { + check_expr(src, &o.target, at); + check_expr(src, &o.value, at); + } + BinItemKind::Directive(raw) => assert_inside(src, "raw text", raw.span, at), + BinItemKind::Empty => {} + } + } +} + +fn check_bin_spec(src: &str, spec: &BinSpec, parent: TextRange) { + match spec { + BinSpec::Values(items) => { + for e in items { + assert_inside(src, "bin value", e.span, parent); + check_expr(src, &e.expr, e.span); + } + } + BinSpec::Transitions(sets) => { + for set in sets { + assert_inside(src, "transition set", set.span, parent); + for r in &set.ranges { + for e in &r.items { + assert_inside(src, "transition item", e.span, set.span); + check_expr(src, &e.expr, e.span); + } + if let Some(rep) = &r.repeat { + check_expr(src, &rep.lo, set.span); + check_opt_expr(src, rep.hi.as_ref(), set.span); + } + } + } + } + BinSpec::Default | BinSpec::DefaultSequence { .. } => {} + BinSpec::Select(s) => check_select_expr(src, s, parent), + } +} + +fn check_select_expr(src: &str, s: &SelectExpr, parent: TextRange) { + match s { + SelectExpr::Binsof(b) => { + check_expr(src, &b.name, parent); + for e in b.intersect.iter().flatten() { + assert_inside(src, "intersect element", e.span, parent); + check_expr(src, &e.expr, e.span); + } + } + SelectExpr::Not { expr, .. } | SelectExpr::Paren { expr, .. } => { + check_select_expr(src, expr, parent) + } + SelectExpr::Binary { lhs, rhs, .. } => { + check_select_expr(src, lhs, parent); + check_select_expr(src, rhs, parent); + } + SelectExpr::Expr(e) => check_expr(src, e, parent), + } +} + fn check_constraint_set(src: &str, set: &ConstraintSet, parent: TextRange) { assert_inside(src, "constraint set", set.span, parent); for item in &set.items { diff --git a/crates/vlog_semantic/src/bind.rs b/crates/vlog_semantic/src/bind.rs index 36db4a9..8e6ea90 100644 --- a/crates/vlog_semantic/src/bind.rs +++ b/crates/vlog_semantic/src/bind.rs @@ -423,6 +423,7 @@ impl<'a> Binder<'a> { } } ItemKind::Constraint(c) => self.bind_constraint(c, item.span, scope), + ItemKind::Covergroup(c) => self.bind_covergroup(c, item.span, scope), ItemKind::Function(f) => self.bind_function(f, item.span, scope), ItemKind::Task(t) => self.bind_task(t, item.span, scope), ItemKind::Class(c) => self.bind_class(c, item.span, scope), @@ -1132,6 +1133,186 @@ impl<'a> Binder<'a> { } } + // ------------------------------------------------------------------ + // Covergroups + // ------------------------------------------------------------------ + + /// A `covergroup g (args) with function sample (args); ... endgroup` + /// (IEEE 1800 §19.3). + /// + /// The covergroup opens a scope of its own whose parent is where it is + /// written, so every sampled expression reaches an enclosing class's + /// properties with `this.` implicit — the rule a constraint body follows, + /// for the same reason. What that scope *declares* is the covergroup's + /// formal arguments, its `sample` method and that method's arguments, and + /// one symbol per labelled coverpoint and cross: those are the names + /// `cg.cp` and a `cross a, b` reach. + fn bind_covergroup(&mut self, c: &'a CovergroupDecl, span: TextRange, scope: ScopeId) { + let inner = self.declare_with_scope( + scope, + &c.name.text, + SymbolKind::Covergroup, + c.name.span, + span, + ScopeKind::Covergroup, + ); + if let Some(args) = &c.args { + self.bind_tf_args(args, inner); + } + match &c.event { + Some(CoverageEvent::Sample(s)) => { + // `sample` is a real method of the covergroup — `cg.sample(x)` + // is how every DV testbench calls it. + self.declare(inner, &s.name.text, SymbolKind::Function, s.name.span, s.name.span); + self.bind_tf_args(&s.args, inner); + } + // A clocking event names signals of the *enclosing* scope, not of + // the covergroup: it is written in the header, before anything + // inside exists. + Some(CoverageEvent::Clocking { sens, .. }) => self.bind_sens_list(sens, scope), + None => {} + } + for item in &c.items { + self.bind_cover_item(item, inner); + } + self.use_end_label( + scope, + inner, + c.end_label.as_ref().map(|l| &l.text), + c.end_label.as_ref().map(|l| l.span), + ); + } + + fn bind_cover_item(&mut self, item: &'a CoverItem, scope: ScopeId) { + match &item.kind { + CoverItemKind::Coverpoint(cp) => { + self.declare_cover_label( + cp.label.as_ref(), + SymbolKind::Coverpoint, + item.span, + scope, + ); + self.bind_expr(&cp.expr, scope); + self.bind_cover_iff(cp.iff.as_deref(), scope); + self.bind_cover_body(cp.body.as_ref(), scope); + } + CoverItemKind::Cross(cr) => { + self.declare_cover_label(cr.label.as_ref(), SymbolKind::Cross, item.span, scope); + for e in &cr.items { + self.bind_expr(&e.expr, scope); + } + self.bind_cover_iff(cr.iff.as_deref(), scope); + self.bind_cover_body(cr.body.as_ref(), scope); + } + // `option.per_instance` names a built-in of the covergroup, not + // anything this crate models, so neither half is recorded — the + // value is an ordinary expression and is. + CoverItemKind::Option(o) => self.bind_expr(&o.value, scope), + CoverItemKind::Directive(_) | CoverItemKind::Empty => {} + } + } + + fn declare_cover_label( + &mut self, + label: Option<&CoverLabel>, + kind: SymbolKind, + span: TextRange, + scope: ScopeId, + ) { + if let Some(l) = label { + self.declare(scope, &l.name.text, kind, l.name.span, span); + } + } + + fn bind_cover_iff(&mut self, iff: Option<&'a CoverIff>, scope: ScopeId) { + if let Some(i) = iff { + self.bind_expr(&i.expr, scope); + } + } + + fn bind_cover_body(&mut self, body: Option<&'a CoverBody>, scope: ScopeId) { + let Some(body) = body else { return }; + for item in &body.items { + match &item.kind { + BinItemKind::Bin(b) => self.bind_bin_decl(b, scope), + BinItemKind::Option(o) => self.bind_expr(&o.value, scope), + BinItemKind::Directive(_) | BinItemKind::Empty => {} + } + } + } + + fn bind_bin_decl(&mut self, b: &'a BinDecl, scope: ScopeId) { + if let Some(a) = &b.array { + self.bind_opt_expr(a.size.as_ref(), scope); + } + self.bind_bin_spec(&b.spec, scope); + if let Some(w) = &b.with_expr { + // `item` is the implicit iteration variable of a `with` filter + // (IEEE 1800 §19.5.1.1) — the coverpoint's own sampled value, not + // anything the enclosing class declares. It gets a scope of its + // own so that a class property that happens to be called `item` + // is not silently taken to be it, which would make renaming that + // property rewrite a filter that never named it. `item` is not + // *written* as a declaration anywhere, so the first use of it + // inside the filter is what the declaration points at — every + // name this crate records must be locatable in the source, and an + // invented span is not. + let inner = self.new_scope(ScopeKind::Block, scope, w.expr.span); + let first = self.pending.len(); + self.bind_expr(&w.expr, inner); + if let Some(at) = + self.pending[first..].iter().find(|p| p.name == "item").map(|p| p.name_span) + { + self.declare(inner, "item", SymbolKind::Var, at, w.expr.span); + } + } + self.bind_cover_iff(b.iff.as_deref(), scope); + } + + fn bind_bin_spec(&mut self, spec: &'a BinSpec, scope: ScopeId) { + match spec { + BinSpec::Values(items) => { + for e in items { + self.bind_expr(&e.expr, scope); + } + } + BinSpec::Transitions(sets) => { + for set in sets { + for r in &set.ranges { + for e in &r.items { + self.bind_expr(&e.expr, scope); + } + if let Some(rep) = &r.repeat { + self.bind_expr(&rep.lo, scope); + self.bind_opt_expr(rep.hi.as_ref(), scope); + } + } + } + } + BinSpec::Default | BinSpec::DefaultSequence { .. } => {} + BinSpec::Select(s) => self.bind_select_expr(s, scope), + } + } + + fn bind_select_expr(&mut self, s: &'a SelectExpr, scope: ScopeId) { + match s { + SelectExpr::Binsof(b) => { + self.bind_expr(&b.name, scope); + for e in b.intersect.iter().flatten() { + self.bind_expr(&e.expr, scope); + } + } + SelectExpr::Not { expr, .. } | SelectExpr::Paren { expr, .. } => { + self.bind_select_expr(expr, scope) + } + SelectExpr::Binary { lhs, rhs, .. } => { + self.bind_select_expr(lhs, scope); + self.bind_select_expr(rhs, scope); + } + SelectExpr::Expr(e) => self.bind_expr(e, scope), + } + } + /// `base with { ... }` — a `randomize` call's inline constraint block /// (IEEE 1800 §18.7). /// diff --git a/crates/vlog_semantic/src/facts.rs b/crates/vlog_semantic/src/facts.rs index f08d268..8e77438 100644 --- a/crates/vlog_semantic/src/facts.rs +++ b/crates/vlog_semantic/src/facts.rs @@ -68,7 +68,7 @@ use crate::workspace::{ /// (`prim_fifo_sync`'s `localparam int DepthW = $clog2(Depth)` was offered). /// An older reader has no name for the new kind either, so the bump is needed /// in both directions. -pub const FACTS_FORMAT: u32 = 11; +pub const FACTS_FORMAT: u32 = 12; impl FileFacts { /// These facts as one line's worth of fields, tab-separated. @@ -550,6 +550,9 @@ fn kind_name(kind: SymbolKind) -> &'static str { SymbolKind::StructMember => "structmember", SymbolKind::Class => "class", SymbolKind::Constraint => "constraint", + SymbolKind::Covergroup => "covergroup", + SymbolKind::Coverpoint => "coverpoint", + SymbolKind::Cross => "cross", } } @@ -578,6 +581,9 @@ fn kind_of(name: &str) -> Option { "structmember" => SymbolKind::StructMember, "class" => SymbolKind::Class, "constraint" => SymbolKind::Constraint, + "covergroup" => SymbolKind::Covergroup, + "coverpoint" => SymbolKind::Coverpoint, + "cross" => SymbolKind::Cross, _ => return None, }) } @@ -612,6 +618,10 @@ mod tests { SymbolKind::Block, SymbolKind::StructMember, SymbolKind::Class, + SymbolKind::Constraint, + SymbolKind::Covergroup, + SymbolKind::Coverpoint, + SymbolKind::Cross, ]; let mut names: Vec<&str> = kinds.iter().map(|k| kind_name(*k)).collect(); for kind in kinds { diff --git a/crates/vlog_semantic/src/model.rs b/crates/vlog_semantic/src/model.rs index aca9b25..26145d3 100644 --- a/crates/vlog_semantic/src/model.rs +++ b/crates/vlog_semantic/src/model.rs @@ -85,6 +85,18 @@ pub enum SymbolKind { /// rename of a `rand` property left every constraint that reads it /// untouched. Constraint, + /// A `covergroup g ... endgroup` (IEEE 1800 §19.3) — a named member of a + /// class, a module or a package, and the container `cg.cp` reaches + /// through. `covergroup-bodies` gave it a symbol for the same reason + /// `constraint-bodies` gave a constraint one: before it, the parsed name + /// was discarded and nothing inside bound. + Covergroup, + /// A labelled `cp : coverpoint expr` inside a covergroup. An + /// *unlabelled* coverpoint declares nothing, which is exactly what the + /// LRM says: there is no name to reach it by. + Coverpoint, + /// A labelled `cr : cross a, b` inside a covergroup. + Cross, } impl SymbolKind { @@ -258,6 +270,12 @@ pub enum ScopeKind { /// variables. It is its own kind so that "am I inside a constraint" is /// answerable without walking back to the owning symbol. Constraint, + /// A `covergroup g ... endgroup` body. Its parent is the enclosing class + /// (or module, or package) scope, so every sampled expression reaches a + /// property with `this.` implicit; it declares the covergroup's formal + /// arguments, its `sample` method and that method's arguments, and one + /// symbol per *labelled* coverpoint and cross. + Covergroup, } /// One `import p::x;` / `import p::*;` recorded in the scope that wrote it. diff --git a/crates/vlog_semantic/src/resolve.rs b/crates/vlog_semantic/src/resolve.rs index 4e6f367..03b7e5e 100644 --- a/crates/vlog_semantic/src/resolve.rs +++ b/crates/vlog_semantic/src/resolve.rs @@ -498,7 +498,10 @@ fn container_scope(symbols: &[Symbol], id: SymbolId) -> Option { /// no type name exists to look anything up by. `docs/features/struct-members/README.md`. fn member_scope(scopes: &[Scope], symbols: &[Symbol], id: SymbolId) -> Option { let symbol = symbols.get(id.0 as usize)?; - if symbol.kind == SymbolKind::Class || symbol.kind.is_instantiable() { + if symbol.kind == SymbolKind::Class + || symbol.kind == SymbolKind::Covergroup + || symbol.kind.is_instantiable() + { return symbol.child_scope; } let child = symbol.child_scope?; diff --git a/crates/vlog_semantic/src/workspace.rs b/crates/vlog_semantic/src/workspace.rs index feca156..4441775 100644 --- a/crates/vlog_semantic/src/workspace.rs +++ b/crates/vlog_semantic/src/workspace.rs @@ -1341,10 +1341,11 @@ fn collect_members( // A class nested in a package (the dominant UVM shape) is not a unit, // but an external `cls::x` candidate looks its members up under the // *class's* name — register them there too. A struct `typedef` nested - // in a package is the same shape, and an inline aggregate member is - // the same shape under its synthesized key. The scope tree is acyclic, - // so this recursion terminates. - if matches!(member.kind, SymbolKind::Class | SymbolKind::Typedef) { + // in a package is the same shape, an inline aggregate member is the + // same shape under its synthesized key, and so is a covergroup, whose + // labelled coverpoints `cg_inst.cp` reaches. The scope tree is + // acyclic, so this recursion terminates. + if matches!(member.kind, SymbolKind::Class | SymbolKind::Typedef | SymbolKind::Covergroup) { collect_members(sem, &member.name, member, lines, out); } else if let Some(nested) = nested { collect_members(sem, &nested, member, lines, out); @@ -1544,6 +1545,7 @@ fn is_exported(unit: SymbolKind, member: SymbolKind) -> bool { | SymbolKind::Var | SymbolKind::Class | SymbolKind::Constraint + | SymbolKind::Covergroup ), SymbolKind::Module => { matches!(member, SymbolKind::Port | SymbolKind::Param | SymbolKind::LocalParam) @@ -1556,6 +1558,13 @@ fn is_exported(unit: SymbolKind, member: SymbolKind) -> bool { SymbolKind::Typedef | SymbolKind::StructMember => { matches!(member, SymbolKind::StructMember) } + // A covergroup's surface is its labelled coverpoints and crosses — + // `cg.cp` is how a cross in another covergroup, or a `get_coverage` + // call in another file, names one — plus the `sample` method the + // header declares. + SymbolKind::Covergroup => { + matches!(member, SymbolKind::Coverpoint | SymbolKind::Cross | SymbolKind::Function) + } SymbolKind::Interface => matches!( member, SymbolKind::Net diff --git a/crates/vlog_semantic/tests/classes.rs b/crates/vlog_semantic/tests/classes.rs index e3aba49..29884e5 100644 --- a/crates/vlog_semantic/tests/classes.rs +++ b/crates/vlog_semantic/tests/classes.rs @@ -602,7 +602,7 @@ endfunction } #[test] -fn a_covergroup_is_absent_but_nothing_crashes() { +fn a_covergroup_declares_its_name_and_binds_inside() { let src = "\ class c; rand int x; @@ -612,11 +612,19 @@ class c; endclass "; let s = sem(src); - // No symbol for the covergroup name, no reference inside: it is still an - // `ItemKind::Verbatim(_)` leaf. Round 2 of `constraint-bodies` is what - // changes that. - assert!(s.symbols().iter().all(|sym| sym.name != "cg")); - assert!(s.reference_at(nth(src, "coverpoint x", 0) + 11).is_none()); + // Round 2 of the wave: the covergroup declares a symbol of its own and + // the sampled expression is an ordinary reference to the class property. + // See `docs/features/covergroup-bodies/README.md`. + assert!(s.symbols().iter().any(|sym| sym.name == "cg")); + let r = s.reference_at(nth(src, "coverpoint x", 0) + 11).expect("`x` is a reference"); + assert_eq!(r.name, "x"); + assert_eq!( + s.definition_of(nth(src, "coverpoint x", 0) + 11).map(|d| d.name_span), + Some(vlog_parser::TextRange::new( + nth(src, "rand int x", 0) + 9, + nth(src, "rand int x", 0) + 10, + )) + ); // Queries at every offset stay panic-free. for offset in 0..=src.len() as u32 { let _ = s.definition_of(offset); diff --git a/crates/vlog_semantic/tests/covergroups.rs b/crates/vlog_semantic/tests/covergroups.rs new file mode 100644 index 0000000..243fcac --- /dev/null +++ b/crates/vlog_semantic/tests/covergroups.rs @@ -0,0 +1,356 @@ +//! Covergroup bodies: what a `covergroup g ... endgroup` declares, where the +//! names inside it bind, and how `cg.cp` reaches a coverpoint across files. +//! The rules live in `docs/features/covergroup-bodies/README.md`. + +use std::path::PathBuf; +use vlog_parser::parse_source; +use vlog_semantic::{ + analyze, resolve_external, Def, ExternalTarget, FileFacts, Resolution, Semantics, SymbolKind, + WorkspaceIndex, +}; + +fn sem(src: &str) -> Semantics { + let file = parse_source(src).expect("fixture must parse"); + analyze(&file, src) +} + +/// Offset of the `n`th (0-based) occurrence of `needle`. +fn nth(src: &str, needle: &str, n: usize) -> u32 { + src.match_indices(needle).nth(n).expect("occurrence must exist").0 as u32 +} + +fn resolution_at(s: &Semantics, offset: u32) -> Resolution { + s.reference_at(offset).unwrap_or_else(|| panic!("no reference at {offset}")).resolution.clone() +} + +/// The declaration the use at `offset` points at, by name. +fn defines(s: &Semantics, offset: u32) -> Option<(String, SymbolKind)> { + let d = s.definition_of(offset)?; + Some((d.name.clone(), d.kind)) +} + +fn index(files: &[(&str, &str)]) -> WorkspaceIndex { + WorkspaceIndex::build(files.iter().map(|(name, src)| (PathBuf::from(name), *src))) +} + +fn overlay_def(ws: &WorkspaceIndex, src: &str, offset: u32) -> Option { + let s = sem(src); + let id = s.reference_id_at(offset)?; + resolve_external(&s, ws).get(id).and_then(ExternalTarget::best).cloned() +} + +fn kind_of(s: &Semantics, name: &str) -> SymbolKind { + s.symbols() + .iter() + .find(|sym| sym.name == name) + .unwrap_or_else(|| panic!("no symbol {name}")) + .kind +} + +// ---------------------------------------------------------------------- +// What a covergroup declares +// ---------------------------------------------------------------------- + +#[test] +fn a_covergroup_declares_itself_its_sample_method_and_its_labels() { + let src = "\ +class cov; + covergroup cg (int seed) with function sample (int addr); + cp_addr: coverpoint addr; + coverpoint seed; + cr: cross cp_addr, cp_seed; + endgroup +endclass +"; + let s = sem(src); + assert_eq!(kind_of(&s, "cg"), SymbolKind::Covergroup); + assert_eq!(kind_of(&s, "sample"), SymbolKind::Function); + assert_eq!(kind_of(&s, "cp_addr"), SymbolKind::Coverpoint); + assert_eq!(kind_of(&s, "cr"), SymbolKind::Cross); + assert_eq!(kind_of(&s, "seed"), SymbolKind::TfArg); + assert_eq!(kind_of(&s, "addr"), SymbolKind::TfArg); + // An unlabelled coverpoint declares nothing at all. + assert_eq!( + s.symbols().iter().filter(|sym| sym.kind == SymbolKind::Coverpoint).count(), + 1, + "only the labelled coverpoint has a name" + ); +} + +#[test] +fn a_sampled_expression_binds_to_the_enclosing_class_property() { + let src = "\ +class item; + rand int addr; + rand bit rw; + covergroup cg; + cp: coverpoint addr { + bins lo = {[0:addr_max]}; + } + cr: cross cp, rw iff (rw); + endgroup + int addr_max; +endclass +"; + let s = sem(src); + assert_eq!( + defines(&s, nth(src, "coverpoint addr", 0) + 11), + Some(("addr".into(), SymbolKind::Var)) + ); + assert_eq!( + defines(&s, nth(src, "addr_max]", 0)), + Some(("addr_max".into(), SymbolKind::Var)), + "a bin value is an ordinary lexical use of a class property" + ); + assert_eq!(defines(&s, nth(src, "cross cp, rw", 0) + 10), Some(("rw".into(), SymbolKind::Var))); + assert_eq!( + defines(&s, nth(src, "iff (rw)", 0) + 5), + Some(("rw".into(), SymbolKind::Var)), + "and so is an `iff` guard" + ); +} + +#[test] +fn a_cross_operand_binds_to_the_coverpoint_the_covergroup_declared() { + let src = "\ +class cov; + covergroup cg; + cp_a: coverpoint a; + cp_b: coverpoint b; + cr: cross cp_a, cp_b { + bins sel = binsof(cp_a) intersect {0} && !binsof(cp_b); + } + endgroup +endclass +"; + let s = sem(src); + assert_eq!( + defines(&s, nth(src, "cross cp_a", 0) + 6), + Some(("cp_a".into(), SymbolKind::Coverpoint)) + ); + assert_eq!( + defines(&s, nth(src, "binsof(cp_a)", 0) + 7), + Some(("cp_a".into(), SymbolKind::Coverpoint)), + "a `binsof` operand names a coverpoint of this covergroup" + ); + assert_eq!( + defines(&s, nth(src, "!binsof(cp_b)", 0) + 8), + Some(("cp_b".into(), SymbolKind::Coverpoint)) + ); +} + +#[test] +fn a_sample_argument_is_visible_in_every_body_slot() { + let src = "\ +class cov; + covergroup cg with function sample (int lvl, bit en); + cp: coverpoint lvl iff (en) { + bins hi = {[lvl:$]}; + } + endgroup +endclass +"; + let s = sem(src); + for (needle, skip) in [("coverpoint lvl", 11), ("iff (en)", 5), ("[lvl:$]", 1)] { + assert_eq!( + defines(&s, nth(src, needle, 0) + skip).map(|(_, k)| k), + Some(SymbolKind::TfArg), + "{needle} must reach the sample argument" + ); + } +} + +#[test] +fn the_implicit_item_of_a_with_filter_shadows_a_property_of_the_same_name() { + // IEEE 1800 §19.5.1.1: `item` is the coverpoint's own sampled value. A + // class property called `item` must not be taken to be it — renaming that + // property would otherwise rewrite a filter that never named it. + let src = "\ +class cov; + rand int item; + covergroup cg; + cp: coverpoint x { + bins even = {[0:$]} with (item % 2 == 0); + } + endgroup +endclass +"; + let s = sem(src); + let property = s + .symbols() + .iter() + .position(|sym| sym.name == "item" && sym.kind == SymbolKind::Var) + .expect("the class property"); + let d = s.definition_of(nth(src, "with (item", 0) + 6).expect("`item` resolves"); + assert_ne!( + d.name_span, + s.symbols()[property].name_span, + "the filter's `item` is not the class property" + ); + // Other names in the same filter still reach the class. + let src = "\ +class cov; + int limit; + covergroup cg; + cp: coverpoint x { + bins under = {[0:$]} with (item < limit); + } + endgroup +endclass +"; + let s = sem(src); + assert_eq!(defines(&s, nth(src, "< limit", 0) + 2), Some(("limit".into(), SymbolKind::Var))); +} + +#[test] +fn an_option_target_names_nothing_and_its_value_names_everything() { + let src = "\ +class cov; + int weight_cfg; + covergroup cg; + option.per_instance = 1; + option.weight = weight_cfg; + coverpoint x; + endgroup +endclass +"; + let s = sem(src); + assert!( + s.reference_at(nth(src, "option.per_instance", 0)).is_none(), + "`option` is a covergroup built-in, not a name this crate models" + ); + assert_eq!( + defines(&s, nth(src, "= weight_cfg", 0) + 2), + Some(("weight_cfg".into(), SymbolKind::Var)) + ); +} + +#[test] +fn a_covergroup_that_fell_back_binds_nothing_again() { + // The fallback is the pre-round behaviour, exactly: an `ItemKind::Verbatim` + // leaf with no symbol and no reference inside. + let src = "\ +class cov; + rand int addr; + covergroup cg; + cp: coverpoint addr `GPR_BIN_TYPES + endgroup +endclass +"; + let s = sem(src); + assert!(s.symbols().iter().all(|sym| sym.name != "cg")); + assert!(s.reference_at(nth(src, "coverpoint addr", 0) + 11).is_none()); +} + +#[test] +fn a_clocking_event_names_the_enclosing_scope_not_the_covergroup() { + let src = "\ +module m; + logic clk; + covergroup cg @(posedge clk); + coverpoint clk; + endgroup +endmodule +"; + let s = sem(src); + assert_eq!(defines(&s, nth(src, "posedge clk", 0) + 8), Some(("clk".into(), SymbolKind::Var))); +} + +// ---------------------------------------------------------------------- +// Across files +// ---------------------------------------------------------------------- + +#[test] +fn a_coverpoint_of_a_covergroup_in_another_file_is_reachable() { + let cov = "\ +package cov_pkg; + class cov; + covergroup cg; + cp_addr: coverpoint addr; + endgroup + endclass +endpackage +"; + let user = "\ +class user; + cov_pkg::cov c; + function void f(); + $display(c.cg); + endfunction +endclass +"; + let ws = index(&[("cov.sv", cov), ("user.sv", user)]); + let def = overlay_def(&ws, user, nth(user, "c.cg", 0) + 2).expect("`cg` is reachable"); + assert_eq!(def.kind, SymbolKind::Covergroup); + assert_eq!(&cov[def.name_span.as_range()], "cg"); +} + +#[test] +fn a_covergroups_members_are_exported_and_its_bins_are_not() { + // `cg.cp` reaches a coverpoint; nothing reaches a bin, which has no name + // an expression can spell. + let src = "\ +class cov; + covergroup cg; + cp: coverpoint a { + bins lo = {0}; + } + endgroup +endclass +"; + let ws = index(&[("cov.sv", src)]); + let names = |unit: &str| -> Vec { + ws.members_of(unit).map(|(name, _)| name.to_string()).collect() + }; + assert!(names("cov").contains(&"cg".to_string())); + assert!(names("cg").contains(&"cp".to_string())); + assert!(!names("cg").contains(&"lo".to_string()), "a bin has no name to reach it by"); +} + +#[test] +fn a_sampled_property_declared_in_a_base_class_in_another_file_is_answered() { + let base = "\ +package base_pkg; + class base_item; + rand int addr; + endclass +endpackage +"; + let derived = "\ +class my_item extends base_pkg::base_item; + covergroup cg; + cp: coverpoint addr; + endgroup +endclass +"; + let ws = index(&[("base.sv", base), ("derived.sv", derived)]); + let s = sem(derived); + let at = nth(derived, "coverpoint addr", 0) + 11; + assert!( + matches!(resolution_at(&s, at), Resolution::InheritedCandidate { .. }), + "in-file it can only be the base class's" + ); + let def = overlay_def(&ws, derived, at).expect("the workspace finishes it"); + assert_eq!(&base[def.name_span.as_range()], "addr"); +} + +#[test] +fn the_index_of_a_file_with_a_covergroup_is_the_same_however_it_is_built() { + let cov = "\ +class cov; + rand int addr; + covergroup cg with function sample (int a); + cp: coverpoint a { bins lo = {[0:7]}; } + cr: cross cp, addr; + endgroup +endclass +"; + let other = "module m;\n wire w;\nendmodule\n"; + let full = index(&[("cov.sv", cov), ("other.sv", other)]); + let mut incremental = index(&[("other.sv", other)]); + incremental.update_file(PathBuf::from("cov.sv"), cov); + assert_eq!(incremental.fingerprint(), full.fingerprint()); + let mut absorbed = index(&[("other.sv", other)]); + absorbed.absorb(vec![FileFacts::of(PathBuf::from("cov.sv"), cov)], &[]); + assert_eq!(absorbed.fingerprint(), full.fingerprint()); +} diff --git a/docs/features/class-semantics/README.md b/docs/features/class-semantics/README.md index c5aad17..10e9c9d 100644 --- a/docs/features/class-semantics/README.md +++ b/docs/features/class-semantics/README.md @@ -637,3 +637,22 @@ other member. The pinned opacity test constraint body the grammar does not recognise falls back to `ItemKind::Verbatim` and keeps rule 2 exactly. See `docs/features/constraint-bodies/README.md`. + +--- + +## Amendment — 2026-09-02, `covergroup-bodies` (TODO.md §21) + +Rule 2 — "verbatim members stay opaque" — now covers **`property` and +`sequence` declarations and concurrent assertions**, and nothing else a class +body normally holds. A `covergroup` declares a `SymbolKind::Covergroup` where +it is written, its body opens a `ScopeKind::Covergroup` whose parent is that +scope (so every sampled expression is a property with `this.` implicit), and +that scope declares the covergroup's formal arguments, its `sample` method and +that method's arguments, and one `SymbolKind::Coverpoint` / `Cross` per +*labelled* coverpoint and cross. An unlabelled coverpoint declares nothing — +there is no name to reach it by. A class exports its covergroups, and a +covergroup exports its coverpoints, crosses and `sample`, so `cg.cp` resolves +across files. `a_covergroup_is_absent_but_nothing_crashes` became +`a_covergroup_declares_its_name_and_binds_inside`. A covergroup the grammar +does not recognise falls back to `ItemKind::Verbatim` and keeps rule 2 +exactly. See `docs/features/covergroup-bodies/README.md`. diff --git a/docs/features/classes/README.md b/docs/features/classes/README.md index 5ff0361..51fe459 100644 --- a/docs/features/classes/README.md +++ b/docs/features/classes/README.md @@ -775,3 +775,25 @@ is the machinery: a body the constraint grammar does not recognise byte-for-byte the same output — the fallback re-runs this round's function body verbatim, and a parser test pins its text, span and column. See `docs/features/constraint-bodies/README.md`. + +--- + +## Amendment — 2026-09-02, `covergroup-bodies` (TODO.md §21) + +The verbatim ruling above no longer covers covergroups either. A +`covergroup ... endgroup` is parsed into a real +`ItemKind::Covergroup(CovergroupDecl)` — header, formals, `with function +sample (...)`, clocking event, coverpoints, crosses, bins, options and the +`endgroup : g` label — and laid out canonically, so the §58 table row for it +is superseded on the same terms the `constraint` row was: there was no layout +convention worth inventing while the body was opaque bytes, and there is one +now that it is navigable. What survives unchanged is the machinery: +`Parser::parse_covergroup_verbatim` **is** this round's flat token scan, +character for character, and a covergroup the grammar does not recognise +rewinds into it with the same `RawText.col` re-indent contract and +byte-for-byte the same output. A parser test pins its text, span and column. + +What is left in the verbatim bucket after two rounds: `property` / +`sequence` declarations and concurrent assertions. The parser test that used +to pin a covergroup's capture now pins a `property`'s, which is what the +bucket is still for. See `docs/features/covergroup-bodies/README.md`. diff --git a/docs/features/constraint-bodies/README.md b/docs/features/constraint-bodies/README.md index fafc7bd..d161327 100644 --- a/docs/features/constraint-bodies/README.md +++ b/docs/features/constraint-bodies/README.md @@ -296,9 +296,13 @@ anyway"). re-derived, 13 verification, 13 semantic, 2 e2e, 1 lint case file - [x] Gates: fmt / clippy / `cargo test --workspace` / corpus gate / vsix smoke / opentitan read-only sweep -- [ ] **Not done, round 2:** covergroups. `covergroup ... endgroup` is still - an `ItemKind::Verbatim` leaf and `coverpoint`/`bins`/`cross` still bind - nothing. +- [x] **Round 2, done 2026-09-02:** covergroups. + `docs/features/covergroup-bodies/README.md` — `ItemKind::Covergroup` + with the same `Rewind`-to-verbatim fallback, the same "no keywords + reserved" posture, the same named comment fields and `takes_semi`, and + the gap fuzzer this round's rework invented, written first rather than + after. `Rewind`, `gap_before`, `word_at` and + `parse_constraint_expr_set` were reused unchanged. - [ ] **Filed, not done:** the `vlog_refactor` refusal above. ## Work log diff --git a/docs/features/covergroup-bodies/README.md b/docs/features/covergroup-bodies/README.md new file mode 100644 index 0000000..2daadfb --- /dev/null +++ b/docs/features/covergroup-bodies/README.md @@ -0,0 +1,835 @@ +# covergroup bodies + +## Goal + +Give `covergroup g ... endgroup` a real AST — the name, the formal arguments, +the `with function sample (...)` header, the clocking event, every coverpoint, +cross, bin and `option.x = v`, and the `endgroup : g` label — so that the +formatter, the binder, the linter, rename, hover and go-to-definition can all +see inside a covergroup. Until v0.27.0 a covergroup was an +`ItemKind::Verbatim(RawText)` leaf produced by a flat token scan +(`parser.rs::parse_covergroup`: `expect_kw("covergroup")`, then bump until +`endgroup`): the parsed label was *discarded*, no name span existed, and +nothing inside bound — so a rename of a `rand` property left +`coverpoint addr` untouched and `cg.cp` was unreachable. This is round 2 of +the `constraint-bodies` wave (TODO.md §21) and follows that round's shape +exactly: a structured parse behind a `Rewind` snapshot, a byte-for-byte +fallback, no keywords reserved, a named comment field for every slot, and an +exhaustive gap fuzzer — this time from day one rather than after a rework. + +## Assumptions + +- **The covergroup sub-grammar is modelled where real code writes it, and + nowhere else.** Everything the parser does not recognise rewinds to the + pre-round verbatim capture. The fallback is measured, not assumed: + `SourceFile::covergroups` / `covergroup_fallbacks` count both sides, and the + numbers are in the work log. Over OpenTitan's 3 975 `hw` files the count is + **544 structured, 0 fallbacks**. +- **`coverpoint`, `cross`, `bins`, `ignore_bins`, `illegal_bins`, `wildcard`, + `binsof`, `intersect`, `option`, `type_option` and `sample` are matched by + text, not reserved.** The argument is `constraint-bodies`' word for word: + `is_keyword` gates `expect_name` and `Binder::use_member`, so reserving ten + more words would stop a file that declares `int option;` from parsing and + would silently drop every reference to a signal called `cross`. Inside a + covergroup body their position leaves no other reading. `default`, + `sequence`, `iff` and `with` **are** already keywords and are read as such. + Consequence: `token.rs`, `pairs.rs`, `tests/grammar.rs` and the editor + grammar are untouched, so the round does not sit on the `token.rs` choke + point at all. +- **Which grammar a `(` opens is decided by where it is written, not by what + is inside it.** A coverpoint bin's `= ( ... )` is a transition list + (IEEE 1800 §19.5.1.2); a cross bin's is a parenthesized select expression + (§19.6.1). That is what the LRM says, and it is the only rule that gets + opentitan's `bins zero_delay_5 = (1'b1[*5]);` right — a transition list with + no `=>` anywhere in it. See the work log. +- **`&&` and `||` in a select expression are read left-associatively at one + precedence level.** The LRM binds `&&` tighter. lucisv evaluates neither and + prints no parentheses of its own, so the shape of the tree cannot reach the + output; recorded because it is a difference, not because it bites — the same + note `constraint-bodies` made about `a <-> b -> c`. +- **A covergroup is accepted wherever it was before**: class, module, + interface, package and file scope alike. No new legal-position check. +- **`item` inside a bin's `with ( ... )` filter is the coverpoint's own + sampled value**, not a name of the enclosing class (IEEE 1800 §19.5.1.1). + It is bound in a scope of its own — see Design — because a class property + called `item` is common in UVM and letting it capture the filter would make + renaming that property rewrite a filter that never named it. +- **A bin declares no symbol.** Nothing in SystemVerilog names a bin from an + expression, so a symbol for one would be an outline entry no reference can + ever point at — and `SymbolKind` is a `FACTS_FORMAT`-bumping choke point. + `cg.cp` is the reach the round buys; `cg.cp.bin` is not a thing. + +## Handshakes + +**Consumed, unchanged:** + +- `classes` — `verbatim_since` / `RawText` and the `RawText.col` re-indent + contract, now reached only through the fallback. The fallback re-runs the + *old function body verbatim* (`Parser::parse_covergroup_verbatim`), so a + covergroup the grammar does not know produces byte-identical output to + v0.27.0, and the parser test + `an_unrecognised_covergroup_rewinds_to_exactly_the_old_capture` pins the + text, the source slice and the `col`. +- `constraint-bodies` — `Rewind` / `rewind_mark` / `rewind_to`, + `Parser::gap_before`, `word_at`, `takes_semi` as the single owner of a `;`, + and `parse_constraint_expr_set` (the `{ a, [lo:hi] }` range list, which is + also a bin's value list and an `intersect` set). All reused as they stand; + none of them changed. +- `escaped-identifiers` — every name this round prints goes through + `format::name_doc` / `named`: the covergroup name, the `endgroup` label, + coverpoint and cross labels, bin names, and the `sample` method. +- `dv-statements` / the shared expression grammar — a sampled expression, a + bin value, an `iff` guard and a `with` filter are ordinary `Expr`s. +- `parse_tf_ports` and `parse_sens_list` — a covergroup's formal list and its + `sample` function's are `tf_port_list`s, and `@(posedge clk)` is the very + event list `always @(...)` reads. + +**Promised to others:** + +- **`ItemKind::Covergroup(Box)` is a new `ast.rs` variant.** + Per `topo.md` §3.3 it costs a `format.rs` arm (delivered), a `bind.rs` arm + (delivered), a `spans.rs` arm (delivered) and a `visit.rs` arm — the last + one is written and does nothing, deliberately, for the reason + `ItemKind::Constraint`'s does: a covergroup body holds cover items, not + `Item`s or `Stmt`s. Rules that need to see inside read the reference table. +- **`FACTS_FORMAT` 11 → 12.** `SymbolKind::Covergroup`, `Coverpoint` and + `Cross` are new kinds, so a store written by an older build is not read. +- **`ScopeKind::Covergroup` is new** (`vlog_semantic`). It costs no arm: + nothing outside `model.rs` matches `ScopeKind` exhaustively. +- **`Parser::at_postfix_segment` no longer takes a `[` that is immediately + followed by `*`, `->` or `=`.** No index expression can start with one of + those, so this says "that `[` is not an index" everywhere rather than only + inside a covergroup — which was already true, and is now acted on. It is + what lets `1'b0[*1:10]` parse as a transition repetition instead of sending + the whole covergroup down the fallback. +- **`Parser::no_with`** — one bool, set only while a bin's spec operand is + read, that stops `at_postfix_segment` from taking the bin's own + `with ( ... )` filter as an array method's iterator argument. Cleared on the + error path too, so a failed speculative parse never leaves it set. +- **`workspace.rs::collect_members` recurses into a covergroup**, so + `cg_inst.cp` finds a coverpoint declared in another file, exactly as it + already recursed into a nested class or `typedef`. `is_exported` gains a + `Covergroup` arm (its coverpoints, crosses and `sample`) and lists + `Covergroup` among what a package or class exports. +- **`resolve.rs::member_scope` accepts a covergroup**, so a handle whose + `type_name` is a covergroup opens it for a `.`. +- **`undriven-net` changes verdict**: a net read only by a coverpoint used to + have zero reads (the whole block was an `opaque_span`) and be skipped; it + now has a real one and is reported. Pinned in + `crates/vlog_linter/tests/cases/covergroups.lint`. +- **`signals.rs` no longer routes a covergroup to `opaque_spans`.** A + covergroup samples its operands and drives nothing; those reads are ordinary + resolved references now. A covergroup that fell back is still an + `ItemKind::Verbatim` and keeps the opaque posture. +- **`on_type.rs`: `covergroup` left the `OPAQUE` list.** Its items are laid + out from a real tree now, at one indent from the header, which is exactly + what an ordinary block frame computes; its bins bodies sit behind a `{`, + where an open bracket already silences the model, so they need no entry for + the reason a constraint's do not. Pinned by + `a_covergroup_body_indents_like_any_other_block`. +- **`SourceFile` gains `covergroups: u32` and `covergroup_fallbacks: u32`** — + parse statistics, documented as diagnostic-only, that nothing in the tree + depends on. `constraint_fallbacks` is left exactly as round 1 wrote it + rather than folded into a struct: churning a field five tests read to gain + symmetry is not worth a line of diff. +- **`pairs.rs` is untouched and keeps working.** `pairs::analyze` reads + *tokens*, not the tree, so `covergroup`/`endgroup` rainbow, folding and + the `with function sample` rule are unaffected by a structured node. The + `pairs.rs` unit tests are green and were not edited. + +**Requests filed, not acted on:** + +1. **The 52 gaps the fuzzer still fails are `docs/topo.md` §2.9-22's**, the + parser-wide comment-slot round round 1 filed. Every one of them is in + shared name, declaration or expression machinery — the `class`/`module` + header, `parse_tf_ports`, `parse_label`, `parse_sens_list`, + `parse_value_range`, member expressions, `take_member_prefix` — and every + one fails identically **outside** a covergroup. That classification is not + a claim in prose: `the_gaps_the_fuzzer_still_fails_fail_outside_a_covergroup_too` + in `tests/verification.rs` runs the equivalent non-covergroup source for + each shape and asserts it fails too, so if §2.9-22 is ever done, both tests + move in the same commit. +2. **Files edited outside the stated ownership list**: none, except one new + `#[ignore]`d probe, `crates/vlog_parser/tests/census.rs`, which is what + produces the sweep numbers in the work log (`CENSUS= cargo test -p + vlog_parser --test census -- --ignored --nocapture`). It is disclosed here + rather than added silently; delete it if the lead would rather the + measurement stayed external. + +## Design + +### AST + +``` +ItemKind::Covergroup(Box, // local / static / protected + before_name, name: Name, before_args, + args: Option>, // None when no parens were written + event: Option, // `with function sample(...)` | `@(...)` + before_semi, + items: Vec, dangling, + end_label: Option, before_end_semi, end_semi, +}>) + +CoverageEvent::{ Sample(Box), Clocking { before, sens: SensList } } +SampleFn { before_with, after_with, after_function, name: Name, + before_args, has_parens, args: Vec } + +CoverItem { meta, kind, before_semi, span } +CoverItemKind:: + Coverpoint(Box) + | Cross(Box, iff, before_body, body }>) + | Option(Box) + | Directive(RawText) | Empty + +CoverLabel { name: Name, comments } // the `cp :` a label is written as +CoverIff { before_kw, after_kw, after_open, before_close, expr } +CoverBody { items: Vec, dangling, span } + +BinItem { meta, kind, before_semi, span } +BinItemKind::{ Bin(Box), Option(Box), Directive, Empty } + +BinDecl { wildcard, after_wildcard, kind: BinKind, before_name, name: Name, + array: Option }>>, + eq_comments, spec: BinSpec, + with_expr: Option>, iff: Option> } +BinKind::{ Bins, IgnoreBins, IllegalBins } + +BinSpec:: + Values(Vec) // = { 0, [1:3], $ } + | Transitions(Vec) // = (a => b, c), (d => e) + | Default | DefaultSequence { comments } + | Select(SelectExpr) // = cp_x, = binsof(a) && !binsof(b) + +TransSet { meta, ranges: Vec, dangling, span } +TransRange{ arrow_comments, items: Vec, repeat: Option> } +TransRepeat { before, after_open, op: "*"|"->"|"=", comments, lo, hi, colon_comments } + +SelectExpr:: + Binsof(Box) + | Not { comments, expr } | Binary { lhs, op, comments, rhs } + | Paren { comments, expr } | Expr(Expr) +``` + +Three deviations from the brief's sketch, argued in the work log: +`event` is one `CoverageEvent` rather than a `sample` field beside an `event` +field (the LRM makes them alternatives, so two fields could represent a shape +no source can write); `OptionAssign.target` is the `Expr` the option path is +written as rather than a keyword plus a `Vec` path; and there is no +`SymbolKind::Bin`. + +### The fallback + +`Parser::parse_covergroup` takes a `Rewind` snapshot — cursor, **both** pending +comment buckets, nesting depth, chain links, open conditional regions, +diagnostics length — attempts `parse_covergroup_decl`, and on **any** error +restores the snapshot and re-runs `parse_covergroup_verbatim`, which is +v0.27.0's `parse_covergroup` body character for character. The comment buckets +are part of the snapshot because the speculative parse harvests comments into +`Meta`s it then throws away, and hard invariant #3 does not forgive that; +`a_covergroup_fallback_keeps_the_comments_written_around_it` is the test that +would have caught getting it wrong. + +The structured parse closes with `expect_kw("endgroup")`, **not** +`expect_closer` — an unclosed covergroup must *fail* here so the rewind puts +the old flat scan back, and that is what records the tolerant diagnostic. One +message, from one place, and the same one v0.27.0 wrote: +`a_covergroup_with_no_endgroup_falls_back_and_reports_it_once` pins that there +is exactly one. + +### Layout + +- The **whole header on one line**: `covergroup g(args) with function + sample(args) @(posedge clk);` — the two argument lists break like any port + list when they do not fit. The parens hug the name, which is what + `function f(int a);` already does everywhere else in lucisv. +- One cover item per line at one indent; `endgroup` back at the header's + column, with the label the source wrote and a stray `;` if there was one. +- `cp: coverpoint expr iff (cond) {` — a braced body cuddles onto the header + line and holds one bin per line at one further indent, `}` at the header's + column: a constraint set's layout, for a construct that reads the same way. + An empty body prints `{}`. +- `bins name[4] = spec with (expr) iff (cond);` — the value list breaks like + every other braced list, `:=`-style operators do not exist here, and the + three bins keywords, `wildcard`, the three repetition operators and the two + `default` spellings are printed back exactly as written because each means + something different. +- `option.per_instance = 1;` prints as the assignment it is. +- A directive item prints as raw text, both arms of an `` `ifdef `` standing + as ordinary items of the one body. +- A covergroup that fell back prints exactly as it did in v0.27.0. + +### Comment slots + +Every keyword and punctuation position this round introduced owns the comments +written in front of it, in a named field the formatter prints in place — the +rule `constraint-bodies` arrived at after its rework, applied here from the +first commit. The slots: + +| written here | kept in | +|---|---| +| `covergroup /*c*/ g` | `CovergroupDecl::before_name` | +| `g /*c*/ (args)` | `CovergroupDecl::before_args` | +| `) /*c*/ with` · `) /*c*/ @` | `SampleFn::before_with` · `Clocking::before` | +| `with /*c*/ function /*c*/ sample /*c*/ (` | `after_with`, `after_function`, `before_args` | +| `… /*c*/ ;` | `CovergroupDecl::before_semi` | +| `endgroup : g /*c*/ ;` | `CovergroupDecl::before_end_semi` | +| ` /*c*/ ;` | `CoverItem::before_semi` | +| `cp /*c*/ : /*c*/ coverpoint` | `CoverLabel::comments` | +| `coverpoint /*c*/ expr` · `cross /*c*/ a` | `after_kw` | +| `… /*c*/ iff /*c*/ ( /*c*/ e /*c*/ )` | `CoverIff`'s four fields | +| `) /*c*/ {` | `before_body` | +| `wildcard /*c*/ bins /*c*/ v` | `after_wildcard`, `before_name` | +| `v /*c*/ [ /*c*/ 4 /*c*/ ]` | `BinArray::before` + `comments` | +| `] /*c*/ = /*c*/ spec` | `BinDecl::eq_comments` | +| `default /*c*/ sequence` | `BinSpec::DefaultSequence::comments` | +| `spec /*c*/ with /*c*/ ( /*c*/ e /*c*/ )` | `BinWith`'s four fields | +| `a /*c*/ => /*c*/ b` | `TransRange::arrow_comments` | +| `b /*c*/ [ /*c*/ * /*c*/ 3 /*c*/ ]` | `TransRepeat::before`, `after_open`, `comments` | +| `[* 1 /*c*/ : /*c*/ $]` | `TransRepeat::colon_comments` | +| `binsof /*c*/ ( /*c*/ a /*c*/ ) /*c*/ intersect /*c*/ {` | `BinsofSel`'s five fields | +| `! /*c*/ binsof` · `a /*c*/ && /*c*/ b` · `( /*c*/ e /*c*/ )` | `SelectExpr`'s per-variant fields | +| `target /*c*/ = /*c*/ value` | `OptionAssign::comments` | + +Two rules keep them from fighting, both inherited from round 1: +**one owner per gap** — `CoverItemKind::takes_semi` / `BinItemKind::takes_semi` +is the single answer to "who writes the `;`", read by the parser that consumes +it and the formatter that writes it back (a coverpoint that wrote a `{ }` body +takes none) — and **a gap belongs to the construct only when the token that +closes it was written**, which is `Parser::gap_before`. + +`verify.rs` is **untouched**. Token equivalence is what proves the layout, and +the round ships twelve new attack pairs in `tests/verification.rs` regardless +(invariant #4's standing pattern: "untouched + rejection tests anyway"). + +### Binder + +- `SymbolKind::Covergroup`, declared where the covergroup is written, with a + `ScopeKind::Covergroup` child scope whose parent is that same scope — so + every sampled expression, bin value and `iff` guard binds lexically to a + class property with `this.` implicit, exactly as a constraint body's names + do. +- That scope declares the covergroup's formal arguments (`TfArg`), the + `sample` method (`Function`, so `cg.sample(x)` resolves) and its arguments, + and one `Coverpoint` / `Cross` symbol per **labelled** coverpoint and cross. + An unlabelled coverpoint declares nothing, which is what the LRM says: there + is no name to reach it by. +- `cross a, b` and `binsof(cp_a)` are ordinary lexical uses, so they land on + those `Coverpoint` symbols. +- A clocking event is bound in the **enclosing** scope: it is written in the + header, before anything inside exists. +- An `option.x` target is not recorded at all — an option names a covergroup + built-in, not anything this crate models — while its value is an ordinary + expression and is. +- A bin's `with ( ... )` filter is bound in a `ScopeKind::Block` child that + declares `item`. `item` is never *written* as a declaration, so the + declaration points at the **first use of it inside the filter**: every name + this crate records must be locatable in the source (the corpus test's + "0 names unplaced" contract), and an invented span is not. A filter that + never says `item` declares nothing. + +## Status / TODO + +- [x] `ast.rs`: `ItemKind::Covergroup`, `CovergroupDecl`, `CoverageEvent`, + `SampleFn`, `CoverItem(Kind)`, `CoverpointDecl`, `CrossDecl`, + `CoverLabel`, `CoverIff`, `CoverBody`, `BinItem(Kind)`, `OptionAssign`, + `BinDecl`, `BinKind`, `BinArray`, `BinSpec`, `BinWith`, `TransSet`, + `TransRange`, `TransRepeat`, `SelectExpr`, `BinsofSel`, + `SourceFile::covergroups` / `covergroup_fallbacks` +- [x] Parser: every header, cover-item, bin and select shape; the exact + rewind-to-verbatim fallback +- [x] Formatter: canonical layout; the fallback prints exactly as before +- [x] `verify.rs` untouched; the two existing covergroup attack pairs + re-derived and twelve more added +- [x] Binder: `SymbolKind::Covergroup`/`Coverpoint`/`Cross`, + `ScopeKind::Covergroup`, the implicit `item`, export rules, + `FACTS_FORMAT` 12 +- [x] Linter: `visit.rs` arm (documented no-op), `signals.rs` no longer opaque + for a structured covergroup, `covergroups.lint` +- [x] Server: `symbols.rs` label + LSP kind, `completion.rs` kind, + `tokens.rs` highlight, `covergroup` out of `on_type.rs`'s `OPAQUE` +- [x] The gap fuzzer, committed, with its classification asserted beside it +- [x] Tests: 29 parser (plus 3 pre-existing ones re-derived), a `spans.rs` + walker and 2 sources, 30 formatter cases + the `classes.cases` case + re-derived, 14 verification (12 attack pairs + the fuzzer and its + classification), 12 semantic, 2 e2e, 4 lint cases +- [x] Gates: fmt / clippy / `cargo test --workspace` / corpus gate / vsix + smoke / opentitan read-only sweep +- [ ] **Filed, not done:** the 52 shared-machinery comment slots + (`docs/topo.md` §2.9-22). + +## Work log + +### 2026-09-02 — dev + +**The ten words the round did not reserve.** `coverpoint`, `cross`, `bins`, +`ignore_bins`, `illegal_bins`, `wildcard`, `binsof`, `intersect`, `option`, +`type_option` and `sample` are all matched by text through round 1's +`word_at`, plus a two-line `bin_kind_at`. The argument is round 1's, and the +`token.rs` choke point is untouched. `sequence` is the one word that *is* read +as a keyword — because it already is one (`sequence ... endsequence`), so +`default sequence` asks `is_kw` rather than `word_at`; the first draft asked +`word_at` and `default sequence` fell back, which the probe caught in the +first ten minutes. + +**Which grammar a `(` opens: the round's one real design correction.** The +first draft decided between a transition list and a parenthesized select +expression by scanning for a `=>` directly inside the parentheses. It read +opentitan's `hw/ip/rom_ctrl/dv/cov/rom_ctrl_cov_if.sv` wrong: + +```systemverilog +bins zero_delay_5 = (1'b1[*5]); +``` + +is a transition list of one range with a repetition and no arrow at all, so +the scan said "select expression", `1'b1` is not a name, and the whole +covergroup fell back. The fix is the LRM's own rule: a **coverpoint** bin's +`( ... )` is a `trans_list` (§19.5.1.2) and a **cross** bin's is a +`select_expression` (§19.6.1) — decided by where it is written, which the +parser already knows, so `parse_bin_spec` takes an `in_cross` flag and the +lookahead scan is gone entirely. Simpler *and* correct. + +**Two guards in shared expression machinery, both stated as global truths.** + +- `at_postfix_segment` no longer takes a `[` immediately followed by `*`, + `->` or `=`. Without it `1'b0[*1:10]` sends the whole covergroup down the + fallback, because `parse_postfix_inner` takes the `[` and then fails on the + `*`. It needs no covergroup context: no index expression can begin with one + of those three tokens anywhere in the language, so the guard says something + that was already true. `a_repeat_bracket_never_steals_an_ordinary_index` + pins that `q[3]`, `r[a:b]` and `s[i +: 2]` are unaffected. +- `Parser::no_with` — one bool, set only while a bin's spec **operand** is + read. `with (` is a postfix segment everywhere else (an array method's + iterator argument); in a bin spec it introduces the bin's own filter, and + the expression parser has to stop in front of it. It is cleared before the + `?`, so a failed parse never leaves it set, and + `a_bins_with_filter_is_never_read_as_an_array_method` pins both halves in + one file. The alternative — a private restricted postfix parser — would have + duplicated twenty lines of `parse_postfix` to say the same thing. + +The bin spec's bare operand is read at the **postfix** level rather than with +`parse_ternary`, so it stops in front of the `&&` and `||` this grammar reads +itself, and it accepts the call opentitan writes in +`hw/ip/csrng/dv/cov/csrng_cov_if.sv`: `bins single_exc[] = +single_masks(num_hw_apps);`. Tools accept it, the LRM does not spell it, and +reading it costs nothing. Those two files were the round's only two fallbacks +in all of opentitan; both are now structured, and both shapes have parser +pins. + +**Three AST deviations, all shape-not-substance.** `CoverageEvent` is one +field rather than the brief's `sample` beside `event`, because IEEE 1800 §19.3 +makes the two spellings alternatives of one `coverage_event` and two fields +could hold a shape no source can write. `OptionAssign.target` is the `Expr` +the path is written as rather than a keyword plus a `Vec`: an option +name resolves to nothing lucisv models, the expression printer already writes +a dotted chain back exactly, and splitting it would only have bought +per-segment comment slots that no other member access in the language has +(§2.9-22). And there is no `SymbolKind::Bin`, for the reason in Assumptions. + +**`item` needed a scope, and then it needed a span.** Binding a `with` filter +in the covergroup scope gives a *wrong* answer whenever the class declares a +property called `item` — which UVM code does constantly — and then renaming +that property rewrites a filter that never named it. So the filter gets a +`Block` scope of its own declaring `item`. The first draft gave that +declaration an **empty** span, on the theory that rename's `unspelled` refusal +would then protect it; the corpus test disagreed, loudly and correctly — +`every_corpus_file_analyzes_without_panicking` asserts *0 names unplaced*, and +11 implicit `item`s were unplaced. The declaration now points at the first use +of `item` inside the filter, which slices back to `item` exactly. If the +filter never says `item`, nothing is declared. + +**`visit.rs` gets an arm that does nothing, on purpose** — round 1's ruling, +unchanged: a covergroup body contains cover items and expressions, not `Item`s +or `Stmt`s, so an item or statement walk has nothing to descend into. The +rules that see inside do it through the reference table, and one of them +changed verdict (below). + +**One real lint behaviour change, pinned.** `undriven-net` skips a net with +`reads == 0`. A net read only by a coverpoint used to have zero reads, because +the whole block was an `opaque_span`; it now has a real one. On + +```systemverilog +module m; + wire w; + covergroup cg; + cp: coverpoint w; + endgroup +endmodule +``` + +v0.27.0 reports nothing and this tree reports `w`, correctly. +`covergroups.lint` case 1 pins it, case 2 pins that the verbatim fallback goes +back to silence. + +**`on_type.rs`: `covergroup` left `OPAQUE`, and the entry it left behind is +the honest one.** The list is "scopes whose bodies the formatter keeps +byte-for-byte". A covergroup's no longer is, and an ordinary block frame +computes exactly the right answer — one indent from the header. Its bin bodies +sit behind a `{`, where an open bracket already silences the model, which is +why a constraint needs no entry either. The old test's fixture was a +covergroup; it is now a `property`, which is what the list is still for. + +**The gap fuzzer, from day one.** Round 1 built one after QA found six dropped +comment slots; this round wrote it first and shipped it as a test: +`a_comment_in_every_covergroup_gap_still_formats` puts a `/*C*/` in **every** +inter-token gap of ten fixtures covering the whole sub-grammar — **329 gaps** +— and demands `format_source` succeed *and* be idempotent for each. It found +exactly one slot of this round's own: the gap between a repetition's `[` and +its operator, now `TransRepeat::after_open`. The other **52** are shared +machinery, and the classification is asserted rather than asserted-in-prose: +`the_gaps_the_fuzzer_still_fails_fail_outside_a_covergroup_too` runs the +equivalent non-covergroup source for each of the eighteen shapes and requires +it to fail too. All 18 do. + +| shape | n | owner | +|---|---|---| +| `class /*c*/ c` / `class c /*c*/ ;` | 18 | the class header | +| `module /*c*/ m` / `module m /*c*/ ;` | 2 | the module header | +| a `tf_port_list` type, dimensions and name | 13 | `parse_tf_ports` | +| `endgroup /*c*/ : g` / `endgroup : /*c*/ g` | 4 | `parse_label` | +| `@ /*c*/ (` / `@(posedge /*c*/ clk)` | 2 | `parse_sens_list` | +| `[ /*c*/ 0 : 3 /*c*/ ]` | 8 | `parse_value_range` | +| `option /*c*/ . /*c*/ per_instance` | 4 | member expressions | +| `local /*c*/ covergroup` | 1 | `take_member_prefix` | + +That is the honest bar and it has not been quietly widened: an +`ItemKind::Verbatim` body made all of these work before this round, so a file +with a comment in one of them is a real regression *for covergroups +specifically* — it is just not one this lane can fix without editing machinery +it does not own. Filed as request 1. **No opentitan or corpus file hits one**: +every file that formatted before still formats. + +**Measurements.** + +*OpenTitan `hw`, 3 975 `.sv`/`.svh`, read-only `--no-cache --check`, against a +release build of v0.27.0 (`53bc293`) in a detached worktree.* The checkout had +exactly three modified files before the sweep and exactly the same three after +(the owner's `aes/dv/tb/tb.sv` and the two `ast.sv`s). + +| | v0.27.0 | this tree | +|---|---|---| +| files that fail to format | 12 | **12** | +| newly failing (set difference) | — | **0** | +| newly fixed | — | 0 | + +The two error lists are byte-identical when sorted. `--check` runs +`format_source`, which runs *both* halves of the safety net, so "12 failures, +the same 12" is also the statement that **3 963 real files — carrying 544 +freshly laid-out covergroups — are token-equivalent to their input and +idempotent.** That is why `verify.rs` needed no widening. + +*Tolerant-mode diagnostics over the same 3 975 files*, measured with the +`census` probe against each tree's own `vlog_parser`: + +| | v0.27.0 | this tree | +|---|---|---| +| total diagnostics | 1 105 | **1 105** | +| files with any | 12 | **12** | +| per-file difference | — | **none** (`diff` of the per-file lists is empty) | + +*The covergroup census, opentitan `hw`:* + +| | count | +|---|---| +| covergroups parsed **structured** | **544** | +| covergroups that fell back | **0** | +| `constraint_fallbacks` (round 1's number, unmoved) | 29 | + +*Layout.* **81 of the 3 963** opentitan files that format change layout, and +all 81 verify — the count comes from formatting every file through both +binaries' `--stdout` and diffing, and `--stdout` only succeeds when +`format_source`'s own token-equivalence check passes. + +*The DV sweep the brief asked for*: every `.sv`/`.svh` under `hw/dv`, +`hw/ip/*/dv` and `hw/top_*/dv` containing the word `covergroup` — **87 files** +— formatted with `--stdout` and then formatted again: + +| | files | formatted | idempotent | +|---|---|---|---| +| result | 87 | **87/87** | **87/87** | + +A `--stdout` that succeeds has already had its whole token stream — comments +included, in order — compared against the input by `verify_equivalence`, so +"87/87 formatted" *is* "87/87 comment streams preserved and ordered". + +*Corpus (860 files).* `scripts/corpus_gate.sh corpus` → +`{"passing":813,"total":820,...}`, **0 verification errors, 0 crashes** — +exactly the baseline. **10 of 853** files that both binaries format change +layout, and all 10 verify. Census: **27 covergroups structured, 0 fallbacks** +over the 817 `.sv`/`.svh` files. + +*Corpus resolution column* (`vlog_semantic`'s +`the_corpus_index_finishes_most_external_references`, every-file row): + +| | v0.27.0 | this tree | +|---|---|---| +| symbols recorded | 27 219 | **27 472** (+253) | +| references recorded | 101 199 | **102 338** (+1 139) | +| resolved in-file | 70.4% | 70.4% | +| nowhere to jump | 1 162 (1.15%) | 1 166 (**1.14%**) | + +Covergroup bodies contributed **1 139 references that did not exist at all +before** — they were not unresolved, they were unrecorded — and **1 135 of +them (99.6%) are answered**. The four that are not are names whose declaration +is outside the corpus. "0 names unplaced" holds in both trees. + +**Gates.** `cargo fmt --all -- --check` clean · `cargo clippy --all-targets +--workspace` **0 warnings** · `cargo test --workspace` green (**43 binaries, +3 009 passed, 0 failed**) · `scripts/corpus_gate.sh corpus` 813/820, 0 +verification errors · `cargo build -p lucisv_server` + `node +editors/vscode/smoke.js target/debug/lucisv-server` OK · OpenTitan sweep +unchanged, checkout untouched. + +## QA log + +### 2026-09-02 — QA + +**Verdict: SHIP.** Every gate reproduces the dev's numbers exactly; the two +shared-machinery guards were attacked directly and hold; an independent +89-file/3-fixture re-derivation of the fuzzer classification found zero +covergroup-bodies-specific regressions; the 87-file DV sweep and the full +opentitan/corpus sweeps reproduce byte-for-byte. One gap found in the attack +pairs (a dropped bin-array `[]` marker had no pin) — closed directly, per +the QA charter's "small unambiguous fixes." + +**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets +--workspace` 0 warnings, verified with a forced rebuild (`touch`ed +`parser.rs`/`format.rs`/`bind.rs` first, not a cache hit). `cargo test +--workspace`: **43 binaries, 3 010 passed, 0 failed** (3 009 plus the one +attack pair added below). `scripts/corpus_gate.sh corpus` → 813/820, 0 +verification errors — matches the dev's number exactly. `cargo build +--release` clean. `node editors/vscode/smoke.js target/debug/lucisv-server` +→ OK. `cargo test -p lucisv_server --test grammar` → 3/3. No +`.unwrap()`/`.expect()`/`panic!` added to library code: checked every hit in +`git diff` for every changed non-test file (`ast.rs`, `parser.rs`, +`format.rs`, `bind.rs`, `facts.rs`, `model.rs`, `resolve.rs`, `workspace.rs`, +`signals.rs`, `visit.rs`, `completion.rs`, `on_type.rs`, `symbols.rs`, +`tokens.rs`) against each file's own `#[cfg(test)]`/`mod tests` line number — +every hit in `parser.rs` falls at or after its test module (line 6781); +every other changed file has zero. + +**Scope.** `verify.rs`, `token.rs`, `pairs.rs`, `lexer.rs`, +`editors/vscode/syntaxes`, `vlog_refactor`: all absent from `git diff +--stat`, confirmed. `pairs.rs`'s own unit tests (65, in +`lucisv_server::pairs`) are green and untouched. Files touched outside the +README's list: none, except the disclosed `census.rs` probe (see below) — +plus release-prep files already sitting in the tree ahead of QA +(`Cargo.toml`/`Cargo.lock`, `CHANGELOG.md`, `docs/topo.md`, +`editors/vscode/{CHANGELOG,README,package.json}`, all bumped to 0.28.0), +which is the same pattern `constraint-bodies`' QA noted as its Finding 2 — +not this lane's doing, not re-litigated here. + +**The two shared-machinery guards, attacked directly.** +- `at_postfix_segment`'s `[* / [-> / [=` refusal: constructed + `arr[i]`, `arr[i:i+2]`, `arr[i+:2]`, `arr[i*2]` (an index *starting* with + an identifier then `*`), `q[$]`, `q[$-1]` — all still parse as ordinary + indexes, format, and are idempotent. Grepped opentitan `hw` for `\[\*` and + `\[->` (58 files, zero for `\[=`): all 58 format with `--stdout` with zero + verification errors, and the exact same 50/58 "would reformat" as a + v0.27.0 baseline built in a detached worktree (`git worktree add --detach + /tmp/lucisv_v27_baseline 53bc293`) — the reformat set is byte-identical + sorted. A synthetic `sequence`/`property` file with `[*3]`, `[*2:4]`, + `[->2]` in assertion bodies (verbatim territory) formats and stays + idempotent — the guard does not reach into assertion verbatim capture. +- `no_with`: `arr.find with (item > 0)`, `arr.find(item) with (item > 0)`, + `q.sort with (item.x)`, `x = q.sum with (item)` all still parse correctly + **outside** a covergroup (no_with is scoped to the bin-spec-operand read + only). Inside a covergroup: `bins single_exc[] = single_masks(num_hw_apps);` + and `bins b = single_masks(num_hw_apps) with (item > 0);` (the two real + opentitan shapes the work log names) both parse structured and round-trip. + Nested `with ... with` in one bin spec (`arr.find with (a) with (b)`, + which the LRM does not define) correctly falls back to the verbatim + capture rather than mis-parsing — confirmed by injecting ragged whitespace + into the bin line and observing it survive untouched in the output, i.e. + the covergroup really took the fallback path, not a lucky canonical match. + +**Corruption + comment hunt.** `find hw/dv hw/ip/*/dv hw/top_*/dv -name +'*.sv' -o -name '*.svh' | xargs grep -l covergroup` → **87 files**, matching +the dev's count. `--stdout` twice each, idempotency + a string-aware +`//`/`/* */` comment-stream extractor comparing content and order against +the original input: + +| | files | formatted | idempotent | comment stream preserved | +|---|---|---|---|---| +| result | 87 | **87/87** | **87/87** | **86/87 clean; 1 pre-existing** | + +The one apparent mismatch (`hw/ip/kmac/dv/env/kmac_scoreboard.sv`) is a +multi-line block comment whose *internal* indentation shifts when the +comment block itself is reindented — reproduces byte-for-byte identically +on the v0.27.0 baseline binary, and the file contains no actual +`covergroup` declaration at all (the grep hit is the word appearing inside +a comment) — not a covergroup-bodies regression by any measure. Eyeballed +10 DV files (`csrng_cov_if.sv`: `with function sample(...)` header +breaking like a port list, `bins single_exc[] = single_masks(...)`, +`ignore_bins ... binsof(...) intersect {...} with (...)`; +`rom_ctrl_cov_if.sv`: all four of `zero_delay_5 = (1'b1[*5])`, +`stall_1 = (1'b1 => 1'b0 => 1'b1)`, `stall_long`/`stall_repeat` with +`[*5:10]`/`[*1:10]` — the exact work-log example, correctly not misread as +an index; `usbdev_env_cov.sv`: eight `cross ... { }` bodies and +`endgroup`, no bare `endgroup : g` mishandling). `git -C +.../opentitan status --short` before and after every read-only run: +unchanged, the same 3 pre-existing owner files +(`hw/ip/aes/dv/tb/tb.sv`, the two `top_*/ip/ast/rtl/ast.sv`s). + +Scratch attacks, each formatted with `--stdout` and checked for +idempotency: `` `ifdef ``/`` `else ``/`` `endif `` arms as cover items +inside a `{ }` body; a bin body's `}` at column 0; CRLF line endings; +escaped identifiers as the covergroup name, a coverpoint label and a bin +name; an empty covergroup (`{}`... actually just `endgroup` with nothing +between); an unlabelled coverpoint; `bins b[] = {[0:$]};`; a 3-arrow +transition `bins t = (a => b => c);`; `with function sample(int a, bit +b);` with a real argument list; a macro-expanded covergroup body +(`` `define MY_CG(NAME) covergroup NAME; ... endgroup``) — byte-identical +output to the v0.27.0 baseline, confirming the fallback capture is +unchanged. **All ten formatted and round-tripped cleanly.** `covergroup cg +@@(begin_tr);` (the LRM's other coverage-event spelling, which this round's +`CoverageEvent` does not model) correctly falls back to verbatim — confirmed +with ragged internal whitespace surviving untouched in the output, the same +technique used for the nested-`with` case above. + +**Fuzzer re-derivation, independent.** Wrote a fresh, standalone Python +tokenizer + gap-injector (not the dev's code) and ran it over three fixtures +of my own, none shared with the dev's ten: a transition-heavy body (four +`TransSet`s including `[*2:5]`, `[->3]`, `[=2]`, a multi-value transition), +a cross with `binsof ... intersect ... && !binsof ... intersect`, and an +options/wildcard/ignore/illegal/default body. + +| fixture | gaps | failing | +|---|---|---| +| transition-heavy | 120 | 11 | +| cross + binsof/intersect | 109 | 9 | +| options/wildcard/ignore/illegal | 111 | 17 | +| **total** | **340** | **37** | + +Classified all 37 by constructing the equivalent non-covergroup source at +the same gap position and running it through the v0.27.0 baseline binary: +five shapes match the dev's own table exactly (class header before/after +name and semicolon, `option.`/`type_option.` member-dot, a value-range +inside a braced set — `binsof(...) intersect {[ /*C*/ 0:3]}`); four more do +not appear in the dev's table but reproduce identically on **plain +declarations containing no covergroup at all** on the same v0.27.0 build: +`rand /*C*/ bit x;` (a qualifier-to-type gap), `bit /*C*/ [3:0] x;` (a +declarator's type-to-dimension gap), and the three packed-dimension range +positions `bit [ /*C*/ 3:0]` / `bit [3 /*C*/ :0]` / `bit [3:0 /*C*/ ]`. All +nine shapes fail on v0.27.0. **Zero new findings; zero covergroup-bodies- +specific regressions**, extending the dev's own §2.9-22 classification +rather than contradicting it. + +**Corpus resolution column, independently reproduced.** +`cargo test -p vlog_semantic --release --test corpus -- --nocapture`: +`860 files, 27472 symbols, 102338 references — 70.4% resolved in-file, ... +1.14% unresolved (1166), 0 names unplaced` — matches the dev's table +exactly, cell for cell. `CENSUS=/hw cargo test -p vlog_parser +--release --test census -- --ignored --nocapture`: `files=3975 +covergroups=544 covergroup_fallbacks=0 constraint_fallbacks=29 +diagnostics=1105 files_with_diagnostics=12` — exact match. Same over this +repo's `corpus/`: `files=817 covergroups=27 covergroup_fallbacks=0` — exact +match. + +**Opentitan full sweep, independently reproduced.** `--check --no-cache hw` +against both this build and the v0.27.0 baseline: **13 files fail on both, +byte-identical error-message sets** (the 12→13 drift is the checkout's own +`ast.sv` mid-edit, not a regression — same phenomenon `constraint-bodies`' +QA logged at its own re-verification pass). Copied `hw/` to two scratch +trees and formatted each in place with its own binary (avoids one-process- +per-file overhead over ~3.9k files): **3 858 files reformatted, 108 +unchanged, 13 failed — identical on both binaries.** `diff -rq` between the +two output trees: 81 files differ; every one of the 78 that survived clean +path-extraction contains the word `covergroup` (0 that don't) — the layout +changes are exactly and only this round's doing. Same exercise over this +repo's `corpus/`: **10 files differ, all 10 contain `covergroup`** — matches +the dev's "10 of 853" exactly. `git -C .../opentitan status --short`: +unchanged throughout, the same 3 owner files. + +**Attack pairs.** Read all 14 covergroup-shaped tests (12 new + 2 +re-derived, matching the README's count). Re-ran them: all pass, all +correctly reject their corrupted pair. **Gap found**: no pin existed for a +dropped bin-array `[]` marker (`bins z[] = {0,1};` → `bins z = {0,1};`, +which changes "one bin per value" into "one bin for both" — a real +semantic change to what the covergroup counts) nor for a widened fixed +array size (`z[2]` → `z[4]`). Added +`a_dropped_bin_array_marker_is_rejected` to +`crates/vlog_formatter/tests/verification.rs` (right after +`a_dropped_bins_qualifier_is_rejected`), confirmed it exercises +`verify_equivalence` genuinely (not a no-op — the two literal strings really +have different token streams) and passes. `fmt`/`clippy` clean on the +addition; full `cargo test --workspace` re-run afterward (see Gates above). + +**Semantics.** Read `crates/vlog_semantic/tests/covergroups.rs` (356 lines, +12 tests: self/sample/label declaration, sampled-expression binding, +cross-operand-to-coverpoint binding, sample-argument scoping, the `item` +shadow test with both the "shadowed" and "not shadowed" halves, the +`option.`/`type_option.` target-vs-value split, a fallback binding nothing, +a clocking event naming the enclosing scope, cross-file coverpoint +reachability, covergroup member export, a base-class property answered +cross-file, and index-determinism) and both e2e tests +(`renaming_a_rand_field_rewrites_its_coverpoint_uses`, +`renaming_a_rand_field_reaches_a_coverpoint_in_another_file`) — the second +is non-trivial: definition from the covergroup file into a base class in +another file, then a rename from the base declaration that edits both +files, asserted by URI and line. Ran both explicitly +(`cargo test -p vlog_semantic --test covergroups`, +`cargo test -p lucisv_server --test e2e coverpoint`): 12/12 and 2/2. Did not +independently re-drive the LSP session over a raw socket (no separate +client available); relied on reading the `talk()`-based test bodies plus +the green run, same posture `constraint-bodies`' QA took for its own e2e +tests. + +**Linter.** `crates/vlog_linter/tests/cases/covergroups.lint` read: four +cases matching the README (undriven-net now sees a coverpoint read; a +fallback covergroup stays opaque; `empty-item` does not fire on a null +cover/bin item; an item walk still reaches past a covergroup to a class +member). `lucisv check corpus/` with this release binary and the v0.27.0 +baseline: **7 932 violations, both binaries, identical** — no new false +positive from coverpoint operands now resolving. + +**Docs.** README follows the template, the fallback census and the +work-log numbers all reproduced exactly (see above). The `census.rs` probe +is `#[ignore]`d, read-only, touches no other file, and is disclosed in the +README's Handshakes section exactly as it should be — informational, the +lead's call whether it stays. TODO §21 QA line added below. + +**Small fix made directly, per the QA charter:** added +`a_dropped_bin_array_marker_is_rejected` to +`crates/vlog_formatter/tests/verification.rs` (see Attack pairs above) — +the one gap this checklist's own guidance asked QA to check for +("a bin array `[]` dropped"). No other file was modified. + +## Review + +## Review + +**2026-09-02 — lead.** Approved and committed; coverage_gaps C1 is closed +for both constraints and covergroups. + +- The round used the constraint round as its template and improved on the + order of operations: the comment-gap fuzzer was built in from day one + rather than after a QA rework, and its classification is *asserted* + (`the_gaps_the_fuzzer_still_fails_fail_outside_a_covergroup_too` runs + each remaining shape outside a covergroup and requires the same failure) + rather than claimed. Zero fallbacks over opentitan's 544 covergroups is + the result of replacing a lookahead scan with the LRM's own positional + rule for the bin `(…)` ambiguity — the kind of decision that gets simpler + and more correct at once. +- **The one risk was the two guards in shared expression machinery**, and + the lead read both: `at_repeat_bracket` is a two-token look for `[` then + `*`/`->`/`=`, which no index can begin with; `no_with` is reset + unconditionally before the `?` propagates, so an error inside a bin spec + cannot leak it into the rest of the file. QA attacked both against 58 + opentitan files carrying `[*`/`[->` and every array-method `with` shape, + in and out of covergroups; the whole corpus and tree re-verified under + them. Accepted. +- `verify.rs` untouched; twelve attack pairs from the dev plus QA's + thirteenth (a dropped bin-array `[]`, a real semantic change). 87/87 DV + covergroup files idempotent with comment streams byte-identical; the + sweep's failure set and per-file tolerant diagnostics identical; corpus + +1 139 references, 1 135 answered. Renaming a `rand` field now rewrites + the coverpoints that sample it as well as the constraints that bound it. +- `on_type.rs` keeping `covergroup` opaque is accepted on the dev's + argument (bin bodies sit behind a `{` a bracket already silences); the + `census.rs` probe stays as an `#[ignore]`d measurement. Lead's one edit: + the `Rewind` doc comment now names its third caller. +- Gates re-run by the lead: fmt clean, clippy zero warnings, 3 009 passed / + 0 failed over 43 binaries (3 010 with QA's pin), corpus 813/820, smoke + OK. `docs/topo.md`: two rows. Ships as 0.28.0 (FACTS_FORMAT 12). diff --git a/docs/features/vlog-semantic/README.md b/docs/features/vlog-semantic/README.md index f30cdb9..1813a12 100644 --- a/docs/features/vlog-semantic/README.md +++ b/docs/features/vlog-semantic/README.md @@ -724,3 +724,37 @@ Two new kinds and one new target: Corpus effect (860 files, both layers): references 99,553 → 101,199, of which 1,646 are new names inside constraint bodies that bound nothing at all before. See `docs/features/constraint-bodies/README.md`. + +--- + +## Amendment — 2026-09-02, `covergroup-bodies` (TODO.md §21) + +Three new symbol kinds and one new scope kind: + +- `SymbolKind::Covergroup` — a `covergroup g ... endgroup` name, declared + wherever the covergroup is written. A package or class exports it on the + same terms it exports a class; `member_scope` opens it for a `.`, and + `collect_members` recurses into it, so `cg_inst.cp` reaches a coverpoint + declared in another file. +- `SymbolKind::Coverpoint` / `SymbolKind::Cross` — a **labelled** `cp : + coverpoint e` and `cr : cross a, b`. Both are exported by the covergroup + that declares them. An unlabelled one declares nothing. +- `ScopeKind::Covergroup` — the body. Its lookup rules are a block's, its + parent is the scope the covergroup is written in, and it declares the + covergroup's formals, its `sample` method and that method's arguments + alongside the coverpoint and cross names. + +`FACTS_FORMAT` is bumped **11 → 12** for the three kinds. Nothing outside +`model.rs` matches `ScopeKind` exhaustively, so that variant cost no arms. + +One implicit declaration: `item` inside a bin's `with ( ... )` filter +(IEEE 1800 §19.5.1.1) is bound in a `Block` scope of its own, so a class +property called `item` cannot capture it. It is never written as a +declaration, so the declaration points at the **first use of it inside the +filter** — every name this crate records must slice back to itself, which the +corpus test's "0 names unplaced" assertion enforces. + +Corpus effect (860 files, both layers): references 101,199 → 102,338, of which +1,139 are new names inside covergroup bodies that bound nothing at all before, +and 1,135 of those are answered. See +`docs/features/covergroup-bodies/README.md`. diff --git a/docs/topo.md b/docs/topo.md index 0437c2d..8c4935f 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -361,6 +361,7 @@ recursion-limit, whose edges sit in §2.1). Code edges: | `null-items ──▶ corpus-check / safety-net` | depends | `ItemKind::Empty` (2026-09-01): a lone `;` where an item belongs — IEEE 1800-2017 A.1.4's null item — accepted in every item scope by one branch at the top of `parse_item_kind`. The variant's exhaustive-arm cost was paid in exactly the three places §3.3 predicts (`format.rs`, `bind.rs`, `tests/spans.rs`); every other walker is catch-all and a leaf needs nothing. Formatter layout is decided from `src` spans in `item_seq` (glued to the previous sibling's line when no newline separates them and the `;` carries no docs of its own; else its own line), so the AST carries no layout flag. `verify.rs` untouched, seven attack pairs added; corpus byte-identical at 813/820, measured against the pre-change binary. Ships with the `empty-item` lint (slang's `-Wempty-member`) and its safe fix — see §2.4. | | `escaped-identifiers ──▶ safety-net / spans` | depends | (2026-09-02) An escaped identifier is terminated by whitespace (IEEE 1800 §5.6.1) and the lexer ends the token *before* it, so the formatter — which emitted every name bare or through a `format!` splice — produced `\my-signal;`, one token on re-lex, and the safety net refused the whole file. Fix: one choke point (`format::named`/`name_doc`, predicate `ends_escaped` because parser-joined composites end inside an escaped name) that fifty emission sites go through; the space is unconditional and the printer's trailing trim removes it before a break. `verify.rs` untouched, eight attack pairs; corpus neutral by construction. Ran in a worktree in parallel with member-completion (disjoint files). Open: §2.9-21. | | `constraint-bodies ──▶ classes / out-of-class-constraints / dv-statements / safety-net` | depends | (2026-09-02, round 1 of coverage_gaps C1) `ItemKind::Constraint(ConstraintDecl)` with a structured `ConstraintSet` (`Expr{soft}`, `Implication`, `If`, `Foreach`, `SolveBefore`, `Unique`, `DisableSoft`, `Directive`, `Empty`), `ExprKind::Dist`, and `WithConstraint.block` as `ConstraintBody::{Items, Verbatim}`. The parser takes a `Rewind` snapshot (cursor, **both pending-comment buckets**, depth, links, `open_conds`, diagnostics length), attempts the structured body, and on any error restores it and re-runs v0.26.0's verbatim capture character for character — so an unknown shape *is* the old behavior, not an approximation (pinned on text, slice and `col`). **No keywords reserved**: `soft`/`dist`/`solve`/`before` are matched by text like `restrict`, so `token.rs`, `pairs.rs`, the editor grammar and `tests/grammar.rs` are untouched and `logic before;` keeps working; `:=`/`:/` stay two tokens with a span-adjacency check (a `:/` token would swallow `:/* c */`). Canonical layout: one item per line, `}` at the header column, dist weights as a braced list; a `with` block keeps the source's one-line-or-not shape. `verify.rs` untouched; the constraint attack pairs re-derived plus new ones. Exhaustive arms paid in `format.rs`, `bind.rs`, `tests/spans.rs`; `visit.rs` gets an explicit no-op arm (no items/statements inside). **QA rework**: comments after the round's own text-matched words were dropped; the dev answered with an exhaustive gap fuzzer (a `/*C*/` in every inter-token gap of 15 fixtures, 358 gaps, format + idempotency demanded) and 14 named comment fields plus `ConstraintItemKind::takes_semi()` (one owner of the `;`) and `Parser::gap_before` (the closer-side twin of `take_before_open`); 96 regressions vs v0.26.0 became 40, all in shared machinery outside this lane — §2.9-22. Opentitan: 1 993 of 2 009 bodies structured (fallbacks: 10 macro-item bodies, 6 non-LRM shapes), failure set unchanged, per-file tolerant diagnostics identical, 48 DV files idempotent with comment streams byte-identical. | +| `covergroup-bodies ──▶ constraint-bodies / classes / safety-net` | depends | (2026-09-02, round 2 of coverage_gaps C1) `ItemKind::Covergroup(Box)` with `CoverItemKind::{Coverpoint, Cross, Option, Directive, Empty}`, `BinDecl { wildcard, kind, name, array, spec: BinSpec::{Values, Transitions, Default, DefaultSequence, Select}, with_expr, iff }`, `SelectExpr` for `binsof … intersect … && !binsof`, one `CoverageEvent` enum. Same `Rewind` fallback as constraints — v0.27.0's flat scan re-run character for character on any failure — and no keywords reserved (`coverpoint`, `bins`, `cross`, `binsof`, `intersect`, `wildcard`, `ignore_bins`, `illegal_bins`, `option`, `type_option` by text). **Two guards in shared expression machinery, the round's one risk**: `at_postfix_segment` refuses `[` followed by `*`/`->`/`=` (no index can start with those — it is what lets `1'b1[*5]` be a transition repeat), and a `no_with` flag while a bin spec operand is read (so the bin's own `with (…)` filter is not eaten as an array-method iterator argument); `(`-disambiguation is by position, the LRM's own rule. `plain_expr_list` → `plain_list` and `constraint_parens` → `guard_parens`, shared with `iff`/`with`. `verify.rs` untouched, twelve attack pairs. The gap fuzzer was built in from day one (329 gaps, 52 fail, all §2.9-22 shared machinery — *asserted* by running each shape outside a covergroup). Opentitan: 544 of 544 covergroups structured, 87/87 DV covergroup files idempotent, failure set and per-file diagnostics identical. `on_type.rs` keeps `covergroup` OPAQUE by argument. | | `formatter-bug-fixes (round 2) ──▶ safety-net` | depends | Three comment-shape bugs fixed in `format.rs` (`then_is_block` trailing-line-comment cuddle guard, `Fmt::header_parens`, `default_has_colon`); `verify.rs` untouched, four masked-corruption rejection pairs added per the standing template, plus three more for the directive capture at merge (2026-08-29 testbench wave, Lane B + lead). | | `lexer-cleanup ──▶ error-recovery / lint-rules-2` (QA logs) | depends | Fixes three lexer gaps: `@(* )` (TODO §1) plus the BOM and non-ASCII-honesty findings those two QA rounds filed; adds `ParsedSource::lex_error()` so `lucisv check` stops silently passing unlexable files. | | `error-recovery ─▶ lucisv-server / linter-core` | depends (downstream) | `parse_source_tolerant` is the entry point the whole LSP and the linter stand on; the strict/tolerant split (shared grammar, no second parser) is the contract. | @@ -439,6 +440,7 @@ promise: | `interface-semantics ◀──▶ workspace-index / index-persistence / class-member-access / editor-scopes` | handshake | **`FACTS_FORMAT` 7 → 8** (2026-09-01): three new kind names (`Interface`, `Modport`, `Clocking`), no layout change. `SymbolKind::is_instantiable()` (`Module | Interface`) is the predicate every "is this a module" filter now reads — resolve (`Target::Module`/`Port`, container/member scopes), `is_unit`, the completion module table, `nearest_definition`/`module_header`, candidates, design hierarchy, call hierarchy, refactor `locate_module`/`module_definition`/`module_names` — each pinned in place; the sidebar's schema-2 wire shape is unchanged. Export: `Interface => Net | Var | Port | Param | Typedef | Function | Task | Modport | Clocking` (a module still exports ports and params only — round-2 ruling stands). Modport and clocking-block names are symbols; the names inside them are `Target::InScope` references (scope-local, nothing on a miss — a lexical walk would land a modport port on a file-scope lure); a clocking block carries `type_name` = its enclosing unit so `vif.cb.data` hops through round-2 machinery unchanged. The modport half of `bus_if.mp` in a type position is `Target::TypeMember { unit }`, resolved through `type_here`. `IndexCounts.interfaces` is separate so `modules` still means modules. Semantic-token legend deliberately not grown (indices are wire contract): Interface/Modport highlight as `class`, Clocking as `variable`. Rename truth flipped: a modport renames from its type-position use (`renaming_the_modport_half_of_a_port_type_renames_the_modport`). | | `struct-members ◀──▶ workspace-index / index-persistence / class-member-access / type-definition` | handshake | **`FACTS_FORMAT` 8 → 9** (2026-09-01): struct members exported (`is_exported(Typedef \| StructMember, StructMember)`), fields declared with `declare_typed` so `s.hdr.addr` hops through a member's own type, and `collect_members` recursing into package-nested struct typedefs (bare-name key, the nested-class convention — two packages with a same-named struct typedef collide by name and answer `Ambiguous`/nothing, never a guess) and into **inline nested fields under a synthesized key `owner.field` joined with `.`** carried as the field's `Def::type_name` — `.` not `::` because `member_type` runs `last_segment` on it and `::` would collapse to the bare field name; the key is unwritable as a type name and passes `units()`'s ambiguity guard for free. This is what makes opentitan's generated register packages resolve (`hw2reg.status.txfull.d` picks `txfull`'s `d`, not `rxfull`'s). `resolve::member_scope` accepts any symbol whose child scope is `ScopeKind::Struct` — typedef, anonymous declarator or inline field, one rule. `type_def.rs::alias_site` descends into `typedef struct` bodies. Corpus unresolved 1 203 → 1 162; store shrank 1.14 % (resolved anonymous-enum variants encode smaller than the external candidates they replaced). | | `constraint-bodies ◀──▶ class-semantics / class-member-access / index-persistence / semantic-lints` | handshake | **`FACTS_FORMAT` 10 → 11** (2026-09-02): `SymbolKind::Constraint` declared in the class scope (a stand-in `Class` scope for `constraint C::c`, the out-of-body-method mechanism reused); the body opens a scope under the class so every operand binds to the class's properties — rename from a `rand` field's declaration now rewrites its constraint uses, in-file and cross-file; `foreach` vars nest; `Target::InlineConstraint` resolves a `randomize() with { … }` operand against the randomized object's class first and the writing scope second. `Constraint` exported from `Class`. `signals.rs` reads constraint operands instead of routing the body to `opaque_spans` (a constraint reads, never drives). Corpus references +1 646, 84 % answered. Filed: a rename issued *from inside* an out-of-block constraint body whose class is elsewhere is refused by `vlog_refactor` (pre-existing — the same refusal `task C::m` bodies get). | +| `covergroup-bodies ◀──▶ class-semantics / class-member-access / index-persistence / semantic-lints` | handshake | **`FACTS_FORMAT` 11 → 12** (2026-09-02): `SymbolKind::{Covergroup, Coverpoint, Cross}` and `ScopeKind::Covergroup`; the covergroup opens a scope whose labelled coverpoints and crosses are symbols (an unlabelled coverpoint declares nothing), `sample()`/`(args)` parameters are visible in the body and nowhere else, every sampled expression, bin value and `iff` binds to the enclosing class's properties. `collect_members` recurses into a covergroup so `cg_inst.cp` resolves cross-file; `member_scope` accepts a `Covergroup` symbol. `signals.rs` reads coverpoint operands (a covergroup samples, never drives). Corpus references +1 139 with 1 135 answered. | | `define-table ◀──▶ macro-expansion` | handshake | What began as free-to-change became contract at M14: params stored **as written**, `NAME()` = `Some(vec![])` — `expand.rs` counts arguments against them and declines on mismatch. | ### 2.6 Refactor lane (the M-plan)