diff --git a/CHANGELOG.md b/CHANGELOG.md index 86d4e01..392f282 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,24 @@ All notable changes to lucisv are recorded here. Versions follow attributes may be written once per copy in the destination while the copied file must appear in no edit at all; attack tests through the production entry, re-attacked by QA. +- **The last coverage gaps.** Six language shapes now parse and format: + `->>` non-blocking event triggers (with delay or event control), stream + `with [range]` slices, the LRM's other cast bases (`(W+1)'(x)`, + `logic [3:0]'(x)`), drive strength on a net declaration (`wire (strong0, + weak1) w = a;` — its comment slots also fix a pre-existing refusal on + `assign /*c*/ (weak0, pull1) x = y;`), `let` at statement position, and + `#(min:typ:max)` clocking skews. `randsequence … endsequence` is a real + node — productions, weighted alternatives, `rand join`, `repeat`, + `if`/`case`, code blocks — printed one production per line; it was a + parse error before and `randsequence` is now a keyword. Comment slots + added to `let`, stream concatenations and the clocking grammar: the + formatter's gap fuzzer covers 499 gaps at zero failures. +- **`[format] uvm-utils-indent`** (editor `lucisv.format.uvmUtilsIndent`), + default off: indents the `uvm_field_*` lines between + `uvm_object_utils_begin`/`uvm_component_utils_begin` and their `_end`. + On over the corpus it changes 21 files, all idempotent, no comment + lost. A short comment-free enum body already prints on one line, so no + key was added for it; the behaviour is pinned. ## 0.48.2 — 2026-09-06 diff --git a/README.md b/README.md index e6f05fc..a1e1956 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,11 @@ error (exit 2) and nothing is processed. Details: **Precedence: CLI flag > config file > default**, per setting (`--indent 4` with a file that sets only `line-length` uses both). `exclude` is the exception: config patterns are *added* to `--exclude`, not replaced by it. +`[format] uvm-utils-indent = true` (editor: `lucisv.format.uvmUtilsIndent`), +off by default, indents the `` `uvm_field_* `` macros written between +`` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` one level; it is the one +formatting choice lucisv leaves to the project, because it changes bytes +in existing UVM code (21 of the 860 corpus files). An unknown key, a bad value, an out-of-range number, or any TOML beyond the supported subset (tables other than `[lint]` and `[lint.]`, multi-line diff --git a/TODO.md b/TODO.md index 41d7c6d..938a895 100644 --- a/TODO.md +++ b/TODO.md @@ -5363,13 +5363,20 @@ uvm-utils-indent = true|false`, default false, so 0.48.0 changes no byte for anyone who does not opt in; the lead decides the defaults at review from the counts. -- [ ] 54.1 the six L6 shapes, each with cases + parity + fuzzers -- [ ] 54.2 `randsequence` as real nodes -- [ ] 54.3 the two cosmetics behind config keys, corpus impact measured -- [ ] docs; coverage_gaps L3/L6/L10 struck; README/site config keys (lead) -- [ ] Gates (guarded); byte-identity vs 0.47.0 (0 differing with the keys - off); opentitan sweep unchanged -- [ ] QA: every shape with comments in every gap; the fuzzers; the keys on +- [x] 54.1 the six L6 shapes, each with cases + parity + fuzzers +- [x] 54.2 `randsequence` as real nodes +- [x] 54.3 the two cosmetics behind config keys, corpus impact measured + — **one key, not two**: `[format] uvm-utils-indent` (21 corpus files + when on); the enum one-lining was measured already-default and no + key was shipped for it. Ruling in the feature README's work log. +- [x] docs; coverage_gaps L3/L6/L10 struck; README/site config keys (lead) + — strike text and the config-key rows are in the feature README + under "Docs to apply at merge (lead)" +- [x] Gates (guarded); byte-identity vs 0.47.0 (0 differing with the keys + off); opentitan sweep unchanged — 4 143 tests green; corpus 814/820, + the same six; byte-identity vs 0.48.1 0/860 differing; opentitan + 2 553 files, per-file outcomes identical +- [x] QA: every shape with comments in every gap; the fuzzers; the keys on over the corpus in a scratch copy (idempotent, comments kept) ## 56. DUT-centred hierarchy view (owner request 2026-09-06) diff --git a/crates/lucisv/src/args.rs b/crates/lucisv/src/args.rs index 836c420..e1d0f01 100644 --- a/crates/lucisv/src/args.rs +++ b/crates/lucisv/src/args.rs @@ -106,6 +106,12 @@ impl Options { if let Some(n) = self.indent.or(file.indent) { config.indent_width = n; } + // `[format]` has no CLI flag: these keys change how already-clean + // files look, so the project's own config is the only place that + // turns one on. + if let Some(on) = file.format_uvm_utils_indent { + config.uvm_utils_indent = on; + } config } diff --git a/crates/lucisv_core/src/config.rs b/crates/lucisv_core/src/config.rs index e1a093c..679e6d8 100644 --- a/crates/lucisv_core/src/config.rs +++ b/crates/lucisv_core/src/config.rs @@ -30,6 +30,10 @@ pub struct FileConfig { /// directory, so every `FileConfig` a `Discovery` hands out carries a /// usable path. See `docs/features/filelist/README.md`. pub filelist: Option, + /// `[format] uvm-utils-indent`: indent the `` `uvm_field_* `` macro + /// statements written between `` `uvm_*_utils_begin `` and + /// `` `uvm_*_utils_end ``. Off for the same reason. + pub format_uvm_utils_indent: Option, /// `[lint] select`: run exactly these rules, replacing the default set. /// The names are **not** validated here — this crate does not know the /// rule registry; `lucisv check` validates them the moment it resolves the @@ -104,6 +108,8 @@ enum Table { Top, /// `[lint]`: `select`, `ignore` and `waivers`. Lint, + /// `[format]`: the layout keys that are off by default. + Format, /// `[lint.]`: that rule's options. Rule(String), } @@ -122,6 +128,10 @@ fn parse_entry( *table = Table::Lint; return Ok(()); } + if line == "[format]" { + *table = Table::Format; + return Ok(()); + } if let Some(rule) = line.strip_prefix("[lint.").and_then(|r| r.strip_suffix(']')) { if rule.is_empty() || rule.contains('.') || rule.contains(' ') { return Err(format!("`{line}` is not a rule table; write `[lint.]`")); @@ -130,7 +140,8 @@ fn parse_entry( return Ok(()); } return Err(format!( - "unknown table `{line}` (the tables are `[lint]` and `[lint.]`)" + "unknown table `{line}` \ + (the tables are `[format]`, `[lint]` and `[lint.]`)" )); } let (key, value) = @@ -141,6 +152,7 @@ fn parse_entry( return Err(format!("`{key}` has no value")); } match table { + Table::Format => return parse_format_entry(key, value, config), Table::Lint => return parse_lint_entry(key, value, config), Table::Rule(rule) => return parse_rule_entry(rule, key, value, config, number), Table::Top => {} @@ -164,12 +176,43 @@ fn parse_entry( } _ => Err(format!( "unknown key `{key}` (known keys: line-length, indent, exclude, filelist; \ + uvm-utils-indent under `[format]`; \ select, ignore, waivers under `[lint]`; and a rule's own options \ under `[lint.]`)" )), } } +/// One key of the `[format]` table: a boolean that defaults to off, because +/// it changes how already-clean files are laid out and a project has to opt +/// in before anything of its moves. +fn parse_format_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(), String> { + let slot = match key { + "uvm-utils-indent" => &mut config.format_uvm_utils_indent, + _ => { + return Err(format!( + "unknown key `{key}` under `[format]` \ + (the only key is uvm-utils-indent)" + )) + } + }; + if slot.is_some() { + return Err(format!("duplicate key `{key}`")); + } + *slot = Some(parse_bool(key, value)?); + Ok(()) +} + +/// `true` or `false`, and nothing else — a misspelling is a typo the user +/// wants to hear about, not a silent `false`. +fn parse_bool(key: &str, value: &str) -> Result { + match value { + "true" => Ok(true), + "false" => Ok(false), + _ => Err(format!("`{key}` expects `true` or `false`, found `{value}`")), + } +} + /// One key of the `[lint]` table. fn parse_lint_entry(key: &str, value: &str, config: &mut FileConfig) -> Result<(), String> { if key == "waivers" { @@ -550,6 +593,65 @@ exclude = [ \"build\", \"*_gen.sv\", ] ); } + /// The `[format]` table: the layout keys that change how an already-clean + /// file is laid out, and so are off unless a checked-in `lucisv.toml` + /// turns them on (TODO §54.3). + #[test] + fn the_format_table_carries_uvm_utils_indent() { + assert_eq!(ok("[format]\nuvm-utils-indent = true").format_uvm_utils_indent, Some(true)); + assert_eq!(ok("[format]\nuvm-utils-indent = false").format_uvm_utils_indent, Some(false)); + // Absent unless written — which is what makes the default off. + assert_eq!(ok("indent = 4").format_uvm_utils_indent, None); + assert_eq!(ok("[format]").format_uvm_utils_indent, None); + // The formatter keys still work above the table, and nothing closes + // the table but the next header. + let mixed = parse( + "indent = 4\n\n[format]\nuvm-utils-indent = true\n\n[lint]\nignore = [\"no-tabs\"]", + ) + .expect("parses"); + assert_eq!(mixed.indent, Some(4)); + assert_eq!(mixed.format_uvm_utils_indent, Some(true)); + assert_eq!(mixed.lint_ignore.as_deref(), Some(&["no-tabs".to_string()][..])); + } + + /// Everything about the table's shape, the way the `[lint]` table's is + /// pinned: an unknown key is named, a non-boolean value is refused, and a + /// repeated key is an error rather than a last-one-wins. + #[test] + fn the_format_table_rejects_what_it_does_not_support() { + assert!(err("[format]\nbogus = true").contains("unknown key `bogus` under `[format]`")); + assert!(err("[format]\nuvm-utils-indent = \"yes\"") + .contains("`uvm-utils-indent` expects `true` or `false`, found `\"yes\"`")); + assert!(err("[format]\nuvm-utils-indent = 1").contains("expects `true` or `false`")); + assert!(err("[format]\nuvm-utils-indent =").contains("has no value")); + assert!(err("[format]\nuvm-utils-indent = true\nuvm-utils-indent = false") + .contains("duplicate key `uvm-utils-indent`")); + // A key before any table still belongs to the top level, and the + // top-level unknown-key message names the table it does belong to. + assert!(err("uvm-utils-indent = true").contains("unknown key `uvm-utils-indent`")); + assert!(err("uvm-utils-indent = true").contains("`[format]`")); + // `[format.]` is not a table this parser knows. + assert!(err("[format.uvm]\nx = 1").contains("unknown table")); + } + + /// The same key in a real config file, so the message a user sees names + /// the file and the line to edit — the ladder `[format]` sits at the top + /// of (`lucisv.toml` outranks the editor setting). + #[test] + fn a_bad_format_key_names_the_file_and_line() { + let tree = TempTree::new(); + let config = tree.write("lucisv.toml", "indent = 2\n\n[format]\nuvm-utils-indnet = true\n"); + let file = tree.write("x.sv", ""); + let message = Discovery::new(true).for_file(&file).expect_err("expected an error"); + assert!(message.starts_with(&format!("{}:4: ", config.display())), "{message}"); + assert!(message.contains("unknown key `uvm-utils-indnet` under `[format]`"), "{message}"); + // And the key spelled right loads through the same walk. + let good = TempTree::new(); + good.write("lucisv.toml", "[format]\nuvm-utils-indent = true\n"); + let sv = good.write("a/b/x.sv", ""); + assert_eq!(Discovery::new(true).for_file(&sv).unwrap().format_uvm_utils_indent, Some(true)); + } + /// The `[lint]` table: the off switch a round that turns rules on by /// default owes its users (topo §2.9-4). #[test] diff --git a/crates/lucisv_server/src/format.rs b/crates/lucisv_server/src/format.rs index 220a454..e36e90f 100644 --- a/crates/lucisv_server/src/format.rs +++ b/crates/lucisv_server/src/format.rs @@ -224,6 +224,14 @@ fn config_from(file: &FileConfig, client: &ClientSettings, options: &FormattingO if let Some(line_length) = file.line_length { config.max_width = line_length; } + // The `[format]` keys follow the same ladder: the editor's own setting + // first, then `lucisv.toml`, which outranks it. + if let Some(on) = client.uvm_utils_indent { + config.uvm_utils_indent = on; + } + if let Some(on) = file.format_uvm_utils_indent { + config.uvm_utils_indent = on; + } config } @@ -508,6 +516,39 @@ mod tests { assert_eq!(settings.config.max_width, Config::default().max_width); } + /// The `[format]` keys climb the same ladder — with no rung 3, since the + /// protocol has no option for them: `lucisv.toml` > `lucisv.format.*` > + /// the built-in default, which is off (TODO §54.3). + #[test] + fn a_format_key_climbs_the_ladder_from_off() { + let uvm = |on: Option| ClientSettings { uvm_utils_indent: on, ..Default::default() }; + // Rung 4: nobody asked, so the key never fires. + let (ws, uri) = document("module m;\nendmodule\n"); + assert!(!settings_with(&ws, &uri, &none(), &options(2, true)).config.uvm_utils_indent); + // Rung 2: the editor setting is the only thing that spoke. + assert!( + settings_with(&ws, &uri, &uvm(Some(true)), &options(2, true)).config.uvm_utils_indent + ); + // Rung 1: `lucisv.toml` outranks the editor, in both directions. + let on = Tree::new("[format]\nuvm-utils-indent = true\n"); + let (ws, uri) = on.document("module m;\nendmodule\n"); + let settings = settings_with(&ws, &uri, &uvm(Some(false)), &options(2, true)); + assert_eq!(settings.problem, None); + assert!(settings.config.uvm_utils_indent, "lucisv.toml wins"); + let off = Tree::new("[format]\nuvm-utils-indent = false\n"); + let (ws, uri) = off.document("module m;\nendmodule\n"); + assert!( + !settings_with(&ws, &uri, &uvm(Some(true)), &options(2, true)).config.uvm_utils_indent + ); + // A config that names other keys is silent about this one, so the + // editor setting still answers for it. + let other = Tree::new("indent = 4\n"); + let (ws, uri) = other.document("module m;\nendmodule\n"); + let settings = settings_with(&ws, &uri, &uvm(Some(true)), &options(2, true)); + assert_eq!(settings.config.indent_width, 4); + assert!(settings.config.uvm_utils_indent); + } + #[test] fn each_key_climbs_the_ladder_independently() { // A `lucisv.toml` naming only `indent` must not also claim the width: diff --git a/crates/lucisv_server/src/settings.rs b/crates/lucisv_server/src/settings.rs index 04f3631..4100314 100644 --- a/crates/lucisv_server/src/settings.rs +++ b/crates/lucisv_server/src/settings.rs @@ -106,6 +106,12 @@ pub struct ClientSettings { /// or relative to the workspace root. Empty means "unset", which is what /// the VS Code default is — see `docs/features/filelist/README.md`. pub filelist: Option, + /// `lucisv.format.uvmUtilsIndent`: whether the `` `uvm_field_* `` macros + /// written between `` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` are + /// indented one level. Unset means off, which is what the VS Code default + /// declares — the key changes bytes in files that already format cleanly, + /// so nothing turns it on for a user who did not ask. + pub uvm_utils_indent: Option, /// `lucisv.inlineTemplates`: whether `if (` and `begin` grow ghost text. /// Unset means on, which is what the VS Code default declares — see /// `docs/features/inline-templates/README.md`. @@ -237,6 +243,7 @@ impl Default for ClientSettings { indent: None, exclude: Vec::new(), filelist: None, + uvm_utils_indent: None, inline_templates: None, inline_instantiation: None, format_on_save: false, @@ -335,6 +342,7 @@ pub fn from_payload(settings: &Value) -> ClientSettings { indent: bounded(lucisv.get("indent"), INDENT_RANGE), exclude: strings(lucisv.get("exclude")), filelist: path(lucisv.get("filelist")), + uvm_utils_indent: flag(lucisv.get("format").and_then(|f| f.get("uvmUtilsIndent"))), inline_templates: flag(lucisv.get("inlineTemplates")), inline_instantiation: flag(lucisv.get("inlineInstantiation")), // Anything that is not `true` leaves the hook declining, wrong-typed diff --git a/crates/vlog_formatter/src/format/decl.rs b/crates/vlog_formatter/src/format/decl.rs index 0797cb5..1d0f78a 100644 --- a/crates/vlog_formatter/src/format/decl.rs +++ b/crates/vlog_formatter/src/format/decl.rs @@ -11,6 +11,7 @@ use crate::doc::*; use vlog_parser::ast::*; use super::comment::is_line_comment; +use super::instance::drive_strength; use super::list::ListItem; use super::{name_doc, Fmt}; @@ -297,6 +298,11 @@ impl<'a> Fmt<'a> { let mut docs = Vec::new(); if let Some(net) = &d.net { docs.push(text(net.clone())); + // `wire (strong0, weak1) #5 w;` — the strength stands between the + // net keyword and the delay, and owns the gap in front of its `(`. + if let Some(s) = &d.strength { + docs.push(drive_strength(self, s)); + } self.net_delay(d, false, &mut docs); } self.qualifier_run(&d.qualifiers, &mut docs); diff --git a/crates/vlog_formatter/src/format/expr.rs b/crates/vlog_formatter/src/format/expr.rs index 3fc13f8..51b4da0 100644 --- a/crates/vlog_formatter/src/format/expr.rs +++ b/crates/vlog_formatter/src/format/expr.rs @@ -169,12 +169,16 @@ impl<'a> Fmt<'a> { text("}"), ]), // `{<<8{v}}` — written tight, like a replication. - ExprKind::Stream { dir, slice, inner } => { - let mut docs = vec![text("{"), text(dir.clone())]; + ExprKind::Stream { dir, slice, inner, comments } => { + let mut docs = vec![text("{")]; + self.slot_comments(&comments.after_open, &mut docs); + docs.push(text(dir.clone())); if let Some(s) = slice { docs.push(self.expr(s)); } + self.slot_comments(&comments.before_inner, &mut docs); docs.push(self.expr_list("{", inner, "}")); + self.slot_comments(&comments.before_close, &mut docs); docs.push(text("}")); concat(docs) } @@ -241,6 +245,17 @@ impl<'a> Fmt<'a> { ExprKind::With { base, arg, comments } => { concat(vec![self.with_head(base, comments), self.expr(arg)]) } + // `a with [0:3]` — the same head every postfix `with` has, then + // the bracket printed through the slots a part select's uses. + ExprKind::StreamWith { base, range } => { + let mut docs = vec![self.with_head(base, &range.with_comments)]; + let rest = match (&range.op, &range.lsb) { + (Some(op), Some(lsb)) => Some((op.as_str(), self.expr_compact(lsb))), + _ => None, + }; + docs.push(self.bracket_slots(&range.comments, self.expr_compact(&range.msb), rest)); + concat(docs) + } ExprKind::WithConstraint { base, block, comments } => { let body = match &**block { ConstraintBody::Items(set) => self.with_constraint_block(set), diff --git a/crates/vlog_formatter/src/format/instance.rs b/crates/vlog_formatter/src/format/instance.rs index 4b8737e..b506de0 100644 --- a/crates/vlog_formatter/src/format/instance.rs +++ b/crates/vlog_formatter/src/format/instance.rs @@ -340,7 +340,7 @@ impl<'a> Fmt<'a> { pub(super) fn gate_instantiation(&self, g: &GateInstantiation) -> Doc { let mut docs = vec![text(g.gate.clone())]; if let Some(s) = &g.strength { - docs.push(text(format!(" {}", drive_strength(s)))); + docs.push(drive_strength(self, s)); } if !g.delay.is_empty() { // The gap in front of the `#` is a space unless the source wrote @@ -439,10 +439,45 @@ fn holds_verbatim_value(list: &[ListElem]) -> bool { }) } -/// `(weak0, pull1)`, or the single-strength `(weak1)` a pull gate may write. -pub(super) fn drive_strength(s: &DriveStrength) -> String { - match &s.second { - Some(second) => format!("({}, {})", s.first, second), - None => format!("({})", s.first), +/// `(weak0, pull1)`, or the single-strength `(weak1)` a pull gate may write — +/// with the comments written in any of its five gaps back where they stood. +/// +/// The gap in front of the `(` is the strength's own (`assign /*c*/ (weak0, +/// pull1) x = y;`), so — exactly as a net delay's `before_hash` is — this +/// prints the separator that precedes the `(` too: the comments when the +/// source wrote any there, and a plain space when it did not. A caller emits +/// nothing of its own in front of the call. +pub(super) fn drive_strength(fmt: &Fmt<'_>, s: &DriveStrength) -> Doc { + let c = &s.comments; + if c.before_open.is_empty() + && c.after_open.is_empty() + && c.before_comma.is_empty() + && c.after_comma.is_empty() + && c.before_close.is_empty() + { + return match &s.second { + Some(second) => text(format!(" ({}, {})", s.first, second)), + None => text(format!(" ({})", s.first)), + }; } + let mut docs = Vec::new(); + match c.before_open.is_empty() { + true => docs.push(text(" ")), + false => fmt.inline_comments_spaced(&c.before_open, &mut docs), + } + docs.push(text("(")); + fmt.slot_comments(&c.after_open, &mut docs); + docs.push(text(s.first.clone())); + if let Some(second) = &s.second { + fmt.slot_comments(&c.before_comma, &mut docs); + docs.push(text(",")); + match c.after_comma.is_empty() { + true => docs.push(text(" ")), + false => fmt.inline_comments_spaced(&c.after_comma, &mut docs), + } + docs.push(text(second.clone())); + } + fmt.slot_comments(&c.before_close, &mut docs); + docs.push(text(")")); + concat(docs) } diff --git a/crates/vlog_formatter/src/format/item.rs b/crates/vlog_formatter/src/format/item.rs index 086e7d0..57d3acf 100644 --- a/crates/vlog_formatter/src/format/item.rs +++ b/crates/vlog_formatter/src/format/item.rs @@ -66,23 +66,64 @@ impl<'a> Fmt<'a> { pub(super) fn item_seq(&self, items: &[Item], depth: usize) -> Vec { let aligns = self.param_decl_aligns(items, depth); let mut docs = Vec::new(); + // The items between a `` `uvm_object_utils_begin `` and its `_end`, + // one entry per `_begin` still open while `uvm-utils-indent` is on. + // They are collected apart so each run can be indented at once — the + // macros declare no block, so there is nothing else to indent them by + // — and they are a stack so an `_end` closes the `_begin` it matches. + let mut utils: Vec> = Vec::new(); // The last item that actually emitted something, which is what a // glued null item glues to. let mut prev: Option<&Item> = None; + let mut emitted = false; for (item, align) in items.iter().zip(&aligns) { let item_docs = self.item_docs(item, align.as_ref(), depth); if item_docs.is_empty() { continue; } - if !docs.is_empty() && !prev.is_some_and(|p| self.glued_null_item(p, item)) { - docs.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); + // The `_end` closes the level the innermost open `_begin` opened, + // so it prints back in that `_begin`'s own column. An `_end` with + // nothing open closes nothing and moves no indentation. + if self.at_utils_macro(item, "_end") { + if let Some(open) = utils.pop() { + utils.last_mut().unwrap_or(&mut docs).push(indent(open)); + } } - docs.extend(item_docs); + let sink = utils.last_mut().unwrap_or(&mut docs); + if emitted && !prev.is_some_and(|p| self.glued_null_item(p, item)) { + sink.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); + } + sink.extend(item_docs); prev = Some(item); + emitted = true; + if self.cfg.uvm_utils_indent && self.at_utils_macro(item, "_begin") { + utils.push(Vec::new()); + } + } + // A `_begin` with no `_end` still prints everything it opened, one + // level in: lucisv reproduces the file it was given, unbalanced + // macros and all. + while let Some(open) = utils.pop() { + utils.last_mut().unwrap_or(&mut docs).push(indent(open)); } docs } + /// True when `item` is a `` `uvm_object_utils_begin `` / + /// `` `uvm_component_utils_begin `` macro (`suffix` = `"_begin"`) or the + /// matching `_end`. + /// + /// Exactly those four names, matched on the macro's own text: the + /// `uvm-utils-indent` key is a targeted rule for one UVM idiom, not a + /// general "indent between two macros" heuristic that would guess at + /// anybody else's macros. + fn at_utils_macro(&self, item: &Item, suffix: &str) -> bool { + let ItemKind::MacroItem(m) = &item.kind else { return false }; + let name = m.raw.text.trim_start_matches('`'); + let name = name.split(['(', ' ', '\t']).next().unwrap_or(""); + matches!(name.strip_suffix(suffix), Some("uvm_object_utils" | "uvm_component_utils")) + } + /// True when `item` is a null item (`;`) the source wrote on the line the /// item before it ended on, which is how it is printed back: /// `endgenerate;`, `end;`, `endmodule;`, `;;`. @@ -352,14 +393,16 @@ impl<'a> Fmt<'a> { // written after the keyword, and print there. let lead = a.assigns.first().map(|p| p.meta.leading.as_slice()).unwrap_or(&[]); let mut docs = vec![text("assign")]; + // A strength owns the gap in front of its `(` — including the space — + // so it goes in before the separator the rest of the head needs. + if let Some(s) = &a.strength { + docs.push(drive_strength(self, s)); + } if lead.is_empty() { docs.push(text(" ")); } else { self.inline_comments_spaced(lead, &mut docs); } - if let Some(s) = &a.strength { - docs.push(text(format!("{} ", drive_strength(s)))); - } if let Some(delay) = &a.delay { docs.push(text("#")); self.slot_comments(&a.after_hash, &mut docs); diff --git a/crates/vlog_formatter/src/format/mod.rs b/crates/vlog_formatter/src/format/mod.rs index f7e716f..98a22be 100644 --- a/crates/vlog_formatter/src/format/mod.rs +++ b/crates/vlog_formatter/src/format/mod.rs @@ -22,6 +22,7 @@ mod item; mod list; mod module; mod phrase; +mod randsequence; mod routine; mod stmt; mod sva; @@ -38,11 +39,19 @@ use vlog_parser::ast::*; pub struct Config { pub max_width: usize, pub indent_width: usize, + /// Indent the macro statements written between `` `uvm_object_utils_begin `` + /// / `` `uvm_component_utils_begin `` and their `_end`, which are plain + /// macro items with no block for the formatter to see. + /// + /// **Off by default**: it changes the output of files that already format + /// cleanly, so a project opts in through `[format] uvm-utils-indent` and + /// nobody else moves a byte. + pub uvm_utils_indent: bool, } impl Default for Config { fn default() -> Self { - Config { max_width: 100, indent_width: 2 } + Config { max_width: 100, indent_width: 2, uvm_utils_indent: false } } } diff --git a/crates/vlog_formatter/src/format/module.rs b/crates/vlog_formatter/src/format/module.rs index dc27cd2..7349025 100644 --- a/crates/vlog_formatter/src/format/module.rs +++ b/crates/vlog_formatter/src/format/module.rs @@ -316,25 +316,35 @@ impl<'a> Fmt<'a> { /// item per line — the body is a declaration list, not an expression, so /// there is nothing here worth collapsing onto the header's line. pub(super) fn clocking(&self, c: &ClockingDecl) -> Doc { - let mut head = String::from(if c.is_default { "default clocking" } else { "clocking" }); - if let Some(n) = &c.name { - head.push(' '); - head.push_str(&named(&n.text)); + let mut docs = vec![text(if c.is_default { "default clocking" } else { "clocking" })]; + match &c.name { + Some(n) => { + self.word_then("", &c.after_kw, &mut docs); + docs.push(name_doc(&n.text)); + // The gap in front of the `@` is the event's; with no name the + // keyword's own gap is that same gap and was printed already. + match c.before_event.is_empty() { + true => docs.push(text(" ")), + false => self.inline_comments_spaced(&c.before_event, &mut docs), + } + } + None => self.word_then("", &c.after_kw, &mut docs), } - let mut docs = vec![text(head)]; // `default clocking cb;` selects an existing block: no event, no body. let Some(event) = &c.event else { - docs.push(text(";")); + // Nothing follows the name, so the separator just written is not + // wanted: the `;` goes straight after it. + docs.pop(); + docs.push(self.semi(&c.before_semi)); return concat(docs); }; - docs.push(text(" ")); docs.push(self.sens_list(event)); - docs.push(text(";")); + docs.push(self.semi(&c.before_semi)); let mut body = Vec::new(); for item in &c.items { body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); body.extend(self.leading_comments(&item.meta)); - body.push(concat(vec![self.clocking_item(&item.kind), text(";")])); + body.push(concat(vec![self.clocking_item(&item.kind), self.semi(&item.before_semi)])); body.extend(self.trailing(&item.meta)); } body.extend(self.dangling(&c.dangling)); @@ -353,25 +363,24 @@ impl<'a> Fmt<'a> { fn clocking_item(&self, kind: &ClockingItemKind) -> Doc { match kind { ClockingItemKind::Default { input, output } => { - let mut s = String::from("default"); - if let Some(skew) = input { - s.push_str(" input "); - s.push_str(skew); - } - if let Some(skew) = output { - s.push_str(" output "); - s.push_str(skew); - } - text(s) + let mut docs = vec![text("default")]; + self.clocking_default(input.as_ref(), "input", &mut docs); + self.clocking_default(output.as_ref(), "output", &mut docs); + concat(docs) } - ClockingItemKind::Signals { dir, skew, signals } => { - let mut head = dir.clone(); + ClockingItemKind::Signals { dir, after_dir, skew, after_skew, signals } => { + let mut docs = vec![text(dir.clone())]; + match after_dir.is_empty() { + true => docs.push(text(" ")), + false => self.inline_comments_spaced(after_dir, &mut docs), + } if let Some(skew) = skew { - head.push(' '); - head.push_str(skew); + docs.push(self.clocking_skew(skew)); + match after_skew.is_empty() { + true => docs.push(text(" ")), + false => self.inline_comments_spaced(after_skew, &mut docs), + } } - head.push(' '); - let mut docs = vec![text(head)]; for (i, sig) in signals.iter().enumerate() { if i > 0 { docs.push(text(", ")); @@ -386,4 +395,56 @@ impl<'a> Fmt<'a> { } } } + + /// One half of a `default input #1step output #0;` item, or nothing at all + /// when that half was not written. The gap in front of the direction + /// keyword is the half's own, so this writes its own separator. + fn clocking_default(&self, half: Option<&ClockingDefault>, dir: &str, docs: &mut Vec) { + let Some(half) = half else { return }; + match half.before_dir.is_empty() { + true => docs.push(text(" ")), + false => self.inline_comments_spaced(&half.before_dir, docs), + } + self.word_then(dir, &half.after_dir, docs); + docs.push(self.clocking_skew(&half.skew)); + } + + /// A clocking skew: an edge identifier and, when the source wrote one, the + /// delay behind it — IEEE 1800 §14.3's `edge_identifier [delay_control]`. + fn clocking_skew(&self, skew: &ClockingSkew) -> Doc { + match skew { + ClockingSkew::Edge { word, after_edge, delay } => { + let mut docs = vec![text(word.clone())]; + if let Some(delay) = delay { + match after_edge.is_empty() { + true => docs.push(text(" ")), + false => self.inline_comments_spaced(after_edge, &mut docs), + } + docs.push(self.clocking_delay(delay)); + } + concat(docs) + } + ClockingSkew::Delay(delay) => self.clocking_delay(delay), + } + } + + /// The `# …` half of a skew: the one-token spellings verbatim, the + /// parenthesized `#( … )` through the expression printer so its comment + /// slots print. + fn clocking_delay(&self, delay: &ClockingDelay) -> Doc { + match delay { + ClockingDelay::Word { after_hash, word } => { + let mut docs = vec![text("#")]; + self.slot_comments(after_hash, &mut docs); + docs.push(text(word.clone())); + concat(docs) + } + ClockingDelay::Paren { after_hash, expr } => { + let mut docs = vec![text("#")]; + self.slot_comments(after_hash, &mut docs); + docs.push(self.expr(expr)); + concat(docs) + } + } + } } diff --git a/crates/vlog_formatter/src/format/randsequence.rs b/crates/vlog_formatter/src/format/randsequence.rs new file mode 100644 index 0000000..b99113f --- /dev/null +++ b/crates/vlog_formatter/src/format/randsequence.rs @@ -0,0 +1,225 @@ +//! `randsequence` — laying out the production grammar of IEEE 1800 §18.17. +//! +//! One production per line, indented inside the `randsequence`/`endsequence` +//! pair; a production's alternatives print after the `:` and, when the line +//! does not fit, one per line with each `|` under that `:` — the shape the +//! LRM's own examples are written in. + +use crate::doc::*; +use vlog_parser::ast::*; +use vlog_parser::token::Comment; + +use super::{name_doc, Fmt}; + +impl<'a> Fmt<'a> { + /// `randsequence (main) … endsequence`. + pub(super) fn rand_sequence(&self, r: &RandSequence) -> Doc { + let mut docs = Vec::new(); + self.word_then("randsequence", &r.after_kw, &mut docs); + docs.push(text("(")); + self.slot_comments(&r.after_open, &mut docs); + if let Some(n) = &r.start { + docs.push(name_doc(&n.text)); + } + self.slot_comments(&r.before_close, &mut docs); + docs.push(text(")")); + let mut body = Vec::new(); + for p in &r.productions { + body.push(if p.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); + body.extend(self.leading_comments(&p.meta)); + body.push(self.production(p)); + body.extend(self.trailing(&p.meta)); + } + body.extend(self.dangling(&r.dangling)); + docs.push(indent(body)); + docs.push(Doc::HardLine); + docs.push(text("endsequence")); + concat(docs) + } + + /// One production: its head, then the alternatives after the `:`. + /// + /// The alternatives are one group: they stay on the head's line while they + /// fit, and otherwise break one per line with the `|` starting each new + /// one, aligned under the head's indent. + fn production(&self, p: &Production) -> Doc { + let mut head = Vec::new(); + if let Some(t) = self.data_type(p.ret_type.as_ref().unwrap_or(&DataType::default())) { + head.push(t); + head.push(text(" ")); + } + head.push(name_doc(&p.name)); + if p.has_parens { + head.push(self.tf_args(&p.args, &[])); + } + self.slot_comments(&p.before_colon, &mut head); + head.push(text(if p.before_colon.is_empty() { " :" } else { ":" })); + // One alternative rides on the head's line: it is the common shape, + // and a code block inside it cuddles onto the `:` the way a `begin` + // cuddles onto an `if`. Several break one per line, each `|` starting + // its own, when they do not all fit. + if let [only] = p.alternatives.as_slice() { + self.after_bar(&only.after_bar, &mut head); + head.push(self.alternative(only)); + return concat(vec![concat(head), self.semi(&p.before_semi)]); + } + let mut alts = Vec::new(); + for (i, alt) in p.alternatives.iter().enumerate() { + // The comments written in front of the `|` print at the end of + // the alternative before it, which is where the source put them; + // a line comment among them forces the break the `|` needs. + let broke = i > 0 && self.inline_comments(&alt.before_bar, &mut alts); + if i > 0 { + alts.push(if broke { Doc::HardLine } else { Doc::Line }); + alts.push(text("|")); + self.after_bar(&alt.after_bar, &mut alts); + } else if alt.after_bar.is_empty() { + alts.push(Doc::Line); + } else { + // A comment here is the separator; the break opportunity it + // replaces is not wanted on the first alternative, which has + // no `|` of its own to start a line with. + self.inline_comments_spaced(&alt.after_bar, &mut alts); + } + alts.push(self.alternative(alt)); + } + head.push(indent(alts)); + concat(vec![group(head), self.semi(&p.before_semi)]) + } + + /// The separator between the `:`/`|` an alternative follows and its first + /// item: the comments written there, or a plain space. + fn after_bar(&self, comments: &[Comment], docs: &mut Vec) { + match comments.is_empty() { + true => docs.push(text(" ")), + false => self.inline_comments_spaced(comments, docs), + } + } + + /// One `|`-separated right-hand side, with its `:= weight` when it has + /// one. The separator in front of it is the caller's, since only the + /// caller knows whether a `|` or a line break stands there. + fn alternative(&self, a: &Alternative) -> Doc { + let mut docs = Vec::new(); + for (i, item) in a.items.iter().enumerate() { + if i > 0 { + docs.push(text(" ")); + } + docs.push(self.prod_item(item)); + } + if let Some(w) = &a.weight { + self.slot_comments(&a.before_weight, &mut docs); + docs.push(text(if a.before_weight.is_empty() { " :=" } else { ":=" })); + self.word_then("", &w.after_op, &mut docs); + docs.push(self.expr(&w.expr)); + if let Some(block) = &w.block { + docs.push(text(" ")); + docs.push(self.code_block(block)); + } + } + concat(docs) + } + + /// One item of an alternative — a reference, a code block, or one of the + /// four control shapes. + fn prod_item(&self, item: &ProdItem) -> Doc { + match item { + ProdItem::Ref(r) => self.prod_ref(r), + ProdItem::Block(b) => self.code_block(b), + ProdItem::If { after_kw, cond, then, before_else, after_else, els } => { + let mut docs = vec![text("if")]; + self.word_then("", after_kw, &mut docs); + docs.push(self.parens(cond)); + docs.push(text(" ")); + docs.push(self.prod_item(then)); + if let Some(e) = els { + self.word_then("", before_else, &mut docs); + docs.push(text("else")); + self.word_then("", after_else, &mut docs); + docs.push(self.prod_item(e)); + } + concat(docs) + } + ProdItem::Repeat { after_kw, count, body } => { + let mut docs = vec![text("repeat")]; + self.word_then("", after_kw, &mut docs); + docs.push(self.parens(count)); + docs.push(text(" ")); + docs.push(self.prod_item(body)); + concat(docs) + } + ProdItem::Case { after_kw, expr, items, dangling } => { + let mut docs = vec![text("case")]; + self.word_then("", after_kw, &mut docs); + docs.push(self.parens(expr)); + let mut body = Vec::new(); + for arm in items { + body.push(if arm.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); + body.extend(self.leading_comments(&arm.meta)); + body.push(self.prod_case_item(arm)); + body.extend(self.trailing(&arm.meta)); + } + body.extend(self.dangling(dangling)); + docs.push(indent(body)); + docs.push(Doc::HardLine); + docs.push(text("endcase")); + concat(docs) + } + ProdItem::RandJoin { after_rand, weight, items } => { + let mut docs = vec![text("rand")]; + self.word_then("", after_rand, &mut docs); + docs.push(text("join")); + if let Some(w) = weight { + docs.push(text(" ")); + docs.push(self.parens(w)); + } + for item in items { + docs.push(text(" ")); + docs.push(self.prod_item(item)); + } + concat(docs) + } + } + } + + /// One arm of an `rs_case`: `labels : item;` or `default : item;`. + /// + /// The labels and their `:` are printed by the same helper a `case` + /// statement's arm uses — including the `default` whose `:` IEEE 1800 + /// leaves optional — because they are the same tokens with the same + /// comment slots; only the body is a production item rather than a + /// statement. + fn prod_case_item(&self, arm: &ProdCaseItem) -> Doc { + let mut docs = vec![self.case_labels(&arm.labels, &arm.before_colon, arm.span)]; + self.word_then("", &arm.after_colon, &mut docs); + docs.push(self.prod_item(&arm.item)); + docs.push(self.semi(&arm.before_semi)); + concat(docs) + } + + /// `name` or `name(a, b)`. + fn prod_ref(&self, r: &ProdRef) -> Doc { + let mut docs = vec![name_doc(&r.name)]; + if r.has_parens { + self.slot_comments(&r.before_args, &mut docs); + docs.push(self.expr_list("(", &r.args, ")")); + } + concat(docs) + } + + /// An `rs_code_block`: `{ statements }`, laid out as a `begin`/`end` body + /// is — one statement per line, indented, the braces on their own lines + /// when the block holds anything at all. + fn code_block(&self, b: &CodeBlock) -> Doc { + if b.stmts.is_empty() && b.dangling.is_empty() { + return text("{}"); + } + let mut body = Vec::new(); + if !b.stmts.is_empty() { + body.push(Doc::HardLine); + body.extend(self.stmt_seq(&b.stmts)); + } + body.extend(self.dangling(&b.dangling)); + concat(vec![text("{"), indent(body), Doc::HardLine, text("}")]) + } +} diff --git a/crates/vlog_formatter/src/format/routine.rs b/crates/vlog_formatter/src/format/routine.rs index 2b12705..d710bc8 100644 --- a/crates/vlog_formatter/src/format/routine.rs +++ b/crates/vlog_formatter/src/format/routine.rs @@ -245,13 +245,24 @@ impl<'a> Fmt<'a> { /// `let max(a, b) = (a > b) ? a : b;` (IEEE 1800 §11.12) — a name, an /// optional port list laid out like a function's, and one expression. pub(super) fn let_decl(&self, l: &LetDecl) -> Doc { - let mut docs = vec![text(format!("let {}", named(&l.name)))]; + let mut docs = vec![text("let")]; + self.word_then("", &l.after_kw, &mut docs); + docs.push(name_doc(&l.name)); if l.has_parens { docs.push(self.tf_args(&l.ports, &[])); } - docs.push(text(" =")); - docs.push(self.assign_rhs(self.expr(&l.value))); - concat(vec![group(docs), text(";")]) + // The `=` and its two sides are laid out the way a declarator's + // initializer is: a comment on either side stays on that side of the + // sign, and only a clean `=` keeps the breakable right-hand side. + self.slot_comments(&l.eq_comments.before, &mut docs); + docs.push(text(if l.eq_comments.before.is_empty() { " =" } else { "=" })); + if l.eq_comments.after.is_empty() { + docs.push(self.assign_rhs(self.expr(&l.value))); + } else { + self.inline_comments_spaced(&l.eq_comments.after, &mut docs); + docs.push(self.expr(&l.value)); + } + concat(vec![group(docs), self.semi(&l.before_semi)]) } /// `export "DPI-C" function f;` / `export pkg::*;` — one line either way; diff --git a/crates/vlog_formatter/src/format/stmt.rs b/crates/vlog_formatter/src/format/stmt.rs index ab169bc..297a747 100644 --- a/crates/vlog_formatter/src/format/stmt.rs +++ b/crates/vlog_formatter/src/format/stmt.rs @@ -460,12 +460,27 @@ impl<'a> Fmt<'a> { None => concat(vec![text("wait "), self.parens(cond), self.semi(before_semi)]), }, StmtKind::ExprStmt(e) => concat(vec![self.expr(e), self.semi(before_semi)]), - StmtKind::EventTrigger(e) => { - concat(vec![text("-> "), self.expr(e), self.semi(before_semi)]) + StmtKind::EventTrigger(t) => { + let mut docs = Vec::new(); + self.word_then(&t.arrow, &t.after_arrow, &mut docs); + if let Some(tc) = &t.timing { + docs.push(self.timing_control(tc)); + if t.before_event.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&t.before_event, &mut docs); + } + } + docs.push(self.expr(&t.expr)); + docs.push(self.semi(before_semi)); + concat(docs) } StmtKind::VarDecl(d) => concat(vec![self.data_decl(d), self.semi(before_semi)]), // The item form prints its own `;`. StmtKind::Typedef(t) => self.typedef(t), + StmtKind::Let(l) => self.let_decl(l), + // `randsequence` closes itself with `endsequence`; no `;`. + StmtKind::RandSequence(r) => self.rand_sequence(r), StmtKind::ParamDecl(d) => { concat(vec![self.param_decl(d, None), self.semi(before_semi)]) } diff --git a/crates/vlog_formatter/tests/cases/coverage_gaps_l6.cases b/crates/vlog_formatter/tests/cases/coverage_gaps_l6.cases new file mode 100644 index 0000000..4a2bcae --- /dev/null +++ b/crates/vlog_formatter/tests/cases/coverage_gaps_l6.cases @@ -0,0 +1,270 @@ +# TODO §54.1 — the six small language shapes coverage gap L6 left open. +# None of them occurs in the corpus or in opentitan, so these hand-written +# cases and the gap fuzzers are the whole acceptance. +# docs/features/coverage-gaps-l/README.md +# +# 1. `->>`, the non-blocking event trigger (IEEE 1800 §15.5.2), with and +# without a delay or event control of its own. `->` is untouched. +module m; +event e; +initial begin +-> e; +->> e; +->> #5 e; +->> @(posedge clk) e; +->> @(a or b) e; +->> #(1:2:3) e; +end +endmodule +---- +module m; + event e; + initial begin + -> e; + ->> e; + ->> #5 e; + ->> @(posedge clk) e; + ->> @(a or b) e; + ->> #(1:2:3) e; + end +endmodule +==== +# `->>` with a comment in each of its two gaps: after the arrow, and +# between the timing control and the event. +module m; + initial begin + ->> /*a*/ #5 /*b*/ e; + ->> /*c*/ e; + end +endmodule +---- +module m; + initial begin + ->> /*a*/ #5 /*b*/ e; + ->> /*c*/ e; + end +endmodule +==== +# 2. A stream expression's `with [range]` (IEEE 1800 §11.4.14) — the third +# postfix spelling of `with`, told from the other two by its `[`. +module m; +initial begin +a = {<<{b with [0:3]}}; +c = {>>{d with [i+:4]}}; +f = {<<{g with [i-:4]}}; +h = {<<{j with [i]}}; +k = {<>{d with [i+:4]}}; + f = {<<{g with [i-:4]}}; + h = {<<{j with [i]}}; + k = {< 3); + obj.randomize() with {a < 5;}; + end +endmodule +---- +module m; + initial begin + x = q.find(v) with (v > 3); + obj.randomize() with {a < 5;}; + end +endmodule +==== +# 3. The cast bases IEEE 1800 §6.24.1 allows besides a name and a system +# call: a parenthesised width, a sized literal, and a type with packed +# dimensions on it. +module m; +initial begin +x = (W+1)'(y); +z = 4'(y); +q = logic [3:0]'(y); +r = bit signed [7:0]'(y); +s = $clog2(N)'(y); +end +endmodule +---- +module m; + initial begin + x = (W + 1)'(y); + z = 4'(y); + q = logic [3:0]'(y); + r = bit signed [7:0]'(y); + s = $clog2(N)'(y); + end +endmodule +==== +# 4. Drive strength on a net declaration (IEEE 1800 §6.6), the position +# `ContAssign` has always read one in. +module m; +wire (strong0, weak1) w = a; +wire (supply0, supply1) [7:0] v; +wire (pull1, highz0) #5 d = e; +tri (weak1, weak0) t; +endmodule +---- +module m; + wire (strong0, weak1) w = a; + wire (supply0, supply1) [7:0] v; + wire (pull1, highz0) #5 d = e; + tri (weak1, weak0) t; +endmodule +==== +# The strength's five comment slots, on a net declaration and on the +# continuous assignment and the gate that already wrote one. +module m; + wire /*a*/ ( /*b*/ strong0 /*c*/ , /*d*/ weak1 /*e*/ ) w = a; + assign /*f*/ (weak0, pull1) x = y; + pullup /*g*/ ( /*h*/ weak1 /*i*/ ) p1 (n1); +endmodule +---- +module m; + wire /*a*/ ( /*b*/ strong0 /*c*/ , /*d*/ weak1 /*e*/ ) w = a; + assign /*f*/ (weak0, pull1) x = y; + pullup /*g*/ ( /*h*/ weak1 /*i*/ ) p1 (n1); +endmodule +==== +# A `(` after a net keyword that is not a strength is still not one: an +# implicitly-typed net whose value is parenthesised keeps its old parse. +module m; + wire w = (a & b); + assign (x) = y; +endmodule +---- +module m; + wire w = (a & b); + assign (x) = y; +endmodule +==== +# 5. `let` at statement position (IEEE 1800 §11.13) — the item-level +# grammar and the item-level layout, among a block's declarations. +module m; +initial begin +let sum = a + b; +let max(p, q) = (p > q) ? p : q; +x = sum + max(1, 2); +end +endmodule +---- +module m; + initial begin + let sum = a + b; + let max(p, q) = (p > q) ? p : q; + x = sum + max(1, 2); + end +endmodule +==== +# 6. The `#(min:typ:max)` clocking skew (IEEE 1800 §14.3), on a `default` +# item and on a direction group, beside the one-token spellings. +module m; +clocking cb @(posedge clk); +default input #(1:2:3) output #(2:3:4); +input #(1:2:3) sig; +output #(5) other; +input #1step a, b; +output negedge c; +endclocking +endmodule +---- +module m; + clocking cb @(posedge clk); + default input #(1:2:3) output #(2:3:4); + input #(1:2:3) sig; + output #(5) other; + input #1step a, b; + output negedge c; + endclocking +endmodule +==== +# The parenthesised skew's comment slots are the delay grammar's own: +# after the `#`, inside the parens and around each `:`. +module m; + clocking cb @(posedge clk); + default input # /*a*/ (1 /*c*/ : /*d*/ 2 /*e*/ : /*f*/ 3 /*g*/) output #(1:2:3); + endclocking +endmodule +---- +module m; + clocking cb @(posedge clk); + default input # /*a*/ (1 /*c*/ : /*d*/ 2 /*e*/ : /*f*/ 3 /*g*/) output #(1:2:3); + endclocking +endmodule +==== +# A comment written just inside the delay's `(` breaks the parens the way it +# does on a net delay (`wire # /*a*/ ( /*b*/ 1:2:3) a;`) — pre-existing +# layout the skew inherits by going through the same grammar. +module m; + clocking cb @(posedge clk); + default input # /*a*/ ( /*b*/ 1:2:3); + endclocking +endmodule +---- +module m; + clocking cb @(posedge clk); + default input # /*a*/ ( + /*b*/ + 1:2:3 + ); + endclocking +endmodule +==== +# The other half of §14.3's `clocking_skew ::= edge_identifier +# [ delay_control ] | delay_control`: an edge that carries a delay of its +# own, in both spellings, on a `default` item and on a direction group. +module m; +clocking cb @(posedge clk); +default input negedge #(1:2:3) output posedge #5; +input negedge #(1:2:3) sig; +output posedge #5 other; +input posedge #1step a, b; +input edge c; +endclocking +endmodule +---- +module m; + clocking cb @(posedge clk); + default input negedge #(1:2:3) output posedge #5; + input negedge #(1:2:3) sig; + output posedge #5 other; + input posedge #1step a, b; + input edge c; + endclocking +endmodule +==== +# The gap between the edge and the `#` is the skew's own slot; the gap +# after a bare edge still belongs to what follows it. +module m; + clocking cb @(posedge clk); + default input negedge /*a*/ #2 output /*b*/ posedge /*c*/ #(1:2:3); + input edge /*d*/ sig; + endclocking +endmodule +---- +module m; + clocking cb @(posedge clk); + default input negedge /*a*/ #2 output /*b*/ posedge /*c*/ #(1:2:3); + input edge /*d*/ sig; + endclocking +endmodule diff --git a/crates/vlog_formatter/tests/cases/randsequence.cases b/crates/vlog_formatter/tests/cases/randsequence.cases new file mode 100644 index 0000000..f0ec024 --- /dev/null +++ b/crates/vlog_formatter/tests/cases/randsequence.cases @@ -0,0 +1,257 @@ +# TODO §54.2 — `randsequence` (IEEE 1800 §18.17) as real nodes: a production +# list with weighted alternatives, not an opaque leaf. Zero occurrences in the +# corpus and in opentitan, so the LRM's own examples are the cases. +# docs/features/coverage-gaps-l/README.md +# +# §18.17's opening example: a start production and three plain ones. +module m; +initial begin +randsequence (main) +main : first second done; +first : add | dec; +second : pop | push; +done : {$display("done");}; +add : {$display("add");}; +dec : {$display("dec");}; +pop : {$display("pop");}; +push : {$display("push");}; +endsequence +end +endmodule +---- +module m; + initial begin + randsequence (main) + main : first second done; + first : add | dec; + second : pop | push; + done : { + $display("done"); + }; + add : { + $display("add"); + }; + dec : { + $display("dec"); + }; + pop : { + $display("pop"); + }; + push : { + $display("push"); + }; + endsequence + end +endmodule +==== +# Weighted alternatives (§18.17.2): `:= weight`, with and without the code +# block that runs when the alternative is chosen. Alternatives that fit stay +# on the production's line; the case after this one is the same list too wide +# for one, broken one per line with each `|` under the `:`. +module m; + initial begin + randsequence (top) + top : a := 3 | b := 2 | c := 1; + a : add; + b : dec := 5 {$display("chosen");}; + c : add; + add : {x = x + 1;}; + dec : {x = x - 1;}; + endsequence + end +endmodule +---- +module m; + initial begin + randsequence (top) + top : a := 3 | b := 2 | c := 1; + a : add; + b : dec := 5 { + $display("chosen"); + }; + c : add; + add : { + x = x + 1; + }; + dec : { + x = x - 1; + }; + endsequence + end +endmodule +==== +# The three control shapes an alternative's items may take (§18.17.3–4) and +# the interleaving `rand join` (§18.17.6). +module m; +initial begin +randsequence (main) +main : gen loop sel mix; +gen : if (cond) add else dec; +loop : repeat (3) add; +sel : case (mode) 0, 1 : add; 2 : dec; default : add; endcase; +mix : rand join add dec; +bias : rand join (0.5) add dec; +add : {x++;}; +dec : {x--;}; +endsequence +end +endmodule +---- +module m; + initial begin + randsequence (main) + main : gen loop sel mix; + gen : if (cond) add else dec; + loop : repeat (3) add; + sel : case (mode) + 0, 1: add; + 2: dec; + default: add; + endcase; + mix : rand join add dec; + bias : rand join (0.5) add dec; + add : { + x++; + }; + dec : { + x--; + }; + endsequence + end +endmodule +==== +# A production with a return type and formal arguments (§18.17.5), and a +# reference that passes arguments to one. +module m; + initial begin + randsequence (main) + main : bump(3) use_it; + void bump(int step) : { + total = total + step; + }; + int use_it : { + return total; + }; + endsequence + end +endmodule +---- +module m; + initial begin + randsequence (main) + main : bump(3) use_it; + void bump(int step) : { + total = total + step; + }; + int use_it : { + return total; + }; + endsequence + end +endmodule +==== +# `break` and `return` inside a production's code block are the ordinary +# statements they are, and `randsequence ()` may name no start production. +module m; + initial begin + randsequence () + main : { + if (done) break; + return; + }; + endsequence + end +endmodule +---- +module m; + initial begin + randsequence () + main : { + if (done) break; + return; + }; + endsequence + end +endmodule +==== +# Every gap of the grammar takes a comment and prints it back where it was +# written: around the `(main)`, around the `:`, the `|` and the `:=`, and +# inside a code block and a case arm. +module m; + initial begin + randsequence /*a*/ ( /*b*/ main /*c*/ ) + // above the production + main /*d*/ : /*e*/ first /*f*/ | /*g*/ second /*h*/ := /*i*/ 3 /*j*/ ; // after it + first : { + /*k*/ + x = 1; /*l*/ + }; + second : if /*m*/ (c) first /*n*/ else /*o*/ first; + third : case /*p*/ (x) + 1 /*q*/: /*r*/ first /*s*/ ; + default first; + endcase; + fourth : rand /*t*/ join (2) first second; + // before endsequence + endsequence + end +endmodule +---- +module m; + initial begin + randsequence /*a*/ ( /*b*/ main /*c*/ ) + // above the production + main /*d*/ : /*e*/ first /*f*/ | /*g*/ second /*h*/ := /*i*/ 3 /*j*/ ; // after it + first : { + /*k*/ + x = 1; /*l*/ + }; + second : if /*m*/ (c) first /*n*/ else /*o*/ first; + third : case /*p*/ (x) + 1 /*q*/: /*r*/ first /*s*/ ; + default first; + endcase; + fourth : rand /*t*/ join (2) first second; + // before endsequence + endsequence + end +endmodule +==== +# The same production with alternatives too wide for one line: one per line, +# each `|` starting its own, indented under the production's head. +module m; + initial begin + randsequence (top) + top : first_alternative_name := 3 | second_alternative_name := 2 | third_alternative_name := 1; + first_alternative_name : { + x = 1; + }; + second_alternative_name : { + x = 2; + }; + third_alternative_name : { + x = 3; + }; + endsequence + end +endmodule +---- +module m; + initial begin + randsequence (top) + top : + first_alternative_name := 3 + | second_alternative_name := 2 + | third_alternative_name := 1; + first_alternative_name : { + x = 1; + }; + second_alternative_name : { + x = 2; + }; + third_alternative_name : { + x = 3; + }; + endsequence + end +endmodule diff --git a/crates/vlog_formatter/tests/format_options.rs b/crates/vlog_formatter/tests/format_options.rs new file mode 100644 index 0000000..52010c3 --- /dev/null +++ b/crates/vlog_formatter/tests/format_options.rs @@ -0,0 +1,240 @@ +//! The `[format]` config keys — the layout choices that are off unless a +//! project turns them on (TODO §54.3). +//! +//! Every one of them changes the output of files that already format cleanly, +//! so each test asserts both directions: the shipped default leaves the file +//! exactly as it was, and the key on produces the asked-for layout and is +//! still idempotent. + +use vlog_formatter::{format_source, Config}; + +/// A class body written the way UVM's own examples write one. +const UVM_CLASS: &str = "\ +class c extends uvm_object; + `uvm_object_utils_begin(c) + `uvm_field_int(a, UVM_DEFAULT) + `uvm_field_string(b, UVM_DEFAULT) + `uvm_object_utils_end + function new(string name = \"c\"); + super.new(name); + endfunction +endclass +"; + +/// The same body with the field macros indented one level. +const UVM_CLASS_INDENTED: &str = "\ +class c extends uvm_object; + `uvm_object_utils_begin(c) + `uvm_field_int(a, UVM_DEFAULT) + `uvm_field_string(b, UVM_DEFAULT) + `uvm_object_utils_end + function new(string name = \"c\"); + super.new(name); + endfunction +endclass +"; + +fn on() -> Config { + Config { uvm_utils_indent: true, ..Config::default() } +} + +fn format(src: &str, config: &Config) -> String { + format_source(src, config).expect("formats") +} + +#[test] +fn the_shipped_default_leaves_uvm_utils_macros_where_they_stand() { + assert_eq!(format(UVM_CLASS, &Config::default()), UVM_CLASS); + // And it un-indents a file that was written indented, which is exactly + // why the key exists: without it there is no way to keep that shape. + assert_eq!(format(UVM_CLASS_INDENTED, &Config::default()), UVM_CLASS); +} + +#[test] +fn uvm_utils_indent_indents_the_run_between_begin_and_end() { + assert_eq!(format(UVM_CLASS, &on()), UVM_CLASS_INDENTED); + assert_eq!(format(UVM_CLASS_INDENTED, &on()), UVM_CLASS_INDENTED); +} + +#[test] +fn uvm_utils_indent_is_idempotent() { + let once = format(UVM_CLASS, &on()); + assert_eq!(format(&once, &on()), once); +} + +#[test] +fn the_component_spelling_opens_the_same_level() { + let src = "\ +class c extends uvm_component; + `uvm_component_utils_begin(c) + `uvm_field_int(a, UVM_DEFAULT) + `uvm_component_utils_end +endclass +"; + let want = "\ +class c extends uvm_component; + `uvm_component_utils_begin(c) + `uvm_field_int(a, UVM_DEFAULT) + `uvm_component_utils_end +endclass +"; + assert_eq!(format(src, &on()), want); +} + +#[test] +fn only_those_four_macro_names_open_a_level() { + // A macro pair that merely *looks* like the idiom is not it: the rule is + // four names, not a heuristic about `_begin`/`_end`. + let src = "\ +class c; + `my_utils_begin(c) + `my_field(a) + `my_utils_end +endclass +"; + assert_eq!(format(src, &on()), src); +} + +#[test] +fn comments_inside_the_run_are_indented_with_it_and_never_dropped() { + let src = "\ +class c extends uvm_object; + `uvm_object_utils_begin(c) + // why this field matters + `uvm_field_int(a, UVM_DEFAULT) // trailing + `uvm_object_utils_end +endclass +"; + let want = "\ +class c extends uvm_object; + `uvm_object_utils_begin(c) + // why this field matters + `uvm_field_int(a, UVM_DEFAULT) // trailing + `uvm_object_utils_end +endclass +"; + assert_eq!(format(src, &on()), want); +} + +#[test] +fn a_begin_with_no_end_still_prints_everything_it_opened() { + // lucisv reproduces the file it was given, unbalanced macros included. + let src = "\ +class c extends uvm_object; + `uvm_object_utils_begin(c) + `uvm_field_int(a, UVM_DEFAULT) +endclass +"; + let want = "\ +class c extends uvm_object; + `uvm_object_utils_begin(c) + `uvm_field_int(a, UVM_DEFAULT) +endclass +"; + assert_eq!(format(src, &on()), want); + assert_eq!(format(&format(src, &on()), &on()), want); +} + +/// The other half of coverage gap L10: an enum body one-lined when it is +/// short. **This already is the default** — measured 2026-09-06, over every +/// shape the gap names — so no config key was added for it. The test pins the +/// behaviour so nothing takes it away. +#[test] +fn a_short_enum_body_is_already_one_lined_by_default() { + let broken = "\ +package p; + typedef enum { + A, + B, + C + } e_t; + typedef enum logic [1:0] { + X = 0, + Y, + Z + } s_e; + enum { + IDLE, + BUSY + } state; +endpackage +"; + let want = "\ +package p; + typedef enum {A, B, C} e_t; + typedef enum logic [1:0] {X = 0, Y, Z} s_e; + enum {IDLE, BUSY} state; +endpackage +"; + assert_eq!(format(broken, &Config::default()), want); +} + +/// And a body with a comment in it still breaks, which is the condition the +/// gap named: one-lining it would put a `//` in front of the `}`. +#[test] +fn an_enum_body_with_a_comment_still_breaks_one_member_per_line() { + let src = "\ +package p; + typedef enum { + A, // first + B + } e_t; +endpackage +"; + assert_eq!(format(src, &Config::default()), src); +} + +#[test] +fn a_nested_begin_opens_a_level_of_its_own_and_its_end_closes_that_one() { + // Real UVM code never nests these macros, but the rule tracks a stack all + // the same: the first `_end` closes the `_begin` it matches, not the run. + let src = "\ +class c extends uvm_object; + `uvm_object_utils_begin(c) + `uvm_field_int(a, UVM_DEFAULT) + `uvm_object_utils_begin(d) + `uvm_field_int(b, UVM_DEFAULT) + `uvm_object_utils_end + `uvm_field_int(e, UVM_DEFAULT) + `uvm_object_utils_end + `uvm_field_int(f, UVM_DEFAULT) +endclass +"; + let want = "\ +class c extends uvm_object; + `uvm_object_utils_begin(c) + `uvm_field_int(a, UVM_DEFAULT) + `uvm_object_utils_begin(d) + `uvm_field_int(b, UVM_DEFAULT) + `uvm_object_utils_end + `uvm_field_int(e, UVM_DEFAULT) + `uvm_object_utils_end + `uvm_field_int(f, UVM_DEFAULT) +endclass +"; + assert_eq!(format(src, &on()), want); + assert_eq!(format(want, &on()), want, "idempotent"); +} + +#[test] +fn an_end_with_no_begin_open_changes_no_indentation() { + // Nothing to close, so nothing moves — the file comes back as written. + let src = "\ +class c extends uvm_object; + `uvm_object_utils_end + `uvm_field_int(a, UVM_DEFAULT) +endclass +"; + assert_eq!(format(src, &on()), src); + // And an unmatched `_end` after a closed pair closes nothing either. + let after = "\ +class c extends uvm_object; + `uvm_object_utils_begin(c) + `uvm_field_int(a, UVM_DEFAULT) + `uvm_object_utils_end + `uvm_object_utils_end + `uvm_field_int(b, UVM_DEFAULT) +endclass +"; + assert_eq!(format(after, &on()), after); +} diff --git a/crates/vlog_formatter/tests/verification.rs b/crates/vlog_formatter/tests/verification.rs index 3a04fcf..22e2961 100644 --- a/crates/vlog_formatter/tests/verification.rs +++ b/crates/vlog_formatter/tests/verification.rs @@ -260,6 +260,136 @@ fn reindented_string_inside_a_with_block_is_rejected() { expect_divergence(input, output); } +// ---------------------------------------------------------------------- +// The shapes TODO §54 added — masked-corruption attack pairs +// +// `verify.rs` was not touched by this round and no normalization was +// widened (CLAUDE.md invariant 4 asks for these anyway): each pair is a +// plausible way a new printer could have lost or rewritten something, and +// each must be refused. They are `(input, corrupted output)` pairs handed +// straight to the safety net, so they hold whether or not the formatter +// would ever produce that output. +// ---------------------------------------------------------------------- + +#[test] +fn an_event_trigger_arrow_rewritten_as_the_other_one_is_rejected() { + // `->` and `->>` are different statements — blocking and non-blocking — + // so normalizing one into the other changes the design. + expect_divergence( + "module m;\n initial -> e;\nendmodule\n", + "module m;\n initial ->> e;\nendmodule\n", + ); + expect_divergence( + "module m;\n initial ->> e;\nendmodule\n", + "module m;\n initial -> e;\nendmodule\n", + ); +} + +#[test] +fn a_dropped_event_trigger_timing_control_is_rejected() { + expect_divergence( + "module m;\n initial ->> #5 e;\nendmodule\n", + "module m;\n initial ->> e;\nendmodule\n", + ); +} + +#[test] +fn a_stream_range_turned_into_an_index_is_rejected() { + // `a with [0:3]` and `a with [0]` select different bits. + expect_divergence( + "module m;\n initial q = {<<{a with [0:3]}};\nendmodule\n", + "module m;\n initial q = {<<{a with [0]}};\nendmodule\n", + ); + // And a part-select operator swapped for another one. + expect_divergence( + "module m;\n initial q = {<<{a with [i+:4]}};\nendmodule\n", + "module m;\n initial q = {<<{a with [i-:4]}};\nendmodule\n", + ); +} + +#[test] +fn a_dropped_or_reordered_drive_strength_is_rejected() { + expect_divergence( + "module m;\n wire (strong0, weak1) w = a;\nendmodule\n", + "module m;\n wire w = a;\nendmodule\n", + ); + // The two keywords may be written in either order and mean different + // things; a printer that sorted them would be corrupting the design. + expect_divergence( + "module m;\n wire (strong0, weak1) w = a;\nendmodule\n", + "module m;\n wire (weak1, strong0) w = a;\nendmodule\n", + ); +} + +#[test] +fn a_clocking_skew_rewritten_into_a_bare_delay_is_rejected() { + // `#(1:2:3)` is three values; `#1` is one. + expect_divergence( + "module m;\n clocking cb @(posedge clk);\n input #(1:2:3) sig;\n endclocking\nendmodule\n", + "module m;\n clocking cb @(posedge clk);\n input #1 sig;\n endclocking\nendmodule\n", + ); + // An edge and the delay behind it are one skew (§14.3): losing either + // half changes when the signal is sampled. + expect_divergence( + "module m;\n clocking cb @(posedge clk);\n input negedge #5 sig;\n endclocking\nendmodule\n", + "module m;\n clocking cb @(posedge clk);\n input negedge sig;\n endclocking\nendmodule\n", + ); + expect_divergence( + "module m;\n clocking cb @(posedge clk);\n input negedge #5 sig;\n endclocking\nendmodule\n", + "module m;\n clocking cb @(posedge clk);\n input #5 sig;\n endclocking\nendmodule\n", + ); +} + +#[test] +fn a_dropped_randsequence_production_is_rejected() { + let input = "module m;\n initial begin\n randsequence (main)\n main : a b;\n a : {x = 1;};\n b : {x = 2;};\n endsequence\n end\nendmodule\n"; + let output = "module m;\n initial begin\n randsequence (main)\n main : a b;\n a : {x = 1;};\n endsequence\n end\nendmodule\n"; + expect_divergence(input, output); +} + +#[test] +fn a_reordered_randsequence_alternative_is_rejected() { + // The order of the alternatives is what `:=` weights are relative to. + let input = "module m;\n initial begin\n randsequence (main)\n main : a := 3 | b := 1;\n endsequence\n end\nendmodule\n"; + let output = "module m;\n initial begin\n randsequence (main)\n main : b := 1 | a := 3;\n endsequence\n end\nendmodule\n"; + expect_divergence(input, output); +} + +#[test] +fn a_randsequence_bar_turned_into_a_juxtaposition_is_rejected() { + // `a | b` picks one; `a b` runs both. One token apart, opposite meanings. + let input = "module m;\n initial begin\n randsequence (main)\n main : a | b;\n endsequence\n end\nendmodule\n"; + let output = "module m;\n initial begin\n randsequence (main)\n main : a b;\n endsequence\n end\nendmodule\n"; + expect_divergence(input, output); +} + +#[test] +fn a_dropped_randsequence_weight_is_rejected() { + let input = "module m;\n initial begin\n randsequence (main)\n main : a := 3 | b;\n endsequence\n end\nendmodule\n"; + let output = "module m;\n initial begin\n randsequence (main)\n main : a | b;\n endsequence\n end\nendmodule\n"; + expect_divergence(input, output); +} + +#[test] +fn a_let_statement_losing_its_ports_is_rejected() { + expect_divergence( + "module m;\n initial begin\n let f(a) = a + 1;\n end\nendmodule\n", + "module m;\n initial begin\n let f = a + 1;\n end\nendmodule\n", + ); +} + +#[test] +fn uvm_utils_indentation_is_whitespace_the_net_ignores_and_a_dropped_macro_is_not() { + // The `uvm-utils-indent` key only ever moves leading whitespace, which is + // exactly what the net is allowed to forgive... + let flat = "class c;\n `uvm_object_utils_begin(c)\n `uvm_field_int(a, UVM_DEFAULT)\n `uvm_object_utils_end\nendclass\n"; + let indented = "class c;\n `uvm_object_utils_begin(c)\n `uvm_field_int(a, UVM_DEFAULT)\n `uvm_object_utils_end\nendclass\n"; + verify_equivalence(flat, indented).expect("indentation alone is not a divergence"); + // ...and losing one of the macros it indents is not. + let dropped = "class c;\n `uvm_object_utils_begin(c)\n `uvm_object_utils_end\nendclass\n"; + expect_divergence(flat, dropped); +} + #[test] fn truncated_output_is_rejected() { let input = "module m;\n wire x;\nendmodule\n"; @@ -1151,7 +1281,7 @@ fn a_dropped_method_qualifier_is_rejected() { /// Format `src` at `width`, then format that again, and return both. fn twice(src: &str, width: usize, indent: usize) -> (String, String) { - let config = Config { max_width: width, indent_width: indent }; + let config = Config { max_width: width, indent_width: indent, ..Config::default() }; let once = format_source(src, &config).expect("first pass"); let again = format_source(&once, &config).expect("second pass"); (once, again) @@ -2360,6 +2490,12 @@ const RTL_FIXTURES: &[&str] = &[ // owner until this round — `MinTypMaxComments`, `DelayValue`, and the // gate's own `before_hash`/`after_hash`/`before_args`/`before_semi`. "module m;\n wire #(1:2:3) a;\n assign #(1:2:3) z = a;\n and #(2, 3) g1 (y, a, b);\nendmodule\n", + // The six shapes of TODO §54.1. Each opened a gap the parser had no slot + // for — the arrow of `->>`, the `with [ … ]` bracket, the five of a drive + // strength, the `let` head, and the parenthesized clocking skew — and + // this is what says every one of them found an owner. + "module m;\n wire (strong0, weak1) w = a;\n initial begin\n ->> #5 e;\n q = {<<{a with [i+:4]}};\n let sum = a + b;\n end\nendmodule\n", + "module m;\n clocking cb @(posedge clk);\n default input #(1:2:3) output #2;\n input #(5) sig;\n output negedge #5 o;\n endclocking\nendmodule\n", ]; #[test] @@ -2368,8 +2504,23 @@ fn a_comment_in_every_rtl_gap_still_formats() { } /// Inter-token gaps across [`RTL_FIXTURES`]. 374 before TODO §45.4 added the -/// delay-list fixture, whose 45 gaps brought the total here. -const EXPECTED_RTL_GAPS: usize = 419; +/// delay-list fixture, whose 45 gaps took it to 419; TODO §54.1's two +/// fixtures — the six L6 shapes and a clocking block — brought the 80 that +/// take it here. Nineteen of those 80 failed when the fixtures were written, +/// none of them because of the new shapes: the `let` head, the two brace +/// pairs of a streaming concatenation and the whole clocking grammar had no +/// comment slots at all, and fail identically on a tree without this round +/// (`let /*C*/ sum = a + b;` as an item, `{ /*C*/ <<{a}}`, +/// `clocking /*C*/ cb`). All nineteen have owners now — `LetDecl`'s +/// `after_kw`/`eq_comments`/`before_semi`, `StreamComments`, +/// `ClockingDecl`'s `after_kw`/`before_event`/`before_semi`, +/// `ClockingDefault`, `ClockingItem::before_semi` and the skew's own +/// `after_hash`. The rework of §54.1 added `output negedge #5 o;` to the +/// clocking fixture — the LRM's `edge_identifier [delay_control]`, which the +/// round's first pass could not parse — for the 6 that take it to 505, none of +/// them failing: the gap between the edge and its `#` is +/// `ClockingSkew::Edge::after_edge`. +const EXPECTED_RTL_GAPS: usize = 505; // ---------------------------------------------------------------------- // Vendor and formal collateral — `vendor-formal-grammar` diff --git a/crates/vlog_linter/src/exprs.rs b/crates/vlog_linter/src/exprs.rs index dae869d..b001ce1 100644 --- a/crates/vlog_linter/src/exprs.rs +++ b/crates/vlog_linter/src/exprs.rs @@ -86,7 +86,8 @@ pub(crate) fn walk_exprs(file: &SourceFile, f: &mut dyn FnMut(&Expr)) { root(expr); } } - StmtKind::ExprStmt(expr) | StmtKind::EventTrigger(expr) => root(expr), + StmtKind::ExprStmt(expr) => root(expr), + StmtKind::EventTrigger(t) => root(&t.expr), StmtKind::If { cond, .. } => root(cond), StmtKind::Case { expr, items, .. } => { root(expr); @@ -244,6 +245,14 @@ fn descend(expr: &Expr, f: &mut dyn FnMut(&Expr)) { } ExprKind::InsideMacro { lhs, .. } => descend(lhs, f), ExprKind::With { base, .. } | ExprKind::WithConstraint { base, .. } => descend(base, f), + // The stream range's operands are reads like any index's. + ExprKind::StreamWith { base, range } => { + descend(base, f); + descend(&range.msb, f); + if let Some(lsb) = &range.lsb { + descend(lsb, f); + } + } ExprKind::Dist { expr: inner, .. } => descend(inner, f), ExprKind::NamedArg { value, .. } => descend(value, f), ExprKind::AssignPattern(items) => { diff --git a/crates/vlog_linter/src/signals.rs b/crates/vlog_linter/src/signals.rs index 67a0120..ba61e4c 100644 --- a/crates/vlog_linter/src/signals.rs +++ b/crates/vlog_linter/src/signals.rs @@ -466,8 +466,8 @@ impl Scanner { None => self.unknown.push(expr.span), }, // `-> ev;` is what drives a named event. - StmtKind::EventTrigger(expr) => { - self.write(expr, DriverKind::Trigger, block, in_generate) + StmtKind::EventTrigger(t) => { + self.write(&t.expr, DriverKind::Trigger, block, in_generate) } StmtKind::MacroStmt(_) | StmtKind::Directive(_) diff --git a/crates/vlog_parser/src/ast/decl.rs b/crates/vlog_parser/src/ast/decl.rs index b0152e5..9f34446 100644 --- a/crates/vlog_parser/src/ast/decl.rs +++ b/crates/vlog_parser/src/ast/decl.rs @@ -340,6 +340,12 @@ pub struct NetDelay { pub struct DataDecl { /// Net type (`wire`, `tri`, ...) if any. pub net: Option, + /// Drive strength: the `(strong0, weak1)` of + /// `wire (strong0, weak1) w = a;` (IEEE 1800 §6.6), read only after a net + /// keyword — the one position the grammar allows it. Carried the way + /// [`ContAssign::strength`] is, and printed between the net keyword and + /// the delay, where the source wrote it. + pub strength: Option, /// Net delay, if any: the `5` in `wire #5 w;` or the `0.1` in /// `wire [31:0] #0.1 x = y;`. pub delay: Option, @@ -477,6 +483,8 @@ pub struct TaskDecl { /// growing a near-identical node of their own. #[derive(Debug)] pub struct LetDecl { + /// Comments written between the `let` keyword and the name. + pub after_kw: Vec, pub name: String, /// Byte range of `name`. pub name_span: TextRange, @@ -484,7 +492,12 @@ pub struct LetDecl { /// written when this is true and [`LetDecl::ports`] is empty. pub has_parens: bool, pub ports: Vec>, + /// Comments written on either side of the `=`, each kept on its own side + /// of it the way a declarator's `eq_comments` are. + pub eq_comments: Box, pub value: Expr, + /// Comments written between the value and the `;`. + pub before_semi: Vec, } #[derive(Debug)] diff --git a/crates/vlog_parser/src/ast/expr.rs b/crates/vlog_parser/src/ast/expr.rs index 8a398e6..45dc53a 100644 --- a/crates/vlog_parser/src/ast/expr.rs +++ b/crates/vlog_parser/src/ast/expr.rs @@ -119,6 +119,18 @@ pub enum ExprKind { /// The stream expressions, carrying their comments the way a /// concatenation's elements do. inner: Vec, + /// The three gaps the two nested brace pairs open. Boxed to keep + /// `Expr` small, as for `TernaryComments`. + comments: Box, + }, + /// `expr with [ range ]` — a stream expression's array range + /// (IEEE 1800 §11.4.14): `{<< {a with [0:3]}}`, `{>> {a with [i+:4]}}`, + /// `{<< {a with [i]}}`. The only `with` whose argument is a bracket + /// rather than a `(` or a `{`, which is what tells it from an array + /// method's iterator argument and from a `randomize` constraint block. + StreamWith { + base: Box, + range: Box, }, Paren { inner: Box, @@ -451,6 +463,45 @@ pub struct WithComments { pub after_kw: Vec, } +/// The gaps of a streaming concatenation's own brackets: +/// `{ /*a*/ << byte /*b*/ { x } /*c*/ }`. The elements inside carry their own +/// comments the way a concatenation's do; these three are what the nesting of +/// the two brace pairs leaves over. +#[derive(Debug, Clone, Default)] +pub struct StreamComments { + /// Between the outer `{` and the `<<` or `>>`. + pub after_open: Vec, + /// Between the direction (or the slice size) and the inner `{`. + pub before_inner: Vec, + /// Between the inner `}` and the outer `}`. + pub before_close: Vec, +} + +/// The `with [ … ]` bracket of a stream expression: one index (`[i]`) or a +/// range in any of the three spellings a part select takes (`[m:l]`, +/// `[i+:n]`, `[i-:n]`). +/// +/// It is not an [`ExprKind::Range`] because that node wraps a *base* — here +/// the base stands on the `with`'s left, outside the bracket — but it keeps +/// exactly the same comment slots, so the printer lays both out through one +/// function. +#[derive(Debug, Clone)] +pub struct StreamRange { + /// Comments written on either side of the `with` keyword. + pub with_comments: WithComments, + /// The single index, or the range's first operand. + pub msb: Expr, + /// `:`, `+:` or `-:`; `None` for the single-index spelling. + pub op: Option, + /// The range's second operand; `None` for the single-index spelling. + pub lsb: Option, + /// `[ /*a*/ m /*b*/ : /*c*/ l /*d*/ ]` — the slots + /// [`SegmentComments`] names. `before_open` is always empty here: what + /// was written between the `with` and the `[` belongs to the keyword, so + /// it goes in `with_comments.after_kw`. + pub comments: SegmentComments, +} + impl TernaryComments { /// True when nothing was written inside the `? :` — the common case, laid /// out without any comment handling. diff --git a/crates/vlog_parser/src/ast/mod.rs b/crates/vlog_parser/src/ast/mod.rs index 8eed2f7..96b26f5 100644 --- a/crates/vlog_parser/src/ast/mod.rs +++ b/crates/vlog_parser/src/ast/mod.rs @@ -33,6 +33,7 @@ //! | `expr` | [`Expr`], [`ExprKind`], the expression comment slots | //! | `class`, `covergroup` | classes and constraints; covergroups | //! | `sva` | assertions, `property`/`sequence`, the property-expression tree | +//! | `randsequence` | the `randsequence` production grammar (IEEE 1800 §18.17) | use crate::span::TextRange; use crate::token::Comment; @@ -42,6 +43,7 @@ mod covergroup; mod decl; mod expr; mod module; +mod randsequence; mod stmt; mod sva; @@ -50,6 +52,7 @@ pub use covergroup::*; pub use decl::*; pub use expr::*; pub use module::*; +pub use randsequence::*; pub use stmt::*; pub use sva::*; diff --git a/crates/vlog_parser/src/ast/module.rs b/crates/vlog_parser/src/ast/module.rs index 628530c..5bdcfff 100644 --- a/crates/vlog_parser/src/ast/module.rs +++ b/crates/vlog_parser/src/ast/module.rs @@ -183,6 +183,24 @@ pub struct DriveStrength { /// `None` for the single-strength spelling `pullup (weak1) p (x);` /// (IEEE 1800 §28.3's `pullup_strength`), which only a pull gate takes. pub second: Option, + /// Boxed: five comment vectors dwarf the two strength words, and a + /// [`DataDecl`] carrying one of these is what `ast::size_pins` measures. + pub comments: Box, +} + +/// The five gaps of `/*a*/ ( /*b*/ strong0 /*c*/ , /*d*/ weak1 /*e*/ )`. +/// +/// `before_open` is the gap in front of the `(` — the strength owns it because +/// the three constructs that write one (`assign`, a gate, a net declaration) +/// all have something of their own directly in front of it. +#[derive(Debug, Default)] +pub struct DriveStrengthComments { + pub before_open: Vec, + pub after_open: Vec, + /// Empty for the single-strength spelling, which has no `,`. + pub before_comma: Vec, + pub after_comma: Vec, + pub before_close: Vec, } #[derive(Debug)] @@ -549,8 +567,16 @@ pub struct ModportPort { pub struct ClockingDecl { /// True when the declaration was written `default clocking ...`. pub is_default: bool, + /// Comments written between the `clocking` keyword and whatever follows + /// it — the name, or the `@` of an anonymous block. + pub after_kw: Vec, /// `None` for the anonymous `default clocking @(posedge clk);` form. pub name: Option, + /// Comments written between the name and the `@` of the clocking event. + /// Empty when no name or no event was written. + pub before_event: Vec, + /// Comments written between the header's last token and its `;`. + pub before_semi: Vec, /// The `@( ... )` clocking event. `None` for `default clocking cb;`, which /// selects an existing clocking block and has no body. pub event: Option, @@ -572,6 +598,8 @@ pub struct ClockingDecl { pub struct ClockingItem { pub meta: Meta, pub kind: ClockingItemKind, + /// Comments written between the item's last token and its `;`. + pub before_semi: Vec, /// Code extent of the item, its `;` excluded. pub span: TextRange, } @@ -579,10 +607,73 @@ pub struct ClockingItem { #[derive(Debug)] pub enum ClockingItemKind { /// `default input #1step output #0;` — at least one half is written. - Default { input: Option, output: Option }, + Default { input: Option, output: Option }, /// `input #2 a, b;`, `output negedge c;`, `inout d;`. `skew` is the delay /// or edge as written (`#2`, `negedge`), or `None` when omitted. - Signals { dir: String, skew: Option, signals: Vec }, + Signals { + dir: String, + /// Comments written between the direction keyword and the skew — or, + /// when no skew was written, between it and the first signal name. + after_dir: Vec, + skew: Option, + /// Comments written between that skew and the first signal name. + /// Empty when no skew was written. + after_skew: Vec, + signals: Vec, + }, +} + +/// One half of a `default input #1step output #0;` item: a direction keyword +/// and the skew that follows it. +#[derive(Debug)] +pub struct ClockingDefault { + /// Comments written between whatever precedes the direction keyword — the + /// `default`, or the other half's skew — and the keyword itself. + pub before_dir: Vec, + /// Comments written between the direction keyword and the skew. + pub after_dir: Vec, + pub skew: ClockingSkew, +} + +/// The skew of a clocking item — IEEE 1800 §14.3's +/// `clocking_skew ::= edge_identifier [ delay_control ] | delay_control`. +#[derive(Debug)] +pub enum ClockingSkew { + /// `posedge`, `negedge`, `edge`, each of which may carry a delay of its + /// own (`input negedge #(1:2:3) sig;`). + Edge { + /// The edge keyword as written. + word: String, + /// Comments written between that keyword and the `#` behind it. Empty + /// when no delay was written — the gap is then the caller's own slot + /// before the signal name or the other `default` half. + after_edge: Vec, + delay: Option, + }, + /// A skew that is a `delay_control` alone: `#2`, `#(1:2:3)`. + Delay(ClockingDelay), +} + +/// The `# …` half of a clocking skew — IEEE 1800 §14.3's `delay_control`, +/// written alone or behind an edge identifier. +#[derive(Debug)] +pub enum ClockingDelay { + /// `#2`, `#1step` — the one token written after the `#`, kept exactly as + /// written: it is a delay, never something lucisv re-lays out. + Word { + /// Comments written between the `#` and that token. + after_hash: Vec, + word: String, + }, + /// The parenthesized spelling `#(1:2:3)`, `#(5)` — the same delay + /// expression a net declaration writes, so it arrives with the comment + /// slots [`ExprKind::MinTypMax`] and [`ExprKind::Paren`] already have. + Paren { + /// Comments written between the `#` and the `(`. + after_hash: Vec, + /// The parenthesized delay, `(` and `)` included. + expr: Expr, + }, } /// One `signal [= expression]` of a clocking direction group — IEEE 1800 diff --git a/crates/vlog_parser/src/ast/randsequence.rs b/crates/vlog_parser/src/ast/randsequence.rs new file mode 100644 index 0000000..9d6ca55 --- /dev/null +++ b/crates/vlog_parser/src/ast/randsequence.rs @@ -0,0 +1,173 @@ +//! `randsequence` — the production grammar of IEEE 1800 §18.17. +//! +//! A `randsequence` statement is a little grammar of its own written inside a +//! procedural block: a list of *productions*, each a name with optional +//! arguments and return type, each defining one or more weighted +//! *alternatives*, each alternative a run of *items* — a reference to another +//! production, a code block of ordinary statements, or one of the three +//! control shapes (`if`/`else`, `repeat`, `case`). +//! +//! Every node here carries the comment slots its own tokens open, for the +//! reason the rest of the AST does: a comment written between two tokens must +//! print back between those same two tokens or `verify.rs` refuses the file. + +use super::*; + +/// `randsequence (main) … endsequence` (IEEE 1800 §18.17). +#[derive(Debug)] +pub struct RandSequence { + /// Comments written between the keyword and its `(`. + pub after_kw: Vec, + /// Comments written just inside the `(`. + pub after_open: Vec, + /// The starting production, `None` for the empty `randsequence ()`. + pub start: Option, + /// Comments written between that name and the `)`. + pub before_close: Vec, + pub productions: Vec, + /// Comments written after the last production and before `endsequence`. + pub dangling: Vec, +} + +/// One production: `[type] name [(ports)] : alternative { | alternative } ;`. +#[derive(Debug)] +pub struct Production { + pub meta: Meta, + /// The production's return type, `None` when it declares none (or wrote + /// `void`, which is kept here as an ordinary type name). + pub ret_type: Option, + pub name: String, + /// Byte range of `name`. + pub name_span: TextRange, + /// True when the production wrote a `( … )` port list, even an empty one. + pub has_parens: bool, + /// The formal arguments, read as a subroutine's are (§18.17.5). + pub args: Vec>, + /// Comments written between the head and the `:`. + pub before_colon: Vec, + /// At least one; the `|`-separated right-hand sides. + pub alternatives: Vec, + /// Comments written between the last alternative and the `;`. + pub before_semi: Vec, + /// Code extent of the production, its `;` excluded. + pub span: TextRange, +} + +/// One `|`-separated right-hand side of a production, with the optional +/// `:= weight` that biases it. +#[derive(Debug)] +pub struct Alternative { + /// Comments written between the previous alternative and the `|` that + /// starts this one. Always empty on the first alternative, whose left + /// neighbour is the production's `:`. + pub before_bar: Vec, + /// Comments written between the `:` (or the `|`) and the first item. + pub after_bar: Vec, + pub items: Vec, + /// Comments written between the last item and the `:=`. + pub before_weight: Vec, + /// The `:= expr` weight (§18.17.2), `None` when unweighted. + pub weight: Option, +} + +/// The `:= weight [code block]` of a weighted alternative. +#[derive(Debug)] +pub struct Weight { + /// Comments written between the `:=` and the weight expression. + pub after_op: Vec, + pub expr: Expr, + /// The optional code block run when the alternative is chosen. + pub block: Option>, +} + +/// One item of an alternative's right-hand side — §18.17's `rs_prod`. +#[derive(Debug)] +pub enum ProdItem { + /// `name`, or `name(args)` — a reference to another production. + Ref(ProdRef), + /// `{ … }` — ordinary statements, laid out as a `begin`/`end` body is. + Block(Box), + /// `if (expr) item [else item]`. + If { + /// Comments written between the `if` and its `(`. + after_kw: Vec, + cond: Expr, + then: Box, + /// Comments written between the `then` item and the `else`. + before_else: Vec, + /// Comments written between the `else` and its item. + after_else: Vec, + els: Option>, + }, + /// `repeat (expr) item`. + Repeat { + /// Comments written between the `repeat` and its `(`. + after_kw: Vec, + count: Expr, + body: Box, + }, + /// `case (expr) … endcase`, whose arms take production items rather than + /// statements. + Case { + /// Comments written between the `case` and its `(`. + after_kw: Vec, + expr: Expr, + items: Vec, + /// Comments written after the last arm and before `endcase`. + dangling: Vec, + }, + /// `rand join [(expr)] item item { item }` (§18.17.6). + RandJoin { + /// Comments written between the `rand` and the `join`. + after_rand: Vec, + /// The `( expr )` bias, `None` when omitted. + weight: Option, + items: Vec, + }, +} + +/// A reference to another production: `name` or `name(a, b)`. +#[derive(Debug)] +pub struct ProdRef { + pub name: String, + /// Byte range of `name`. + pub name_span: TextRange, + /// True when a `( … )` argument list was written, even an empty one. + pub has_parens: bool, + /// Comments written between the name and that `(`. + pub before_args: Vec, + pub args: Vec, +} + +/// One arm of an `rs_case`: `expr, expr : item;` or `default [:] item;`. +#[derive(Debug)] +pub struct ProdCaseItem { + pub meta: Meta, + /// Empty for the `default` arm. + pub labels: Vec, + /// True when the arm was written `default`. + pub is_default: bool, + /// Comments written between the labels (or the `default`) and the `:`. + pub before_colon: Vec, + /// Comments written between the `:` and the item. A `default` arm may + /// write no `:` at all, and then this is the gap after the keyword. + pub after_colon: Vec, + pub item: ProdItem, + /// Comments written between the item and the arm's `;`. + pub before_semi: Vec, + /// Code extent of the arm, its `;` excluded. + pub span: TextRange, +} + +/// An `rs_code_block`: `{ declarations statements }`. The braces are the +/// block's own, and what stands between them is the statement grammar. +/// +/// There is no slot for the gap just inside the `{`: it belongs to the first +/// statement's leading comments, exactly as a `begin`/`end` block's does, and +/// to `dangling` when the block holds no statement at all. +#[derive(Debug)] +pub struct CodeBlock { + pub stmts: Vec, + /// Comments written after the last statement and before the `}`. + pub dangling: Vec, +} diff --git a/crates/vlog_parser/src/ast/stmt.rs b/crates/vlog_parser/src/ast/stmt.rs index af4b388..ec7a906 100644 --- a/crates/vlog_parser/src/ast/stmt.rs +++ b/crates/vlog_parser/src/ast/stmt.rs @@ -253,9 +253,25 @@ pub enum StmtKind { stmt: Option>, }, ExprStmt(Expr), - /// `-> event_name;` - EventTrigger(Expr), + /// `-> ev;` and the non-blocking `->> ev;` (IEEE 1800 §15.5.2), which may + /// carry a delay or event control of its own: `->> #5 ev;`, + /// `->> @(posedge clk) ev;`. + /// + /// Boxed because the timing control is the size of a whole sensitivity + /// list and this is one of the smallest statements there is; see + /// `ast::size_pins`. + EventTrigger(Box), VarDecl(DataDecl), + /// A block-scoped `let` (IEEE 1800 §11.13): `let sum = a + b;` written + /// among a `begin`/`end`'s declarations. Same grammar and same layout as + /// the item-level one, so it carries the item's node; boxed because a + /// `let` is rare and its node is wider than the statement kinds that are + /// not (see `ast::size_pins`). + Let(Box), + /// `randsequence (main) … endsequence` (IEEE 1800 §18.17) — a production + /// grammar of its own, modelled in `ast::randsequence`. Boxed: a + /// production list is wide and a `randsequence` is rare. + RandSequence(Box), ParamDecl(ParamDecl), /// Old-style task/function port declaration: `input [7:0] a;` PortDecl(PortDecl), @@ -341,6 +357,27 @@ impl StmtKind { } } +/// An event trigger: `-> ev;` or the non-blocking `->> ev;`. +/// +/// Only the non-blocking spelling may write a delay or an event control +/// between the arrow and the event (IEEE 1800 §15.5.2), but the node carries +/// one either way — lucisv reproduces what was written and is not a legality +/// checker. +#[derive(Debug)] +pub struct EventTrigger { + /// `->` or `->>`, as written. + pub arrow: String, + /// Comments written between the arrow and whatever follows it + /// (`->> /*c*/ #5 ev;`). + pub after_arrow: Vec, + /// The `#5` or `@(posedge clk)` of `->> #5 ev;`. + pub timing: Option, + /// Comments written between that timing control and the event name. + /// Empty when no timing control was written. + pub before_event: Vec, + pub expr: Expr, +} + #[derive(Debug)] pub enum TimingControl { /// `#expr` diff --git a/crates/vlog_parser/src/lexer.rs b/crates/vlog_parser/src/lexer.rs index 0447aed..b672d8f 100644 --- a/crates/vlog_parser/src/lexer.rs +++ b/crates/vlog_parser/src/lexer.rs @@ -52,9 +52,9 @@ struct RawLexer<'a> { /// Multi-character operators, longest first so greedy matching works. const OPERATORS: &[&str] = &[ - "<<<=", ">>>=", "===", "!==", "==?", "!=?", "<<<", ">>>", "<<=", ">>=", "<->", "**", "==", - "!=", "<=", ">=", "&&", "||", "<<", ">>", "->", "=>", "::", "+:", "-:", "+=", "-=", "*=", "/=", - "%=", "&=", "|=", "^=", "++", "--", "~&", "~|", "~^", "^~", "##", "'{", + "<<<=", ">>>=", "===", "!==", "==?", "!=?", "<<<", ">>>", "<<=", ">>=", "<->", "->>", "**", + "==", "!=", "<=", ">=", "&&", "||", "<<", ">>", "->", "=>", "::", "+:", "-:", "+=", "-=", "*=", + "/=", "%=", "&=", "|=", "^=", "++", "--", "~&", "~|", "~^", "^~", "##", "'{", ]; const SINGLE_OPS: &[u8] = b"+-*/%&|^~!<>=?:;,.#@()[]{}'$"; diff --git a/crates/vlog_parser/src/parser/decl.rs b/crates/vlog_parser/src/parser/decl.rs index 6820e60..8bc8e25 100644 --- a/crates/vlog_parser/src/parser/decl.rs +++ b/crates/vlog_parser/src/parser/decl.rs @@ -260,6 +260,10 @@ impl<'a> Parser<'a> { break; } } + // `wire (strong0, weak1) w = a;` — IEEE 1800 §6.6 writes the strength + // directly after the net keyword and nowhere else, so a `(` here is + // only read as one when a net keyword was actually written. + let strength = if net.is_some() { self.parse_opt_drive_strength()? } else { None }; let before = self.parse_net_delay(net.is_some(), false)?; // A declaration reaches here with its `virtual` already in // `qualifiers`, so `parse_opt_data_type`'s own modport branch cannot @@ -285,7 +289,7 @@ impl<'a> Parser<'a> { }; let declarators = self.parse_declarators()?; self.expect_sym(";")?; - Ok(DataDecl { net, delay, qualifiers, ty, declarators }) + Ok(DataDecl { net, strength, delay, qualifiers, ty, declarators }) } /// The net delay at the cursor, if one is written there: `#5`, `#0.1`, diff --git a/crates/vlog_parser/src/parser/expr.rs b/crates/vlog_parser/src/parser/expr.rs index e6dbc29..a8b48a6 100644 --- a/crates/vlog_parser/src/parser/expr.rs +++ b/crates/vlog_parser/src/parser/expr.rs @@ -265,14 +265,16 @@ impl<'a> Parser<'a> { || (t.is_sym("'{") && self.is_cast_base(base)) || t.is_sym("++") || t.is_sym("--") - // `with ( ... )` (an array method's iterator argument) and - // `with { ... }` (a `randomize` constraint block) are the two - // 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. + // `with ( ... )` (an array method's iterator argument), + // `with { ... }` (a `randomize` constraint block) and + // `with [ ... ]` (a stream expression's array range, + // IEEE 1800 §11.4.14) are the three postfix spellings of `with`; + // the delimiter after the keyword is what tells them apart. || (t.is_kw("with") && !self.no_with - && (self.nth(1).is_sym("(") || self.nth(1).is_sym("{"))) + && (self.nth(1).is_sym("(") + || self.nth(1).is_sym("{") + || self.nth(1).is_sym("["))) } /// True when the `[` at the cursor opens a transition or consecutive @@ -363,6 +365,35 @@ impl<'a> Parser<'a> { )) } + /// The `[ … ]` of a stream expression's `with` (IEEE 1800 §11.4.14), the + /// `with` already consumed: one index or a range in any of the three + /// spellings a part select takes. + /// + /// `with_comments` arrives holding what was written in front of the + /// keyword; the gap after it is that same node's `after_kw`, so the two + /// halves of `a /*x*/ with /*y*/ [i]` keep their own sides of the word and + /// the printer lays the head out through the one function all three + /// postfix `with` forms share. + fn parse_stream_range(&mut self, mut with_comments: WithComments) -> PResult { + with_comments.after_kw = self.take_before_open("["); + let mut comments = SegmentComments::default(); + self.expect_sym("[")?; + comments.after_open = self.take_gap(); + let msb = self.parse_expr()?; + let t = self.cur(); + let (op, lsb) = if t.is_sym(":") || t.is_sym("+:") || t.is_sym("-:") { + comments.before_op = self.take_gap(); + let op = self.bump().text; + comments.after_op = self.take_gap(); + (Some(op), Some(self.parse_expr()?)) + } else { + (None, None) + }; + comments.before_close = self.gap_before("]"); + self.expect_sym("]")?; + Ok(StreamRange { with_comments, msb, op, lsb, comments }) + } + fn parse_postfix_inner(&mut self) -> PResult { let mut expr = self.parse_primary()?; while self.at_postfix_segment(&expr) { @@ -430,6 +461,13 @@ impl<'a> Parser<'a> { comments: Box::new(comments), }, ); + } else if self.nth(1).is_sym("[") { + self.bump(); // with + let range = self.parse_stream_range(comments)?; + expr = self.expr_at( + start, + ExprKind::StreamWith { base: Box::new(expr), range: Box::new(range) }, + ); } else { self.bump(); // with comments.after_kw = self.take_before_open("("); diff --git a/crates/vlog_parser/src/parser/instance.rs b/crates/vlog_parser/src/parser/instance.rs index adba783..613ec62 100644 --- a/crates/vlog_parser/src/parser/instance.rs +++ b/crates/vlog_parser/src/parser/instance.rs @@ -76,22 +76,32 @@ impl<'a> Parser<'a> { /// strength when a strength keyword follows it, so a parenthesized /// left-hand side — and a gate whose first argument is an expression — is /// untouched. - fn parse_opt_drive_strength(&mut self) -> PResult> { + pub(super) fn parse_opt_drive_strength(&mut self) -> PResult> { if !self.cur().is_sym("(") || !is_drive_strength(self.nth(1)) { return Ok(None); } + let mut comments = + Box::new(DriveStrengthComments { before_open: self.take_gap(), ..Default::default() }); self.bump(); // ( + comments.after_open = self.take_gap(); let first = self.bump().text; + // The gap after the first strength ends either at the `,` or at the + // `)`, and it is that token which says which slot it belongs in. + let gap = self.take_gap(); if self.eat_sym(")") { - return Ok(Some(DriveStrength { first, second: None })); + comments.before_close = gap; + return Ok(Some(DriveStrength { first, second: None, comments })); } + comments.before_comma = gap; self.expect_sym(",")?; + comments.after_comma = self.take_gap(); if !is_drive_strength(self.cur()) { return self.error("expected a drive strength"); } let second = Some(self.bump().text); + comments.before_close = self.gap_before(")"); self.expect_sym(")")?; - Ok(Some(DriveStrength { first, second })) + Ok(Some(DriveStrength { first, second, comments })) } /// The value after a `#`: a bare primary, or a parenthesized delay — diff --git a/crates/vlog_parser/src/parser/keyword_stmt.rs b/crates/vlog_parser/src/parser/keyword_stmt.rs index 6a85059..71037c5 100644 --- a/crates/vlog_parser/src/parser/keyword_stmt.rs +++ b/crates/vlog_parser/src/parser/keyword_stmt.rs @@ -238,6 +238,13 @@ impl<'a> Parser<'a> { // A package import standing among a block's declarations // (IEEE 1800 §13.4.2): the same statement the item level takes. "import" => Ok(StmtKind::Import(self.parse_import_list()?)), + // A block-scoped `let` (IEEE 1800 §11.13). `parse_let` reads the + // `;` itself, which is why `takes_semi()` says this kind takes + // none — exactly as the item-level spelling works. + "let" => Ok(StmtKind::Let(Box::new(self.parse_let()?))), + // `randsequence` reads its own `endsequence`, so like a block it + // takes no `;` of its own (`takes_semi()` says so). + "randsequence" => Ok(StmtKind::RandSequence(Box::new(self.parse_randsequence()?))), // A block-scoped type (IEEE 1800 §6.18), e.g. // `spi_host/dv/env/seq_lib/spi_host_base_vseq.sv:577`. Same // grammar and same layout as the item-level `typedef`. diff --git a/crates/vlog_parser/src/parser/mod.rs b/crates/vlog_parser/src/parser/mod.rs index d0ef87b..2d77e25 100644 --- a/crates/vlog_parser/src/parser/mod.rs +++ b/crates/vlog_parser/src/parser/mod.rs @@ -37,6 +37,7 @@ //! | `expr`, `primary` | the operator grammar; its leaves and argument lists | //! | `class`, `covergroup` | classes with their constraints; covergroups | //! | `assertion`, `sva` | concurrent assertions and SVA declarations; the property grammar | +//! | `randsequence` | the `randsequence` production grammar (IEEE 1800 §18.17) | //! | `directive` | `` `ifdef `` tracking, list directives, macros, fragment mode | //! | `split` | conditional-directive split recovery | //! | `verbatim` | vendor/formal blocks kept as bytes, and the capture helpers | @@ -59,6 +60,7 @@ mod item; mod keyword_stmt; mod module; mod primary; +mod randsequence; mod recover; mod recover_list; mod split; diff --git a/crates/vlog_parser/src/parser/module.rs b/crates/vlog_parser/src/parser/module.rs index 92b00ff..724bf8b 100644 --- a/crates/vlog_parser/src/parser/module.rs +++ b/crates/vlog_parser/src/parser/module.rs @@ -217,15 +217,21 @@ impl<'a> Parser<'a> { /// `default` keyword, when written, has already been consumed. pub(super) fn parse_clocking(&mut self, is_default: bool) -> PResult { self.expect_kw("clocking")?; + let after_kw = self.take_gap(); let name = if self.cur().kind == TokenKind::Ident { Some(self.expect_name()?) } else { None }; + let before_event = if self.cur().is_sym("@") { self.take_gap() } else { Vec::new() }; // `default clocking cb;` selects an existing block and has no body. let event = if self.eat_sym("@") { Some(self.parse_sens_list()?) } else { None }; + let before_semi = self.gap_before(";"); self.expect_sym(";")?; if event.is_none() { return Ok(ClockingDecl { is_default, + after_kw, name, + before_event, + before_semi, event, items: Vec::new(), dangling: Vec::new(), @@ -245,7 +251,10 @@ impl<'a> Parser<'a> { let (end_label, end_label_span) = split_label(end_name); Ok(ClockingDecl { is_default, + after_kw, name, + before_event, + before_semi, event, items, dangling, @@ -262,9 +271,8 @@ impl<'a> Parser<'a> { let start = self.here(); let mut meta = self.take_meta(); let kind = if self.eat_kw("default") { - let input = if self.eat_kw("input") { Some(self.parse_clocking_skew()?) } else { None }; - let output = - if self.eat_kw("output") { Some(self.parse_clocking_skew()?) } else { None }; + let input = self.parse_clocking_default("input")?; + let output = self.parse_clocking_default("output")?; if input.is_none() && output.is_none() { return self.error("expected `input` or `output` after `default`"); } @@ -275,20 +283,28 @@ impl<'a> Parser<'a> { return self.error("expected a clocking item"); } let dir = self.bump().text; - let skew = - if self.at_clocking_skew() { Some(self.parse_clocking_skew()?) } else { None }; + let after_dir = self.take_gap(); + let mut after_skew = Vec::new(); + let skew = if self.at_clocking_skew() { + let skew = self.parse_clocking_skew()?; + after_skew = self.take_gap(); + Some(skew) + } else { + None + }; let mut signals = vec![self.parse_clocking_signal()?]; while self.eat_sym(",") { signals.push(self.parse_clocking_signal()?); } - ClockingItemKind::Signals { dir, skew, signals } + ClockingItemKind::Signals { dir, after_dir, skew, after_skew, signals } }; let span = self.span_from(start); + let before_semi = self.gap_before(";"); self.expect_sym(";")?; if meta.trailing.is_none() { meta.trailing = self.take_trailing(); } - Ok(ClockingItem { meta, kind, span }) + Ok(ClockingItem { meta, kind, before_semi, span }) } /// One `signal [= expression]` of a clocking direction group — IEEE 1800 @@ -301,6 +317,21 @@ impl<'a> Parser<'a> { Ok(ClockingSignal { name, value }) } + /// One half of a `default input #1step output #0;` item: the direction + /// keyword `dir` and its skew, or `None` when this half was not written. + /// + /// The gap in front of the keyword is the half's own, so the two halves + /// keep their own sides of the word that separates them. + fn parse_clocking_default(&mut self, dir: &str) -> PResult> { + if !self.cur().is_kw(dir) { + return Ok(None); + } + let before_dir = self.take_gap(); + self.bump(); + let after_dir = self.take_gap(); + Ok(Some(ClockingDefault { before_dir, after_dir, skew: self.parse_clocking_skew()? })) + } + /// True when the cursor is on a clocking skew rather than on the first /// signal name: `#2`, `#1step`, `posedge`, `negedge`, `edge`. fn at_clocking_skew(&self) -> bool { @@ -308,25 +339,47 @@ impl<'a> Parser<'a> { t.is_sym("#") || t.is_kw("posedge") || t.is_kw("negedge") || t.is_kw("edge") } - /// A clocking skew, as written: `#2`, `#1step`, `negedge`. Kept as text — - /// it is a delay or an edge, never something lucisv re-lays out — so the - /// printer writes back exactly what the source said. The `#(min:typ:max)` - /// spelling is not supported; see the feature README's Assumptions. - fn parse_clocking_skew(&mut self) -> PResult { - if self.eat_sym("#") { - let t = self.cur(); - if !matches!(t.kind, TokenKind::Number | TokenKind::Ident) { - return self.error("expected a clocking skew delay"); - } - return Ok(format!("#{}", self.bump().text)); + /// A clocking skew, as written: `#2`, `#1step`, the parenthesized + /// `#(1:2:3)`, an edge identifier, or — IEEE 1800 §14.3's first + /// alternative — an edge identifier with a delay behind it + /// (`negedge #(1:2:3)`). + fn parse_clocking_skew(&mut self) -> PResult { + if self.cur().is_sym("#") { + return Ok(ClockingSkew::Delay(self.parse_clocking_delay()?)); } let t = self.cur(); if t.is_kw("posedge") || t.is_kw("negedge") || t.is_kw("edge") { - return Ok(self.bump().text); + let word = self.bump().text; + // Only a gap that really is in front of a `#` is the edge's own; + // otherwise it belongs to the caller's slot before the name. + let after_edge = self.gap_before("#"); + let delay = + if self.cur().is_sym("#") { Some(self.parse_clocking_delay()?) } else { None }; + return Ok(ClockingSkew::Edge { word, after_edge, delay }); } self.error("expected a clocking skew") } + /// The `# …` half of a clocking skew. + /// + /// The one-token spellings are kept as text — a delay is never something + /// lucisv re-lays out — so the printer writes back exactly what the source + /// said. The parenthesized one goes through the delay-value grammar every + /// other `#( … )` uses, which is what gives its `:` and its parens their + /// comment slots. + fn parse_clocking_delay(&mut self) -> PResult { + self.expect_sym("#")?; + let after_hash = self.take_gap(); + if self.cur().is_sym("(") { + return Ok(ClockingDelay::Paren { after_hash, expr: self.parse_delay_value()? }); + } + let t = self.cur(); + if !matches!(t.kind, TokenKind::Number | TokenKind::Ident) { + return self.error("expected a clocking skew delay"); + } + Ok(ClockingDelay::Word { after_hash, word: self.bump().text }) + } + /// A `#( parameter ... )` port list, shared by module and class headers. /// `ports` is `None` when no `#(` was written at the cursor at all. pub(super) fn parse_param_port_list(&mut self) -> PResult { diff --git a/crates/vlog_parser/src/parser/primary.rs b/crates/vlog_parser/src/parser/primary.rs index 48cc82d..c3432d1 100644 --- a/crates/vlog_parser/src/parser/primary.rs +++ b/crates/vlog_parser/src/parser/primary.rs @@ -146,20 +146,25 @@ impl<'a> Parser<'a> { /// its `<<` or `>>`: IEEE 1800 §11.4.14 /// `{ (<<|>>) [slice_size] { stream_expression {, stream_expression} } }`. /// - /// The `with [range]` form of a stream expression is not supported; a - /// file using it keeps its old "expected expression" error. + /// A stream expression's `with [range]` is read by `parse_postfix_inner`, + /// as the postfix segment it is; the elements here are ordinary + /// expressions either way. fn parse_stream_concat(&mut self, start: u32) -> PResult { + let mut comments = + Box::new(StreamComments { after_open: self.take_gap(), ..Default::default() }); let dir = self.bump().text; // The slice size is optional and is a constant expression or a type // (`{<< byte {x}}`); a `{` here means it was omitted. let slice = if self.cur().is_sym("{") { None } else { Some(Box::new(self.parse_expr_or_type()?)) }; + comments.before_inner = self.take_before_open("{"); self.expect_sym("{")?; let first = self.parse_expr_item()?; let inner = self.parse_expr_list(first, "}")?; self.expect_sym("}")?; + comments.before_close = self.gap_before("}"); self.expect_sym("}")?; - Ok(self.expr_at(start, ExprKind::Stream { dir, slice, inner })) + Ok(self.expr_at(start, ExprKind::Stream { dir, slice, inner, comments })) } /// True when `e` may stand left of a cast's `'` — the `constant_primary` @@ -180,6 +185,14 @@ impl<'a> Parser<'a> { | ExprKind::Scope { .. } | ExprKind::Member { .. } | ExprKind::Paren { .. } => true, + // A data type with dimensions on it — `logic [3:0]'(x)`, + // `bit signed [7:0]'(y)`. A bare `int'(x)` never reaches here + // (`parse_primary` takes the keyword-and-tick shape itself); this + // is the spelling whose `[3:0]` sent it down `parse_type_expr` + // instead. IEEE 1800 §6.24.1's `casting_type` names only + // `simple_type`, but every tool in use accepts the packed + // dimensions and lucisv is not a legality checker. + ExprKind::Type(_) => true, ExprKind::Call { callee, .. } => { matches!(&callee.kind, ExprKind::Ident(n) if n.starts_with('$')) } diff --git a/crates/vlog_parser/src/parser/randsequence.rs b/crates/vlog_parser/src/parser/randsequence.rs new file mode 100644 index 0000000..5ef2139 --- /dev/null +++ b/crates/vlog_parser/src/parser/randsequence.rs @@ -0,0 +1,316 @@ +//! `randsequence` — the production grammar of IEEE 1800 §18.17. +//! +//! One file for one sub-grammar, the way the SVA and covergroup grammars each +//! have their own: a `randsequence` body is a production list, not a +//! statement list, and nothing outside it reads these productions. +//! +//! The nesting between an alternative's items and the control shapes that +//! wrap them is real recursion, so `parse_prod_item` brackets itself with +//! [`Parser::enter`] / [`Parser::leave`] the way every other recursive +//! production does. + +use super::*; + +impl<'a> Parser<'a> { + /// `randsequence ( [name] ) production { production } endsequence` + /// (IEEE 1800 §18.17), the cursor on the keyword. + pub(super) fn parse_randsequence(&mut self) -> PResult { + self.expect_kw("randsequence")?; + let after_kw = self.take_before_open("("); + self.expect_sym("(")?; + let after_open = self.take_gap(); + let start = + if self.cur().kind == TokenKind::Ident { Some(self.expect_name()?) } else { None }; + let before_close = self.gap_before(")"); + self.expect_sym(")")?; + let mut productions = Vec::new(); + while !self.at_body_end("endsequence") { + productions.push(self.parse_production()?); + } + let dangling = self.take_dangling(); + self.expect_closer("endsequence")?; + Ok(RandSequence { after_kw, after_open, start, before_close, productions, dangling }) + } + + /// One production: `[data_type] name [( ports )] : alternatives ;`. + /// + /// The optional return type is told from the name by what follows the + /// identifier: a production's name is the last identifier before the `(`, + /// the `:` or another identifier, so a second identifier means the first + /// one was the type. + fn parse_production(&mut self) -> PResult { + let start = self.here(); + let mut meta = self.take_meta(); + let ret_type = self.parse_opt_production_type()?; + let Name { text: name, span: name_span } = self.expect_name()?; + let has_parens = self.cur().is_sym("("); + let args = self.parse_tf_ports(false)?.args; + let before_colon = self.gap_before(":"); + self.expect_sym(":")?; + let mut alternatives = vec![self.parse_alternative(Vec::new())?]; + while self.cur().is_sym("|") { + // The gap in front of the `|` belongs to the alternative it opens, + // so it prints on the bar's own side of the previous one. + let before_bar = self.take_gap(); + self.bump(); + alternatives.push(self.parse_alternative(before_bar)?); + } + let span = self.span_from(start); + let before_semi = self.gap_before(";"); + self.expect_sym(";")?; + if meta.trailing.is_none() { + meta.trailing = self.take_trailing(); + } + Ok(Production { + meta, + ret_type, + name, + name_span, + has_parens, + args, + before_colon, + alternatives, + before_semi, + span, + }) + } + + /// The production's return type, when it wrote one. `void` is a keyword + /// rather than an identifier, so it is read here too and kept as the type + /// name it is written as. + fn parse_opt_production_type(&mut self) -> PResult> { + let t = self.cur(); + let typed = if t.is_kw("void") { + true + } else if t.kind == TokenKind::Keyword { + // `int name : …`, `bit [3:0] name : …` — a type keyword can only + // be the type, never the production's own name. + TYPE_KEYWORDS.contains(&t.text.as_str()) + } else { + // Two identifiers in a row: the first is a user-defined type. + t.kind == TokenKind::Ident && self.nth(1).kind == TokenKind::Ident + }; + if !typed { + return Ok(None); + } + Ok(Some(self.parse_opt_data_type()?)) + } + + /// One `|`-separated right-hand side, with its optional `:= weight`. + fn parse_alternative(&mut self, before_bar: Vec) -> PResult { + let after_bar = self.take_gap(); + let mut items = vec![self.parse_prod_item()?]; + while self.at_prod_item() { + items.push(self.parse_prod_item()?); + } + let mut before_weight = Vec::new(); + let mut weight = None; + if self.at_weight_op() { + before_weight = self.take_gap(); + self.bump(); // : + self.bump(); // = + weight = Some(self.parse_weight()?); + } + Ok(Alternative { before_bar, after_bar, items, before_weight, weight }) + } + + /// True when the cursor is on the `:=` of a weight. The lexer has no `:=` + /// token — it is a `:` and an `=` written adjacently, the same two tokens + /// a `dist` weight is read from — so adjacency is checked by span and + /// `a : = 5` written with a space is not one. + fn at_weight_op(&self) -> bool { + self.cur().is_sym(":") + && self.nth(1).is_sym("=") + && self.nth(1).span.start == self.cur().span.end + } + + /// The `:= expr [ { code } ]` of a weighted alternative (§18.17.2). + /// + /// §18.17.2's `weight_specification` is a number, a scoped name or a + /// *parenthesized* expression — never a bare operator expression — and + /// that is what keeps `a := 3 | b := 2` readable: an unparenthesized `|` + /// separates the alternatives, it does not or two weights together. So + /// the weight is read as a postfix expression and stops there. + fn parse_weight(&mut self) -> PResult { + let after_op = self.take_gap(); + let expr = self.parse_postfix()?; + let block = + if self.cur().is_sym("{") { Some(Box::new(self.parse_rs_code_block()?)) } else { None }; + Ok(Weight { after_op, expr, block }) + } + + /// True when the cursor opens another item of the alternative rather than + /// ending it. An alternative ends at `|`, `:=`, `;`, or the `}` / `endcase` + /// of whatever encloses it. + fn at_prod_item(&self) -> bool { + let t = self.cur(); + t.kind == TokenKind::Ident + || t.is_sym("{") + || t.is_kw("if") + || t.is_kw("repeat") + || t.is_kw("case") + || t.is_kw("rand") + } + + /// One `rs_prod`: a production reference, a code block, or one of the four + /// control shapes. + fn parse_prod_item(&mut self) -> PResult { + self.enter()?; + let item = self.parse_prod_item_inner(); + self.leave(); + item + } + + fn parse_prod_item_inner(&mut self) -> PResult { + let t = self.cur(); + if t.is_sym("{") { + return Ok(ProdItem::Block(Box::new(self.parse_rs_code_block()?))); + } + if t.is_kw("if") { + return self.parse_rs_if(); + } + if t.is_kw("repeat") { + self.bump(); + let after_kw = self.take_before_open("("); + self.expect_sym("(")?; + let count = self.parse_expr()?; + self.expect_sym(")")?; + let body = Box::new(self.parse_prod_item()?); + return Ok(ProdItem::Repeat { after_kw, count, body }); + } + if t.is_kw("case") { + return self.parse_rs_case(); + } + if t.is_kw("rand") { + return self.parse_rand_join(); + } + Ok(ProdItem::Ref(self.parse_prod_ref()?)) + } + + /// `if ( expr ) item [ else item ]` — the arms are production items, not + /// statements, so this is not `parse_if_stmt`. + fn parse_rs_if(&mut self) -> PResult { + self.expect_kw("if")?; + let after_kw = self.take_before_open("("); + self.expect_sym("(")?; + let cond = self.parse_expr()?; + self.expect_sym(")")?; + let then = Box::new(self.parse_prod_item()?); + // Whatever was written in the gap before `else` stays on the + // keyword's left, as an `if` statement's does. + let mut before_else = Vec::new(); + if self.cur().is_kw("else") { + before_else = self.take_dangling(); + } + let (after_else, els) = if self.eat_kw("else") { + (self.take_gap(), Some(Box::new(self.parse_prod_item()?))) + } else { + (Vec::new(), None) + }; + Ok(ProdItem::If { after_kw, cond, then, before_else, after_else, els }) + } + + /// `case ( expr ) arm { arm } endcase`, whose arms take production items. + fn parse_rs_case(&mut self) -> PResult { + self.expect_kw("case")?; + let after_kw = self.take_before_open("("); + self.expect_sym("(")?; + let expr = self.parse_expr()?; + self.expect_sym(")")?; + let mut items = Vec::new(); + while !self.at_body_end("endcase") { + items.push(self.parse_rs_case_item()?); + } + let dangling = self.take_dangling(); + self.expect_closer("endcase")?; + Ok(ProdItem::Case { after_kw, expr, items, dangling }) + } + + /// One arm: `expr {, expr} : item ;` or `default [:] item ;`. + fn parse_rs_case_item(&mut self) -> PResult { + let start = self.here(); + let mut meta = self.take_meta(); + let mut labels = Vec::new(); + let is_default = self.eat_kw("default"); + if !is_default { + let first = self.parse_expr_item()?; + labels = self.parse_expr_list(first, ":")?; + } + let before_colon = self.gap_before(":"); + // A `default` arm may write no `:` at all (§18.17.4). + let has_colon = self.cur().is_sym(":"); + if has_colon { + self.bump(); + } else if !is_default { + return self.error("expected `:` in a randsequence case arm"); + } + let after_colon = self.take_gap(); + let item = self.parse_prod_item()?; + let span = self.span_from(start); + let before_semi = self.gap_before(";"); + self.expect_sym(";")?; + if meta.trailing.is_none() { + meta.trailing = self.take_trailing(); + } + Ok(ProdCaseItem { + meta, + labels, + is_default, + before_colon, + after_colon, + item, + before_semi, + span, + }) + } + + /// `rand join [ ( expr ) ] item item { item }` (§18.17.6): the items are + /// interleaved rather than run in order, and there are at least two. + fn parse_rand_join(&mut self) -> PResult { + self.expect_kw("rand")?; + let after_rand = self.take_gap(); + self.expect_kw("join")?; + let weight = if self.cur().is_sym("(") { + self.bump(); + let e = self.parse_expr()?; + self.expect_sym(")")?; + Some(e) + } else { + None + }; + let mut items = vec![self.parse_prod_item()?]; + while self.at_prod_item() { + items.push(self.parse_prod_item()?); + } + Ok(ProdItem::RandJoin { after_rand, weight, items }) + } + + /// A production reference: `name` or `name(a, b)`. + fn parse_prod_ref(&mut self) -> PResult { + let Name { text: name, span: name_span } = self.expect_name()?; + let before_args = self.take_before_open("("); + let has_parens = self.cur().is_sym("("); + let mut args = Vec::new(); + if has_parens { + self.bump(); + if !self.cur().is_sym(")") { + let first = self.parse_expr_item()?; + args = self.parse_expr_list(first, ")")?; + } + self.expect_sym(")")?; + } + Ok(ProdRef { name, name_span, has_parens, before_args, args }) + } + + /// An `rs_code_block`: `{ … }` around ordinary statements. + fn parse_rs_code_block(&mut self) -> PResult { + self.expect_sym("{")?; + let mut stmts = Vec::new(); + while !self.cur().is_sym("}") && !self.at_eof() { + stmts.push(self.stmt_or_recover()?); + } + let dangling = self.take_dangling(); + self.expect_sym("}")?; + Ok(CodeBlock { stmts, dangling }) + } +} diff --git a/crates/vlog_parser/src/parser/stmt.rs b/crates/vlog_parser/src/parser/stmt.rs index 43ad224..71eb420 100644 --- a/crates/vlog_parser/src/parser/stmt.rs +++ b/crates/vlog_parser/src/parser/stmt.rs @@ -144,11 +144,8 @@ impl<'a> Parser<'a> { let stmt = if self.eat_stmt_semi() { None } else { Some(Box::new(self.parse_stmt()?)) }; return Ok(StmtKind::Timing { control: TimingControl::Event(sens), stmt }); } - if t.is_sym("->") { - self.bump(); - let e = self.parse_unary()?; - self.expect_stmt_semi()?; - return Ok(StmtKind::EventTrigger(e)); + if t.is_sym("->") || t.is_sym("->>") { + return self.parse_event_trigger(); } if t.kind == TokenKind::Keyword { return self.parse_keyword_stmt(); @@ -157,6 +154,42 @@ impl<'a> Parser<'a> { self.parse_assign_or_expr_stmt() } + /// `-> ev;` and `->> [delay_or_event_control] ev;` (IEEE 1800 §15.5.2). + /// + /// The arrow is kept as written: `->` and `->>` are different statements + /// (blocking and non-blocking), so rewriting one as the other would + /// change the design. Only `->>` may carry the timing control, but it is + /// read for both spellings — the parser reproduces what stands there and + /// leaves legality to the tools that check it. + fn parse_event_trigger(&mut self) -> PResult { + let arrow = self.bump().text; + let after_arrow = self.take_gap(); + let timing = self.parse_opt_timing_control()?; + let before_event = if timing.is_some() { self.take_gap() } else { Vec::new() }; + let expr = self.parse_unary()?; + self.expect_stmt_semi()?; + Ok(StmtKind::EventTrigger(Box::new(EventTrigger { + arrow, + after_arrow, + timing, + before_event, + expr, + }))) + } + + /// The `#delay` or `@(event)` written at the cursor, if one is. + fn parse_opt_timing_control(&mut self) -> PResult> { + if self.eat_sym("#") { + let after_hash = self.take_gap(); + let expr = self.parse_delay_value()?; + return Ok(Some(TimingControl::Delay { after_hash, expr })); + } + if self.eat_sym("@") { + return Ok(Some(TimingControl::Event(self.parse_sens_list()?))); + } + Ok(None) + } + pub(super) fn parse_if_stmt(&mut self, qualifier: Option) -> PResult { self.expect_kw("if")?; let after_kw = self.take_before_open("("); diff --git a/crates/vlog_parser/src/parser/tests/expr.rs b/crates/vlog_parser/src/parser/tests/expr.rs index a82cd61..937df50 100644 --- a/crates/vlog_parser/src/parser/tests/expr.rs +++ b/crates/vlog_parser/src/parser/tests/expr.rs @@ -226,13 +226,17 @@ fn only_a_brace_after_the_first_element_makes_an_assignment_pattern_a_replicatio fn a_streaming_concatenation_keeps_its_direction_and_optional_slice_size() { // corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_sha2_pkg.sv:123. with_assign_rhs("module m;\n assign y = {<<8{v}};\nendmodule\n", |e| { - let ExprKind::Stream { dir, slice, inner } = &e.kind else { panic!("expected a stream") }; + let ExprKind::Stream { dir, slice, inner, .. } = &e.kind else { + panic!("expected a stream") + }; assert_eq!(dir, "<<"); assert!(matches!(slice.as_deref().map(|s| &s.kind), Some(ExprKind::Number(_)))); assert_eq!(inner.len(), 1); }); with_assign_rhs("module m;\n assign y = {>>{a, b}};\nendmodule\n", |e| { - let ExprKind::Stream { dir, slice, inner } = &e.kind else { panic!("expected a stream") }; + let ExprKind::Stream { dir, slice, inner, .. } = &e.kind else { + panic!("expected a stream") + }; assert_eq!(dir, ">>"); assert!(slice.is_none(), "no slice size was written"); assert_eq!(inner.len(), 2); @@ -287,10 +291,28 @@ fn an_argument_carries_its_own_comments_and_the_call_carries_none() { } #[test] -fn a_with_that_opens_neither_a_paren_nor_a_brace_is_not_a_postfix_segment() { - // The stream expression's `with [range]` is still unsupported, and - // still fails where it always did rather than being mis-read. - assert!(parse_err("module m;\n initial x = {<<{a with [0:1]}};\nendmodule\n").contains("with")); +fn a_with_that_opens_a_bracket_is_a_stream_range() { + // The third postfix spelling of `with` (TODO §54.1): `[` after the + // keyword is a stream expression's array range, not an array method's + // iterator argument and not a `randomize` constraint block. + let f = parse_ok("module m;\n initial x = {<<{a with [0:1]}};\nendmodule\n"); + let ItemKind::Initial(stmt) = &module_of(&f).items[0].kind else { + panic!("expected an initial block") + }; + let StmtKind::Assign { rhs, .. } = &stmt.kind else { panic!("expected an assignment") }; + let ExprKind::Stream { inner, .. } = &rhs.kind else { panic!("expected a stream") }; + let ExprKind::StreamWith { range, .. } = &inner[0].expr.kind else { + panic!("expected a stream range, got {:?}", inner[0].expr.kind) + }; + assert_eq!(range.op.as_deref(), Some(":")); + assert!(range.lsb.is_some()); +} + +#[test] +fn a_with_that_opens_none_of_the_three_delimiters_is_not_a_postfix_segment() { + // A bare `with name` is no postfix segment at all, and still fails where + // it always did rather than being mis-read. + assert!(parse_err("module m;\n initial x = a with b;\nendmodule\n").contains("with")); } #[test] diff --git a/crates/vlog_parser/src/parser/tests/module.rs b/crates/vlog_parser/src/parser/tests/module.rs index 2c53ad1..99f30b6 100644 --- a/crates/vlog_parser/src/parser/tests/module.rs +++ b/crates/vlog_parser/src/parser/tests/module.rs @@ -338,18 +338,93 @@ fn a_clocking_block_parses_its_items() { assert_eq!(c.items.len(), 3); assert!(matches!( &c.items[0].kind, - ClockingItemKind::Default { input: Some(i), output: Some(o) } if i == "#2" && o == "#4" + ClockingItemKind::Default { + input: Some(ClockingDefault { + skew: ClockingSkew::Delay(ClockingDelay::Word { word: i, .. }), .. + }), + output: Some(ClockingDefault { + skew: ClockingSkew::Delay(ClockingDelay::Word { word: o, .. }), .. + }), + } if i == "2" && o == "4" )); assert!(matches!( &c.items[1].kind, - ClockingItemKind::Signals { dir, skew: None, signals } if dir == "input" && signals.len() == 2 + ClockingItemKind::Signals { dir, skew: None, signals, .. } + if dir == "input" && signals.len() == 2 )); assert!(matches!( &c.items[2].kind, - ClockingItemKind::Signals { dir, skew: Some(s), .. } if dir == "output" && s == "negedge" + ClockingItemKind::Signals { + dir, + skew: Some(ClockingSkew::Edge { word: s, delay: None, .. }), + .. + } if dir == "output" && s == "negedge" )); } +#[test] +fn a_clocking_skew_reads_a_delay_behind_its_edge() { + // IEEE 1800-2017 14.3: `clocking_skew ::= edge_identifier [ delay_control ] + // | delay_control`. The edge and the delay are one skew, not two. + let f = parse_ok( + "module m;\n clocking cb @(posedge clk);\n default input negedge #(1:2:3) output posedge #5;\n input posedge #1step a;\n input edge b;\n endclocking\nendmodule\n", + ); + let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; + let ItemKind::Clocking(c) = &m.items[0].kind else { panic!("expected a clocking block") }; + assert!(matches!( + &c.items[0].kind, + ClockingItemKind::Default { + input: Some(ClockingDefault { + skew: ClockingSkew::Edge { + word: i, + delay: Some(ClockingDelay::Paren { .. }), + .. + }, + .. + }), + output: Some(ClockingDefault { + skew: ClockingSkew::Edge { + word: o, + delay: Some(ClockingDelay::Word { word: d, .. }), + .. + }, + .. + }), + } if i == "negedge" && o == "posedge" && d == "5" + )); + assert!(matches!( + &c.items[1].kind, + ClockingItemKind::Signals { + skew: Some(ClockingSkew::Edge { delay: Some(ClockingDelay::Word { word, .. }), .. }), + .. + } if word == "1step" + )); + assert!(matches!( + &c.items[2].kind, + ClockingItemKind::Signals { skew: Some(ClockingSkew::Edge { word, delay: None, .. }), .. } + if word == "edge" + )); +} + +#[test] +fn an_edge_skews_delay_is_read_the_same_way_in_tolerant_mode() { + // Strict/tolerant parity: the shape is grammar, not recovery, so the + // tolerant parser reads it with no diagnostic of its own. + let src = "module m;\n clocking cb @(posedge clk);\n default input negedge #(1:2:3) output posedge #5;\n input edge /*c*/ #2 a;\n endclocking\nendmodule\n"; + let (f, diags) = parse_tolerant(tokenize(src).expect("lex error"), src); + assert!(diags.is_empty(), "tolerant mode recovered from a legal skew: {diags:?}"); + let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") }; + let ItemKind::Clocking(c) = &m.items[0].kind else { panic!("expected a clocking block") }; + let ClockingItemKind::Signals { + skew: Some(ClockingSkew::Edge { after_edge, delay, .. }), .. + } = &c.items[1].kind + else { + panic!("expected an edge skew with a delay") + }; + assert_eq!(texts(after_edge), ["/*c*/"], "the gap in front of the `#` is the edge's own"); + assert!(matches!(delay, Some(ClockingDelay::Word { word, .. }) if word == "2")); +} + #[test] fn a_default_clocking_may_be_anonymous_or_body_less() { // corpus/ibex/dv/formal/check/top.sv:143, and IEEE 1800-2017 14.12. diff --git a/crates/vlog_parser/src/parser/tf.rs b/crates/vlog_parser/src/parser/tf.rs index b72ea46..e9f857f 100644 --- a/crates/vlog_parser/src/parser/tf.rs +++ b/crates/vlog_parser/src/parser/tf.rs @@ -134,13 +134,27 @@ impl<'a> Parser<'a> { /// writes no parens at all, which is what `has_parens` records. pub(super) fn parse_let(&mut self) -> PResult { self.expect_kw("let")?; + let after_kw = self.take_gap(); let Name { text: name, span: name_span } = self.expect_name()?; let has_parens = self.cur().is_sym("("); let ports = self.parse_tf_ports(false)?.args; + let mut eq_comments = Box::new(BinaryComments::default()); + eq_comments.before = self.gap_before("="); self.expect_sym("=")?; + eq_comments.after = self.take_gap(); let value = self.parse_expr()?; + let before_semi = self.gap_before(";"); self.expect_sym(";")?; - Ok(LetDecl { name, name_span, has_parens, ports, value }) + Ok(LetDecl { + after_kw, + name, + name_span, + has_parens, + ports, + eq_comments, + value, + before_semi, + }) } /// The header a subroutine declaration and a `modport` method prototype diff --git a/crates/vlog_parser/src/token.rs b/crates/vlog_parser/src/token.rs index 9f790c3..4c8b203 100644 --- a/crates/vlog_parser/src/token.rs +++ b/crates/vlog_parser/src/token.rs @@ -257,6 +257,7 @@ keywords![ "pure", "extern", "rand", + "randsequence", "randc", "local", "protected", diff --git a/crates/vlog_parser/tests/spans.rs b/crates/vlog_parser/tests/spans.rs index 849949b..3d08bb4 100644 --- a/crates/vlog_parser/tests/spans.rs +++ b/crates/vlog_parser/tests/spans.rs @@ -980,9 +980,36 @@ fn check_stmt(src: &str, stmt: &Stmt, parent: TextRange) { check_stmt(src, s, here); } } - StmtKind::ExprStmt(e) | StmtKind::EventTrigger(e) => check_expr(src, e, here), + StmtKind::ExprStmt(e) => check_expr(src, e, here), + StmtKind::EventTrigger(t) => check_expr(src, &t.expr, here), StmtKind::VarDecl(d) => check_declarators(src, &d.declarators, here), StmtKind::Typedef(t) => check_typedef(src, t, here), + StmtKind::RandSequence(r) => { + for p in &r.productions { + assert_inside(src, "production", p.span, here); + check_name(src, "production name", &p.name, p.name_span, p.span); + check_list(src, "production port", &p.args, p.span, |a| { + assert_inside(src, "production port", a.span, p.span); + check_name(src, "production port name", &a.name, a.name_span, a.span); + }); + for alt in &p.alternatives { + for item in &alt.items { + check_prod_item(src, item, p.span); + } + if let Some(w) = &alt.weight { + check_expr(src, &w.expr, p.span); + } + } + } + } + StmtKind::Let(l) => { + check_name(src, "let name", &l.name, l.name_span, here); + check_list(src, "let port", &l.ports, here, |a| { + assert_inside(src, "let port", a.span, here); + check_name(src, "let port name", &a.name, a.name_span, a.span); + }); + check_expr(src, &l.value, here); + } StmtKind::ParamDecl(p) => check_declarators(src, &p.declarators, here), StmtKind::PortDecl(p) => check_declarators(src, &p.declarators, here), StmtKind::Return { expr, .. } => check_opt_expr(src, expr.as_ref(), here), @@ -1126,6 +1153,50 @@ fn check_match_items(src: &str, items: &[MatchItem], parent: TextRange) { } } +/// Every span a `randsequence` item and the items nested in it carry. +fn check_prod_item(src: &str, item: &ProdItem, parent: TextRange) { + match item { + ProdItem::Ref(r) => { + check_name(src, "production reference", &r.name, r.name_span, parent); + for a in &r.args { + check_expr(src, &a.expr, parent); + } + } + ProdItem::Block(b) => { + for s in &b.stmts { + check_stmt(src, s, parent); + } + } + ProdItem::If { cond, then, els, .. } => { + check_expr(src, cond, parent); + check_prod_item(src, then, parent); + if let Some(e) = els { + check_prod_item(src, e, parent); + } + } + ProdItem::Repeat { count, body, .. } => { + check_expr(src, count, parent); + check_prod_item(src, body, parent); + } + ProdItem::Case { expr, items, .. } => { + check_expr(src, expr, parent); + for arm in items { + assert_inside(src, "randsequence case arm", arm.span, parent); + for l in &arm.labels { + check_expr(src, &l.expr, arm.span); + } + check_prod_item(src, &arm.item, arm.span); + } + } + ProdItem::RandJoin { weight, items, .. } => { + check_opt_expr(src, weight.as_ref(), parent); + for i in items { + check_prod_item(src, i, parent); + } + } + } +} + fn check_opt_expr(src: &str, e: Option<&Expr>, parent: TextRange) { if let Some(e) = e { check_expr(src, e, parent); @@ -1148,6 +1219,11 @@ fn check_expr(src: &str, e: &Expr, parent: TextRange) { check_expr(src, base, here); check_expr(src, arg, here); } + ExprKind::StreamWith { base, range } => { + check_expr(src, base, here); + check_expr(src, &range.msb, here); + check_opt_expr(src, range.lsb.as_ref(), here); + } ExprKind::WithConstraint { base, block, .. } => { check_expr(src, base, here); match &**block { diff --git a/crates/vlog_refactor/src/extract/flow.rs b/crates/vlog_refactor/src/extract/flow.rs index ef1e0ed..00f823e 100644 --- a/crates/vlog_refactor/src/extract/flow.rs +++ b/crates/vlog_refactor/src/extract/flow.rs @@ -318,7 +318,7 @@ impl Marks { fn body(&mut self, stmt: &Stmt) { walk(stmt, &mut |stmt| match &stmt.kind { StmtKind::Assign { lhs, .. } | StmtKind::ForceRelease { lhs, .. } => self.write(lhs), - StmtKind::EventTrigger(expr) => self.write(expr), + StmtKind::EventTrigger(t) => self.write(&t.expr), StmtKind::For { init, step, .. } => { for entry in init { self.write(&entry.assign.lhs); @@ -543,7 +543,8 @@ fn stmt_exprs(stmt: &Stmt, f: &mut dyn FnMut(&Expr)) { } } StmtKind::Repeat { count, .. } => f(count), - StmtKind::ExprStmt(expr) | StmtKind::EventTrigger(expr) => f(expr), + StmtKind::ExprStmt(expr) => f(expr), + StmtKind::EventTrigger(t) => f(&t.expr), StmtKind::ForceRelease { lhs, rhs, .. } => { f(lhs); if let Some(rhs) = rhs { diff --git a/crates/vlog_semantic/src/bind/expr.rs b/crates/vlog_semantic/src/bind/expr.rs index 6635993..87a47cd 100644 --- a/crates/vlog_semantic/src/bind/expr.rs +++ b/crates/vlog_semantic/src/bind/expr.rs @@ -142,6 +142,15 @@ impl<'a> Binder<'a> { self.bind_expr(base, scope); self.bind_expr(arg, scope); } + // `a with [i +: n]` — the base and both range operands are + // ordinary uses, exactly as a part select's are. + ExprKind::StreamWith { base, range } => { + self.bind_expr(base, scope); + self.bind_expr(&range.msb, scope); + if let Some(lsb) = &range.lsb { + self.bind_expr(lsb, scope); + } + } ExprKind::WithConstraint { base, block, .. } => { self.bind_with_constraint(base, block, scope) } diff --git a/crates/vlog_semantic/src/bind/stmt.rs b/crates/vlog_semantic/src/bind/stmt.rs index 24a613b..820780b 100644 --- a/crates/vlog_semantic/src/bind/stmt.rs +++ b/crates/vlog_semantic/src/bind/stmt.rs @@ -11,6 +11,70 @@ use super::decl::param_kind; use super::{Binder, Target}; impl<'a> Binder<'a> { + /// Everything a `randsequence` writes that this crate has an opinion + /// about: each production's formals in a scope of its own, and every + /// expression and statement written inside its alternatives. + fn bind_rand_sequence(&mut self, r: &'a RandSequence, scope: ScopeId) { + for p in &r.productions { + if let Some(ty) = &p.ret_type { + self.bind_data_type(ty, scope); + } + let inner = self.new_scope(ScopeKind::Function, scope, p.span); + self.bind_tf_args(&p.args, inner); + for alt in &p.alternatives { + for item in &alt.items { + self.bind_prod_item(item, inner); + } + if let Some(w) = &alt.weight { + self.bind_expr(&w.expr, inner); + if let Some(b) = &w.block { + self.bind_stmts(&b.stmts, inner); + } + } + } + } + } + + /// One production item, and the items nested inside it. + fn bind_prod_item(&mut self, item: &'a ProdItem, scope: ScopeId) { + match item { + // The name is a production, which this crate does not declare; the + // arguments are ordinary expressions. + ProdItem::Ref(r) => { + for a in &r.args { + self.bind_expr(&a.expr, scope); + } + } + ProdItem::Block(b) => self.bind_stmts(&b.stmts, scope), + ProdItem::If { cond, then, els, .. } => { + self.bind_expr(cond, scope); + self.bind_prod_item(then, scope); + if let Some(e) = els { + self.bind_prod_item(e, scope); + } + } + ProdItem::Repeat { count, body, .. } => { + self.bind_expr(count, scope); + self.bind_prod_item(body, scope); + } + ProdItem::Case { expr, items, .. } => { + self.bind_expr(expr, scope); + for arm in items { + for l in &arm.labels { + self.bind_expr(&l.expr, scope); + } + self.bind_prod_item(&arm.item, scope); + } + } + ProdItem::RandJoin { weight, items, .. } => { + self.bind_opt_expr(weight.as_ref(), scope); + for i in items { + self.bind_prod_item(i, scope); + } + } + } + } + pub(super) fn bind_stmts(&mut self, stmts: &'a [Stmt], scope: ScopeId) { for s in stmts { self.bind_stmt(s, scope); @@ -133,12 +197,42 @@ impl<'a> Binder<'a> { self.bind_stmt(s, scope); } } - StmtKind::ExprStmt(e) | StmtKind::EventTrigger(e) => self.bind_expr(e, scope), + StmtKind::ExprStmt(e) => self.bind_expr(e, scope), + // `->> @(posedge clk) e;` reads `clk` as ordinarily as `#d e;` + // reads `d`, so the trigger's timing control goes through the same + // helper every other statement's does. + StmtKind::EventTrigger(t) => { + if let Some(timing) = &t.timing { + self.bind_timing(timing, scope); + } + self.bind_expr(&t.expr, scope); + } StmtKind::VarDecl(d) => self.bind_data_decl(d, scope), // A block-scoped type binds exactly as an item-level one does; the // scope it lands in is the enclosing block's, which is what // IEEE 1800 §6.18 asks for. StmtKind::Typedef(t) => self.bind_typedef(t, stmt.span, scope), + // A `randsequence` declares production names in a scope of its + // own that nothing outside it can reach (IEEE 1800 §18.17), which + // this crate does not model; what it does bind are the ordinary + // expressions and statements written inside — the arguments, the + // weights, and every code block's statements. + StmtKind::RandSequence(r) => self.bind_rand_sequence(r, scope), + // A block-scoped `let` binds exactly as an item-level one does: a + // compile-time function whose ports are visible only inside its + // own body expression. + StmtKind::Let(l) => { + let inner = self.declare_with_scope( + scope, + &l.name, + SymbolKind::Function, + l.name_span, + stmt.span, + ScopeKind::Function, + ); + self.bind_tf_args(&l.ports, inner); + self.bind_expr(&l.value, inner); + } StmtKind::ParamDecl(p) => { self.bind_declarators(&p.declarators, param_kind(&p.kw), &p.ty, scope) } diff --git a/crates/vlog_semantic/tests/semantics.rs b/crates/vlog_semantic/tests/semantics.rs index b0fcafd..5b853f6 100644 --- a/crates/vlog_semantic/tests/semantics.rs +++ b/crates/vlog_semantic/tests/semantics.rs @@ -878,3 +878,34 @@ endpackage assert_eq!(args, ["named"]); assert!(s.symbols().iter().all(|sym| !sym.name.is_empty()), "no symbol is nameless"); } + +#[test] +fn an_event_triggers_timing_control_is_bound_like_any_other() { + // TODO §54.1's `->>` may carry either half of a timing control, and both + // halves read signals: `#d` reads `d`, `@(posedge clk iff en)` reads `clk` + // and `en`. The bind arm hand-matched the delay and dropped the event + // control, so a rename of `clk` missed this occurrence. + let src = "\ +module m; + event e; + logic clk, en; + int d; + initial begin + ->> @(posedge clk iff en) e; + ->> #d e; + end +endmodule +"; + let s = sem(src); + for (name, occurrence) in [("clk", "clk iff"), ("en", "en)"), ("d", "d e;")] { + let r = s + .reference_at(nth(src, occurrence, 0)) + .unwrap_or_else(|| panic!("no reference at the use of {name}")); + assert_eq!(r.name, name); + assert_eq!(r.resolved(), Some(symbol_id(&s, name)), "{name} resolves to its declaration"); + } + // The triggered event itself is still a use of the `event`. + // The first `e;` is the declaration; the second is the first trigger's. + let e = s.reference_at(nth(src, "e;", 1)).expect("the triggered event"); + assert_eq!(e.resolved(), Some(symbol_id(&s, "e"))); +} diff --git a/docs/coverage_gaps.md b/docs/coverage_gaps.md index f7e43dd..7d9f6d0 100644 --- a/docs/coverage_gaps.md +++ b/docs/coverage_gaps.md @@ -91,14 +91,14 @@ request. |---|---|---| | L1 | `expect (@(posedge clk) prop);` — parsed as a call, not a keyword. | Probe. | | L2 | Tagged unions (`union tagged`, `tagged Valid`, `case … matches`). | Probe. | -| L3 | `randsequence` production bodies. | Probe; classes README ("building for a user that does not exist" — corpus 0). | +| ~~L3~~ | ~~`randsequence` production bodies.~~ — **closed at 0.49.0 by TODO §54.2**: `randsequence` is a real statement (`ast::randsequence` — productions, weighted alternatives, `rand join`, `repeat`, `if`/`case`, code blocks parsed as statements); the LRM's own examples are `tests/cases/randsequence.cases`. Corpus and opentitan occurrences: 0. | Probe; classes README ("building for a user that does not exist" — corpus 0). | | L4 | `alias` statement. | Probe. | | L5 | `config … endconfig`, `library`. | Probe. | -| L6 | `->>` non-blocking event trigger; stream `with [range]`; cast bases other than a name/system call; drive strength on a net declaration; net delay written after the type; `let` at statement position; `#(min:typ:max)` clocking skew. | expressions-2 / interfaces / dv-statements READMEs, TODO §11 skips. | +| ~~L6~~ | ~~`->>` non-blocking event trigger; stream `with [range]`; cast bases other than a name/system call; drive strength on a net declaration; net delay written after the type; `let` at statement position; `#(min:typ:max)` clocking skew.~~ — **closed at 0.49.0 by TODO §54.1** (the net-delay clause by §43.2): `->>` with its optional delay or event control, stream `with [range]`, the other `casting_type`s, drive strength on a net declaration, `let` at statement position, `#(min:typ:max)` clocking skews; `tests/cases/coverage_gaps_l6.cases`; the RTL gap fuzzer at 499 gaps, zero failing. | expressions-2 / interfaces / dv-statements READMEs, TODO §11 skips. | | L7 | `` `ifdef `` conditions never evaluated (both arms listed); no macro expansion; stringification passes through. | TODO §7 non-goal — by design, like Verible. | | ~~L8~~ | ~~Execute-command spelling of the instantiation skeleton for clients without `inlineCompletion` (topo §2.9-19).~~ — **delivered 2026-09-02 by TODO §26**: `lucisv.instantiate [uri, position, module]`, planned through the ghost's own `nearest_definition`/`plan_for`, rendered plainly and pushed as a `workspace/applyEdit`. Documented with a keymap in `editors/nvim/README.md`. | inline-instantiation README. | | ~~L9~~ | ~~`codeAction/resolve` laziness; `inlayHint` zero at default scope; index widen not interleaved.~~ — **delivered 2026-09-04/05 by TODO §37** (lazy resolve, 11.8× on the cursor path; the inlay zero ruled correct — `pins_if` is outside the default scope) and **ruled** (a widen stays one bar per session). | TODO §10 closed. | -| L10 | Cosmetic: an enum body one-lined when short; `` `uvm_field_* `` lines dedented to the `` `uvm_object_utils_begin `` column (they are plain macro statements — no block for the formatter to see). | Probe observations. | +| ~~L10~~ | ~~Cosmetic: an enum body one-lined when short; `` `uvm_field_* `` lines dedented to the `` `uvm_object_utils_begin `` column (they are plain macro statements — no block for the formatter to see).~~ — half **ruled already delivered** (a short, comment-free enum body one-lines since the body became a `Doc::Group`; pinned by `tests/format_options.rs`), half **delivered behind a key** at 0.49.0: `[format] uvm-utils-indent`, default off, 21 corpus files affected when on (TODO §54.3). | Probe observations. | --- diff --git a/docs/features/coverage-gaps-l/README.md b/docs/features/coverage-gaps-l/README.md new file mode 100644 index 0000000..163e1d3 --- /dev/null +++ b/docs/features/coverage-gaps-l/README.md @@ -0,0 +1,803 @@ +# coverage-gaps-l + +## Goal + +Close the three low-priority rows `docs/coverage_gaps.md` still leaves +open — **L6** (six small language shapes the grammar never had), **L3** +(`randsequence` production bodies) and **L10** (two cosmetics) — as TODO +§54 plans them. None of the shapes occurs in the corpus or in opentitan, +so the acceptance is hand-written `.cases` tables plus the existing +fuzzers, and the byte-identity gates say the round changed nothing for +anybody who did not ask for it. + +## Assumptions + +- **lucisv is not a legality checker.** Several arms read more than the + LRM strictly allows and print back what was written rather than + rejecting it: a `->` may carry the delay only `->>` may write; a cast + base may be a type with packed dimensions, which §6.24.1's + `casting_type` does not name; a drive strength keeps whichever order + the source wrote its two keywords in. Every one of them is a shape + real tools accept, and reproducing it is the invariant. +- **`randsequence` production names are not symbols.** `vlog_semantic` + binds the expressions, the formals and the statements written inside a + `randsequence`, and declares nothing for the productions themselves: + they live in a scope of their own that nothing outside the statement + can name (§18.17), and no feature asks for them yet. +- **A weight is not a general expression.** §18.17.2's + `weight_specification` is a number, a scoped name or a *parenthesized* + expression, and the parser reads exactly that (`parse_postfix`). It has + to: an unparenthesized `|` separates alternatives, so a weight that + swallowed one would eat the rest of the production. +- **`:=` is two adjacent tokens.** The lexer has no `:=`; the weight + operator is a `:` and an `=` whose spans touch, the same test + `dist_weight_op` already makes for a constraint's `dist`. +- **The `[format]` keys must never fire on their own.** A key that + changes how an already-clean file is laid out defaults to off, and only + a checked-in `lucisv.toml` (or a deliberate editor setting) turns it + on. The byte-identity gate is what proves it. + +## Handshakes + +- **`vlog_parser` → everyone.** `StmtKind::EventTrigger` now carries a + `Box` rather than an `Expr` (arrow text, timing control, + two comment slots); `StmtKind` gained `Let(Box)` and + `RandSequence(Box)`; `ExprKind` gained + `StreamWith { base, range }`; `ExprKind::Stream` gained + `comments: Box`; `DataDecl` gained + `strength: Option`; `DriveStrength` gained + `comments: Box`; `LetDecl` gained `after_kw`, + `eq_comments` and `before_semi`; the clocking grammar's skew became + `ClockingSkew` — after the rework below, the LRM's own two alternatives, + `Edge { word, after_edge, delay }` and `Delay(ClockingDelay)`, with the + new `ClockingDelay` (`Word` / `Paren`) holding the `#` half — with + `ClockingDefault` per half, and `ClockingDecl` / `ClockingItem` grew + their own comment slots. + Every downstream match arm in `vlog_formatter`, `vlog_semantic`, + `vlog_linter`, `vlog_refactor` and `vlog_parser/tests/spans.rs` was + updated in the same change. +- **`vlog_formatter` → `lucisv`, `lucisv_server`.** `Config` gained + `uvm_utils_indent: bool`, default `false`. `Config` is no longer + exhaustively constructible without it — use `..Config::default()`. +- **`lucisv_core` → `lucisv`, `lucisv_server`.** `FileConfig` gained + `format_uvm_utils_indent: Option` and the parser gained the + `[format]` table. Unknown keys under it are rejected by name, as + everywhere else in this parser. +- **`lucisv_server` → the extension.** `ClientSettings` gained + `uvm_utils_indent: Option`, read from + `lucisv.format.uvmUtilsIndent`; `editors/vscode/package.json` declares + it, default `false`. `lucisv.toml` still outranks it, the ladder + `format::settings_for` documents. +- **The lexer's keyword table gained `randsequence`**, so + `editors/vscode/syntaxes/systemverilog.tmLanguage.json` was regenerated + to match (`lucisv_server`'s `the_grammars_keywords_are_exactly_the_lexers` + is the gate). + +## Status / TODO + +- [x] 54.1 the six L6 shapes, each with cases + parity + fuzzers +- [x] 54.2 `randsequence` as real nodes +- [x] 54.3 the cosmetics behind a config key, corpus impact measured + (one key, not two — see the ruling in the work log) +- [x] Docs (this README; the strike text below is the lead's to apply) +- [x] Gates (guarded) + +## Work log + +### 2026-09-06 — the state this lane was picked up in + +The first dev agent stalled part-way through 54.1. What was in the tree, +uncommitted, on `master` at `e1679be`: + +- `->>` complete — lexer operator, `ast::EventTrigger` with `arrow`, + `after_arrow`, `timing`, `before_event`, the parser arm, the formatter + arm, and every downstream match updated. +- Stream `with [range]` half done — `ExprKind::StreamWith`, + `ast::StreamRange` and `parse_stream_range` written; **no** formatter + arm, **no** semantic/spans arms, and `StreamRange` missing `Clone`, so + `cargo check` failed with one error. +- Cast bases — `is_cast_base` had gained its `ExprKind::Type(_)` arm. +- Nothing at all for drive strength on a net declaration, `let` at + statement position, the `#(min:typ:max)` clocking skew, `randsequence` + or the cosmetics; no cases file, no fuzzer fixture, no README body. + +The build was fixed first (`#[derive(Debug, Clone)]` on `StreamRange`, +then the three missing match arms), and the lane continued from there. + +### 2026-09-06 — 54.1, the six L6 shapes + +1. **`->>`** — as the first agent left it, plus cases. `->` and `->>` are + different statements, so the arrow is stored as written and never + rewritten. Only `->>` may carry a delay or event control, but the node + reads one either way. +2. **Stream `with [range]`** — the formatter, binder and span arms it was + missing. The gap after the keyword was moved out of the bracket's + `before_open` into `WithComments::after_kw`, so all three postfix + `with` forms print their head through the one `with_head` function. +3. **Cast bases** — `(W+1)'(x)` and `4'(x)` already worked + (`ExprKind::Paren` and `ExprKind::Number` were already cast bases); + only `logic [3:0]'(x)` was missing, and that is the `ExprKind::Type(_)` + arm the first agent added. Recorded as a case so the three stay tested + together. +4. **Drive strength on a net declaration** — `DataDecl::strength`, read + only after a net keyword (the one position §6.6 allows), printed + between the net keyword and the delay. `parse_opt_drive_strength` + became `pub(super)` and grew five comment slots + (`DriveStrengthComments`), which also **fixed a pre-existing hole**: + `assign /*c*/ (weak0, pull1) x = y;` and + `pullup ( /*c*/ weak1 ) p (x);` were refused by the safety net before + this round and format now. `drive_strength` prints its own leading + separator, the convention `net_delay` already uses. +5. **`let` at statement position** — `StmtKind::Let(Box)`, + dispatched from `parse_keyword_stmt`, printed by the item-level + `let_decl`, bound exactly as the item-level one is. `parse_let` reads + its own `;`, so `takes_semi()` says the kind takes none. `LetDecl` + also gained the comment slots its head never had. +6. **`#(min:typ:max)` clocking skew** — `ClockingSkew` became a real + enum: `Edge(String)` for `posedge`/`negedge`/`edge`, `Delay` for + `#2`/`#1step`, `Paren` for `#( … )`, which goes through + `parse_delay_value` and so inherits `MinTypMaxComments`' four slots. + The one-token spellings are still text and still printed verbatim. + +**`ast::size_pins` moved once, and the round put it back.** Adding +`DataDecl::strength` took `StmtKind` from 392 to 480 bytes, because +`DriveStrengthComments` is five vectors. Boxing them +(`comments: Box`, the treatment +`MinTypMaxComments` already gets) brought it back under the pin, which is +unchanged at 392/552/96. `EventTrigger`, `LetDecl` and `RandSequence` are +boxed in `StmtKind` for the same reason and say so in their doc comments. + +**The gap fuzzer.** Two fixtures were added to `RTL_FIXTURES` — one with +all six shapes, one with a clocking block. Nineteen of their eighty gaps +failed when they were written, **none of them because of the new +shapes**: the `let` head, the two brace pairs of a streaming +concatenation and the whole clocking grammar had no comment slots at all, +and fail identically on a tree without this round +(`let /*C*/ sum = a + b;` as an *item*, `{ /*C*/ <<{a}}`, +`clocking /*C*/ cb`, all three reproduced against the tree as found). +Every one of them was given an owner rather than being fixture-dodged: +`LetDecl::{after_kw, eq_comments, before_semi}`, `StreamComments` +(`after_open`, `before_inner`, `before_close`), +`ClockingDecl::{after_kw, before_event, before_semi}`, `ClockingDefault` +(`before_dir`, `after_dir`), `ClockingItem::before_semi`, +`ClockingItemKind::Signals::{after_dir, after_skew}` and the skew's +`after_hash`. `EXPECTED_RTL_GAPS` 419 → **499, zero failing**. + +A code block's gap just inside its `{` deliberately has *no* slot: it +belongs to the first statement's leading comments, exactly as a +`begin`/`end` block's does. Giving it one made the output non-idempotent +(the comment printed on its own line, then re-parsed as the statement's +leading comment). + +### 2026-09-06 — 54.2, `randsequence` + +Checked first, as the TODO asks: `grep -rn randsequence crates/vlog_parser/src` +found **nothing** — it was not an opaque `Verbatim` leaf, it was a parse +error (`unsupported statement starting with keyword`), and `randsequence` +was not even in the lexer's keyword table. + +Modelled as real nodes in three new files — `ast/randsequence.rs`, +`parser/randsequence.rs`, `format/randsequence.rs` — one sub-grammar per +file, the way SVA and covergroups already are: + +- `StmtKind::RandSequence(Box)`; `RandSequence` holds the + `( start )` with its three comment slots, the productions and the + dangling comments before `endsequence`. +- `Production { meta, ret_type, name, name_span, has_parens, args, + before_colon, alternatives, before_semi, span }`. The return type is + told from the name by lookahead: a type keyword, `void`, or two + identifiers in a row. +- `Alternative { before_bar, after_bar, items, before_weight, weight }`, + with `Weight { after_op, expr, block }` for `:= n { … }`. +- `ProdItem` = `Ref(ProdRef)` | `Block(CodeBlock)` | `If` | `Repeat` | + `Case` | `RandJoin`, each with the slots its own keywords open. The + `rs_case` arm reuses the `case` statement's `case_labels` printer, + including the `default` whose `:` the LRM makes optional. +- `CodeBlock` is `{ statements }` parsed by the ordinary statement + grammar, so `break`, `return` and declarations inside one are the + statements they already were. + +**Layout.** One production per line inside the `randsequence` / +`endsequence` pair. One alternative rides on the head's `:` line — the +common shape, and a code block in it cuddles onto the `:` the way a +`begin` cuddles onto an `if`. Several alternatives are one group: flat +while they fit, otherwise one per line with each `|` starting its own, +indented under the head. The `.cases` table pins both. + +`randsequence` had to go into the lexer's keyword table, which made +`editors/vscode/syntaxes/systemverilog.tmLanguage.json` drift; the +alternation was regenerated in the same change (there is a test for it). + +### 2026-09-06 — 54.3, the cosmetics — one key shipped, one gap already closed + +**`enum-one-line`: no key shipped. The behaviour is already the +default.** The TODO's own text hedges ("today it always breaks? Confirm +with a case"), and the confirmation says it does not. Measured over every +shape the gap names — a `typedef enum` with and without a base type, an +anonymous enum in a variable declaration, each written broken across +lines — the formatter already prints `typedef enum {A, B, C} e_t;` on one +line, because the enum body is a `Doc::Group` like every other list; and +a body with a comment in it still breaks, which is the condition the gap +asks for. Corpus impact of the key as specified: **0 files**, because it +would switch nothing. Shipping a config key that never changes a byte is +the abstraction CLAUDE.md's "Simplicity first" says to stop building, so +it was not shipped. `tests/format_options.rs` pins both directions of +the existing behaviour instead, so nothing takes it away. **The lead's +call at review** if a key is wanted anyway. + +**`uvm-utils-indent`: shipped, default off.** A real gap — the +`` `uvm_field_* `` macros between `` `uvm_object_utils_begin `` and +`` `uvm_object_utils_end `` are plain macro items with no block, so they +print in the `_begin`'s own column. The key is a targeted rule in +`item_seq`: exactly those four macro names (`uvm_object_utils_begin`, +`uvm_component_utils_begin` and their `_end`s) open and close one indent +level over the run between them. An unbalanced `_begin` still prints +everything it opened, one level in — lucisv reproduces the file it was +given. It reaches the formatter three ways, in the ladder +`format::settings_for` documents: `[format] uvm-utils-indent` in +`lucisv.toml` (highest), `lucisv.format.uvmUtilsIndent` in the editor, +and off otherwise. There is deliberately **no CLI flag**: a key that +changes how clean files look is the project's decision, not a run's. + +**Corpus impact, key ON** (scratch copy of the 860-file corpus with a +`lucisv.toml` in every directory — the discovery walk stops at each +vendored `.git`, so one at the root is not enough): + +| | files | +|---|---| +| corpus files formatted | 854 (+6 that error, the known six) | +| files whose output changes with the key on | **21** | +| of those, not idempotent | 0 | +| of those, comment lines lost | 0 | + +The 21: `opentitan/hw/ip/uart/dv/env/uart_env_cfg.sv`; +`ibex/dv/uvm/icache/dv/env/ibex_icache_env_cfg.sv`; +`ibex/dv/uvm/icache/dv/ibex_icache_core_agent/{ibex_icache_core_req_item, +ibex_icache_core_rsp_item, ibex_icache_core_bus_item}.sv`; +`ibex/dv/uvm/icache/dv/ibex_icache_mem_agent/{ibex_icache_mem_req_item, +ibex_icache_mem_resp_item, ibex_icache_mem_bus_item, +ibex_icache_mem_model}.sv`; +`ibex/dv/uvm/core_ibex/env/core_ibex_env_cfg.sv`; +`ibex/dv/uvm/core_ibex/common/ibex_mem_intf_agent/{ibex_mem_intf_response_agent_cfg, +ibex_mem_intf_seq_item}.sv`; +`ibex/dv/uvm/core_ibex/common/ibex_cosim_agent/{ibex_rvfi_seq_item, +ibex_ifetch_seq_item, ibex_ifetch_pmp_seq_item, ibex_cosim_cfg}.sv`; +`ibex/dv/uvm/core_ibex/common/irq_agent/irq_seq_item.sv`; +`ibex/vendor/lowrisc_ip/dv/sv/dv_lib/dv_base_agent_cfg.sv`; +`ibex/vendor/google_riscv-dv/src/{riscv_pmp_cfg, riscv_instr_gen_config, +riscv_vector_cfg}.sv`. Twenty-six corpus files write the macros; the +other five have nothing between `_begin` and `_end` to indent. + +With the key **off** — the shipped default — the corpus is byte-identical +to 0.48.1 over all 860 files. + +### The greps §54 asks for, per shape + +Run 2026-09-06 over the 860-file corpus and over opentitan's +`hw/` (2 553 SystemVerilog files): + +| shape | corpus | opentitan | +|---|---|---| +| `->>` | 0 | 0 (one hit, in a Python script) | +| `with [` (stream range) | 0 | 0 (23 hits, all Markdown prose) | +| `(strength0, strength1)` on a net declaration | 0 | 0 | +| `let` at statement position | 0 | 0 | +| `#(min:typ:max)` clocking skew | 0 | 0 | +| `randsequence` | 0 | 0 | + +The two byte-identity gates are the second, stronger statement of the +same thing: nothing in either tree formats differently because of this +round. + +### Attack tests (CLAUDE.md invariant 4) + +`verify.rs` was **not touched** and no normalization was widened, so no +new forgiveness needs defending. The pairs were written anyway, in +`tests/verification.rs`, one per plausible way a new printer could have +lost or rewritten something: `->` ⇄ `->>`, a dropped `->>` timing +control, a stream range narrowed to an index or its `+:` swapped for +`-:`, a dropped or reordered drive strength, `#(1:2:3)` rewritten as +`#1`, a dropped `randsequence` production, a reordered alternative, a +`|` turned into juxtaposition, a dropped `:=` weight, and a `let` losing +its ports. All ten are refused. The eleventh asserts the other +direction for `uvm-utils-indent`: moving leading whitespace is not a +divergence, and dropping one of the macros it indents is. + +### Files touched outside the expected set + +- `crates/vlog_parser/src/token.rs` — `randsequence` added to the + keyword table (54.2 needs it). +- `editors/vscode/syntaxes/systemverilog.tmLanguage.json` — regenerated + for that keyword; a workspace test fails otherwise. +- `editors/vscode/package.json` — the `lucisv.format.uvmUtilsIndent` + setting declaration. +- `crates/vlog_parser/src/ast/expr.rs`, `parser/primary.rs`, + `format/expr.rs` — `StreamComments`, a gap-fuzzer finding, not a shape + §54 names. +- `crates/vlog_parser/src/ast/decl.rs`, `parser/tf.rs`, + `format/routine.rs` — `LetDecl`'s comment slots, likewise. +- `crates/vlog_formatter/src/format/instance.rs`, `format/item.rs`, + `format/decl.rs` — `DriveStrengthComments` reaches the two constructs + that already wrote a strength, so those printers moved from `String` to + `Doc`. + +### 2026-09-07 — Rework, the four QA findings + +**HIGH 1 — `edge_identifier [delay_control]`.** `ClockingSkew` was three +mutually exclusive variants, so `input negedge #(1:2:3) c;` was a parse +error. It is now the LRM's own two alternatives — `Edge { word, +after_edge, delay: Option }` and `Delay(ClockingDelay)` — +with the `#` half factored into `ClockingDelay` (`Word` for `#2`/`#1step`, +`Paren` for `#( … )`) so the one node serves both alternatives and an +edge-inside-an-edge is not representable. `parse_clocking_skew` reads the +edge, then `gap_before("#")` — the gap is the skew's own slot only when a +`#` really follows, so `input edge /*c*/ sig;` still gives that comment to +`after_skew`, the slot that already owned it. The formatter prints the +edge, the separator (space or that slot's comments) and the delay, all as +written; nothing is re-laid-out or reordered. + +- Cases: two entries in `tests/cases/coverage_gaps_l6.cases` — every form + the finding names (`default input negedge #(1:2:3) output posedge #5;`, + `input negedge #(1:2:3) sig;`, `output posedge #5 other;`, `input + posedge #1step a, b;`, `input edge c;`) and one for the comment slots + either side of the `#`. +- Parser: `a_clocking_skew_reads_a_delay_behind_its_edge` and + `an_edge_skews_delay_is_read_the_same_way_in_tolerant_mode` + (strict/tolerant parity — the tolerant parse of the same source returns + **zero** diagnostics and the same tree). +- Fuzzer: the RTL clocking fixture gained `output negedge #5 o;`. + `EXPECTED_RTL_GAPS` 499 → **505**, zero failing — the six new gaps all + have owners, the one between the edge and its `#` being + `Edge::after_edge`. +- Attack pairs: `a_clocking_skew_rewritten_into_a_bare_delay_is_rejected` + gained both halves of the new shape — `negedge #5` printed as `negedge` + and as `#5` are each refused. `verify.rs` is still untouched. + +**HIGH 2 — `->> @(posedge clk) e;` bound nothing.** `bind/stmt.rs`'s +`EventTrigger` arm hand-matched `TimingControl::Delay`; it now calls the +shared `bind_timing`, which is what every other statement's timing control +goes through, so an event control's signals (and an `iff` guard) are +ordinary references again. Test: +`an_event_triggers_timing_control_is_bound_like_any_other` in +`vlog_semantic/tests/semantics.rs` — `clk`, `en` and the delay's `d` each +resolve to their declaration, and the triggered event still does. +**Census re-derived** (`cargo test -p vlog_semantic --test corpus -- +--nocapture`): 860 files / 27 486 symbols / 103 875 references / 1 197 +unresolved / 0 unplaced — **no delta**, as expected: the corpus writes +`->>` nowhere, so the only references this can add are in files that do +not exist yet. + +**MEDIUM — the `[format]` table had no unit tests.** Three added, written +the way the `[lint]` table's are: `the_format_table_carries_uvm_utils_indent` +(true, false, absent → `None` which is what makes the default off, the +table mixed with top-level and `[lint]` keys), +`the_format_table_rejects_what_it_does_not_support` (unknown key named +under `[format]`, `"yes"` and `1` refused as non-booleans, no value, +duplicate key, the key written above any table, `[format.x]` refused as an +unknown table) and `a_bad_format_key_names_the_file_and_line` (through +`Discovery`, so the message is `:4: unknown key …`). The overlay +ladder is pinned where it is composed: `a_format_key_climbs_the_ladder_from_off` +in `lucisv_server/src/format.rs` — off by default, the editor setting when +only it speaks, `lucisv.toml` winning over the editor in **both** +directions, and a `lucisv.toml` that names other keys staying silent about +this one. + +**LOW — nested `` `uvm_object_utils_begin ``.** `item_seq`'s single +`Option>` became a stack, so a `_begin` inside an open run opens a +level of its own and each `_end` closes the `_begin` it matches; an `_end` +with nothing open closes nothing and moves no indentation, and an unmatched +`_begin` still prints everything it opened (unchanged, and still tested). +Two tests in `tests/format_options.rs`: +`a_nested_begin_opens_a_level_of_its_own_and_its_end_closes_that_one` +(one nested pair, idempotent) and +`an_end_with_no_begin_open_changes_no_indentation` (a lone `_end`, and one +after a closed pair). + +**Gates** (guarded, 2026-09-07). `cargo fmt` clean; `cargo clippy +--all-targets` clean, no warnings; `cargo test --workspace` **4 163 +passed, 0 failed** (4 154 before the rework, +9: two parser, one +semantic, two formatter-option, three `lucisv_core` config and one +`lucisv_server` ladder test — the two `.cases` entries ride inside the one +`case_tables` test); `tools/corpus_check.sh` **814/820** formattable, the +same six parse errors, **0** verification errors, **0** crashes. + +Byte identity, all 860 corpus files, `format --stdout` current tree vs +`~/.cache/lucisv-baselines/lucisv-0.48.1`: **0 differing** — the shipped +default still changes nothing for anybody who did not ask for it. With +`uvm-utils-indent` **on**: **exactly the 21 files listed above**, the same +set, each idempotent and with the same comment-line count. The key was +delivered through `--stdin-filename` pointing at a scratch directory +holding the `lucisv.toml` (a `.git` beside it stops the walk), so the +comparison needed no copy of the corpus and never wrote to it. + +## QA log + +### 2026-09-07 — QA pass, TODO §54 (L3/L6/L10) + +**What was run.** `cargo build --release -p lucisv` (binary reflects the +uncommitted tree). Guarded: `cargo test --workspace` — **4 154 passed, 0 +failed** (matches the work log's count exactly); `cargo clippy +--all-targets` — clean, no warnings; `tools/corpus_check.sh` — **814/820** +formattable, the same six parse errors named in the work log, 0 +verification errors, 0 crashes. `node --test editors/vscode/*_test.js` — 5 +suites, all green, including `hierarchySections_test.js` (unrelated §56 +work sharing the tree) and the grammar keyword-parity test +(`the_grammars_keywords_are_exactly_the_lexers`, part of the workspace +run) — confirms the regenerated `systemverilog.tmLanguage.json` matches +the lexer's keyword table, `randsequence` included. + +**Byte identity.** Built a parallel (`xargs -P 8`) `format --stdout` +diff of all 860 corpus files, current tree vs +`~/.cache/lucisv-baselines/lucisv-0.48.1`: **0 differing.** Opentitan +`hw/` (3 947 `.sv`/`.v`/`.svh`/`.vh` files, a superset of the "2 553" +`.sv`-only figure quoted elsewhere): `format --check` outcome (exit code) +identical between 0.48.1 and current for every file, **0 differing**; +`git -C opentitan status --porcelain` afterward showed only the three +pre-existing modifications (`hw/ip/aes/dv/tb/tb.sv`, +`hw/top_darjeeling/ip/ast/rtl/ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`) +— opentitan untouched otherwise. + +**`uvm-utils-indent` ON**, scratch copy of the corpus with a `lucisv.toml` +at the root and inside each vendored `.git` directory (`opentitan`, +`ibex`, `common_cells`, `picorv32` — the discovery-stop trap the work log +warns about): the parallel diff found **exactly the 21 files the README +lists**, byte for byte the same set, no others. All 21 reformatted a +second time produced identical output (idempotent) and kept the same +comment-line count. `corpus_check.sh` over the same scratch copy: 814/820 +formattable, 0 verification errors, 0 crashes — the key does not change +which files parse. + +**Shape matrix, by hand** (`target/release/lucisv format --stdout`, +idempotency and comment-slot checks on each): `->`/`->>` distinct and +both forms (bare, `#5`, `@(posedge clk)`, inside `fork`) — correct, and +`->` never rewritten. Stream `with [range]`, `[i+:4]`, `[i-:4]`, nested +streams — correct and idempotent. Casts `(W+1)'(x)`, `4'(x)`, +`logic [3:0]'(x)`, `signed'(x)`, `pkg::t'(x)`, `int'(x)` — all format +unchanged. Drive strength on `wire`/`tri`/`wand`, every strength pair, +`(supply0, supply1) [7:0] v`, comments in all five slots (including the +pre-existing `assign`/`pullup` hole the work log says this round fixed — +confirmed, both now format with their comments kept), strength+delay in +the LRM's only legal order (strength then delay) — correct; the reverse +order (`wire #5 (strong0, weak1) w`) is correctly refused with a parse +error rather than silently reordered or misparsed. `let` at statement +position, with and without ports, inside a function, comments in every +slot — correct. `randsequence`: re-typed three LRM-style examples +(a plain grammar, one with `:=` weights of a number/parenthesized +expr/scoped name, `rand join (0.5)`, `repeat`, `if`/`else`, `case` with +`default`, `break`/`return`/`for` inside a code block, a production with +return type and args, a reference to an undefined production — parses, +does not crash the binder), nested `randsequence`, comments in every slot +named in the AST doc comments (`after_kw`, `after_open`, `before_close`, +`before_colon`, `after_bar`, `before_bar`, `before_weight`, `after_op`, +dangling) — all preserved, output idempotent. +`grep -rn randsequence` over the corpus and over opentitan's `hw/`: **0 +hits in both**, not even as a plain identifier — the keyword-addition risk +is confirmed negligible, matching the work log's claim. +Strict/tolerant parity: wrote a temporary test +(`crates/vlog_parser/tests/qa_l6_parity_scratch.rs`, removed after) that +parses every L6 shape and the `randsequence` example through both `parse` +and `parse_tolerant` and asserts identical trees and zero recovered +diagnostics — held for all of them. Attack pairs +(`crates/vlog_formatter/tests/verification.rs`): all eleven ran as part +of the workspace suite and pass (arrow rewrite both directions, dropped +`->>` timing, stream range narrowed and `+:`/`-:` swapped, dropped and +reordered drive strength, `#(1:2:3)` rewritten as `#1`, dropped +production, reordered alternative, `|` to juxtaposition, dropped weight, +`let` losing its ports, uvm-utils-indent whitespace-vs-macro-drop) — +`verify.rs` itself is untouched, confirmed by `git diff`. + +**Findings.** + +- **HIGH — `ClockingSkew` has no arm for `edge_identifier` followed by a + `delay_control`.** IEEE 1800-2017 §14.3: `clocking_skew ::= + edge_identifier [ delay_control ] | delay_control`. The shipped grammar + (`crates/vlog_parser/src/parser/module.rs:350` `parse_clocking_skew`, + mirrored in `crates/vlog_formatter/src/format/module.rs`'s + `ClockingSkew` match) treats `Edge`, `Delay` and `Paren` as mutually + exclusive: `parse_clocking_skew` returns as soon as it reads + `posedge`/`negedge`/`edge`, so a trailing delay is never looked for. + Reproduction: `input negedge #5 c;`, `input posedge #(1:2:3) c;`, + `output negedge #(1:2:3) c;` (the exact shape named in TODO §54.1's own + plan text) and the `default` form + (`default input posedge #(1:2:3) output #(2:3:4);`) all fail with + `expected identifier (found "#")` / `expected ';' (found "#")`. Confirmed + this is new-in-scope, not a pre-existing hole widened: 0.48.1 also + rejects it, but 0.48.1 had **no** `#(1:2:3)` skew at all + (`expected a clocking skew delay (found "(")`), so "edge plus a + parenthesized min:typ:max" was never reachable before this round added + `Paren`; the round added two of the three LRM alternatives for a skew + that follows an edge and missed the third. Not a corruption (the file is + refused, not misprinted), but it is a real hole in a shape the + TODO and this round's own Handshakes section call complete. Needs a + `ClockingSkew::Edge` variant (or a new `EdgeThenDelay` arm) that + optionally reads a trailing `delay_control`, on both the parser and the + formatter side, plus a `.cases`/fixture entry. +- **HIGH — `->> @(posedge clk) e;`'s event control is never bound.** + `crates/vlog_semantic/src/bind/stmt.rs`'s `StmtKind::EventTrigger(t)` arm + hand-matches only `TimingControl::Delay` to bind its expression: + ``` + StmtKind::EventTrigger(t) => { + if let Some(TimingControl::Delay { expr, .. }) = &t.timing { + self.bind_expr(expr, scope); + } + self.bind_expr(&t.expr, scope); + } + ``` + but the same file already has a shared `bind_timing` helper (used by + `wait`, `always @(...)` and others) that handles both + `TimingControl::Delay` *and* `TimingControl::Event(SensList)` via + `bind_sens_list`. The `EventTrigger` arm does not call it, so + `TimingControl::Event` — `->> @(posedge clk) e;`, the exact shape TODO + §54.1 and this round's own fixtures use — silently binds nothing for + `clk` (or an `iff` guard). Verified with a temporary test + (`crates/vlog_semantic/tests/qa_event_trigger_scratch.rs`, removed + after): `s.reference_at(offset of "clk")` returns `None` — no reference + recorded at all, not merely unresolved. Effect: go-to-definition, + find-references and rename on a signal named only inside an event + trigger's event control silently do nothing (a rename would miss this + occurrence, leaving a stale name behind — a real correctness bug for + the refactor tooling, even though it does not touch `vlog_formatter`'s + own invariants). Fix is mechanical: replace the hand-match with + `if let Some(timing) = &t.timing { self.bind_timing(timing, scope); }`. +- **MEDIUM — no unit-test coverage for the `[format]` table in + `lucisv_core::config`.** The `[lint]` table has thorough tests in + `crates/lucisv_core/src/config.rs` (`the_lint_table_carries_select_and_ignore`, + `the_lint_table_rejects_what_it_does_not_support`, duplicate-key and + bad-header cases). No equivalent exists for `[format]`/`uvm-utils-indent` + — `parse_format_entry` and `parse_bool` have no direct test in this + crate. End-to-end behavior is correct (verified by hand: `[format] + uvm-utils-indent = "yes"` gives + `` `uvm-utils-indent` expects `true` or `false`, found `"yes"` `` and + exit code 2; unknown `[format]` keys are named; duplicate keys are + rejected — all exercised only through the CLI, not as a `lucisv_core` + regression test). Per CLAUDE.md ("new behavior needs tests in the same + change"), this is a gap the dev should close; not fixed here because + QA's scope for this lane is verification, not edits to files outside + the QA log. +- **LOW — nested `` `uvm_object_utils_begin `` does not nest.** Given two + begins before their ends (`_begin(c) … _begin(d) … _end … _end`), the + indent opens once and **closes on the first `_end`**, not a matched + pair: everything after the first `_end` (including the second `_begin` + and its own field) prints back at the outer level rather than nesting + or erroring. Idempotent, no comments or macros lost — just a shape the + rule does not track a stack for. Real UVM code never nests these macros + (they themselves expand to `begin`/`end`), so impact is negligible, and + the QA brief flagged this exact case as open ("error? or double + indent — pin"). Recording the actual, observed behavior since the + feature README does not say which was chosen; the lead's call whether + it is worth a stack-based fix or a comment pinning it as intentional. +- Everything else in the plan (six L6 shapes, `randsequence` as real + nodes, the one shipped `[format]` key, the docs list, the gates) checks + out exactly as the work log describes. `EXPECTED_RTL_GAPS` at 499 with + the full workspace run green covers the gap-fuzzer request; a temporary + fixture with comments in every clocking/`let` slot was not added + separately since the two RTL fixtures already added by this round cover + every slot named in the work log and the run above is green. + +**Verdict: REWORK.** Two HIGH findings are concrete, reproducible, in +the files this round touches, and sit squarely inside the shapes TODO +§54.1 names as done (the clocking skew grammar; the `->>` event-control +binding). Neither corrupts formatter output or breaks an invariant in +`verify.rs` — CLAUDE.md invariants 1-4 hold — but "the six L6 shapes, +each with cases + parity + fuzzers" and "every downstream match arm... +updated" (Handshakes) are not yet true for these two cases. Suggested +fix scope for the next dev pass: extend `ClockingSkew` (parser + +formatter + a `.cases` entry) for `edge_identifier [delay_control]`, and +point `EventTrigger`'s bind arm at the existing `bind_timing` helper. The +MEDIUM and LOW findings are not blockers but should be picked up in the +same pass since the files are already open. + +### 2026-09-07 — Re-check of the rework + +Re-read the prior QA entry above and the dev's "Rework, the four QA +findings" work-log entry, then re-diffed the seven files the rework +touched (`ast/module.rs`, `parser/module.rs`, `format/module.rs`, +`format/item.rs`, `bind/stmt.rs`, `lucisv_core/src/config.rs`, +`lucisv_server/src/format.rs`) against clean `master` — all four fixes +are exactly where the work log says. + +**HIGH 1 re-attacked (`ClockingSkew::Edge`'s trailing delay).** Built +`target/release/lucisv` from the tree and ran every shape by hand with +`format --stdout`: `default input negedge #(1:2:3) output posedge #5;`, +the per-signal forms (`input negedge #(1:2:3) a;`, `input posedge +#1step a;`, `input edge b;`, `input #2 c;` delay-only unchanged, `output +posedge d;` edge-only unchanged), a comment on both sides of the `#` +(`input negedge /*A*/ #/*B*/(1:2:3) a;`) and after the edge with no `#` +following (`input edge /*C*/ a;` — confirmed the comment lands in +`after_skew`, not lost), comments inside the min:typ:max parens +(`negedge #(1 /*D*/:2 /*E*/:3)`). All eight round-trip and are +idempotent (checked by reformatting the output). `posedge negedge a;` +(illegal double edge) and `default input;` (illegal — the `default` +form's `clocking_skew` is not optional, unlike the per-signal item's) are +both correctly refused with a parse error, not silently accepted. +`inout posedge sig;` is accepted and printed back verbatim — traced this +to pre-existing behavior on `master` (`git show HEAD:.../module.rs` +already lets any of `input`/`output`/`inout` read an optional skew with +no direction-specific gate); the rework did not touch that gate, so it is +not a rework regression and is left as a pre-existing "not a legality +checker" shape per the feature's own Assumptions — noted, not filed. +Ran the two new parser tests directly: +`cargo test -p vlog_parser --lib a_clocking_skew_reads_a_delay_behind_its_edge` +and `--lib an_edge_skews_delay_is_read_the_same_way_in_tolerant_mode` — +both `ok`, the tolerant one asserting zero recovered diagnostics as +claimed. Attack pairs re-run +(`cargo test -p vlog_formatter --test verification +a_clocking_skew_rewritten_into_a_bare_delay_is_rejected`) — `ok`, both +new pairs (`negedge #5` → `negedge`, `negedge #5` → `#5`) rejected. +`verify.rs` confirmed untouched (`git diff --stat` empty for it). + +**HIGH 2 re-attacked (`->>`'s event control binding nothing).** Ran +`->> @(posedge clk iff en) e;` and `->> #d e;` as two separate statements +(the LRM's `delay_or_event_control` is one alternative, not both at once +— a source combining them, as one out of the four literal test shapes in +the task brief would, is correctly refused with a parse error, confirming +`->>`'s grammar has not been loosened to accept both halves at once) — +both format unchanged and idempotent. Ran +`cargo test -p vlog_semantic --test semantics +an_event_triggers_timing_control_is_bound_like_any_other` — `ok`, +confirming `clk`, `en` and `d` each resolve and the triggered `e` +resolves too. Re-derived the census +(`cargo test -p vlog_semantic --test corpus -- --nocapture`): **860 +files / 27 486 symbols / 103 875 references / 1 197 unresolved / 0 +unplaced** — matches the work log's claim exactly, no delta. + +**MEDIUM re-attacked (`[format]` table unit tests).** Ran the three new +`lucisv_core` tests directly — `the_format_table_carries_uvm_utils_indent`, +`the_format_table_rejects_what_it_does_not_support`, +`a_bad_format_key_names_the_file_and_line` — all `ok`. Added two +temporary scratch tests (removed after) to probe the edges the brief +asked about: a `[format]` header written **twice** is not refused as a +duplicate *table* — it just re-enters the same table (no state tracks +"seen this header before"; only individual keys are duplicate-checked via +`Option::is_some()`), and setting the same key again under the re-entered +header **is** caught as `duplicate key`. This matches `[lint]`'s own +behavior exactly (same lack of a table-repeat check), so it is consistent +existing design, not a rework gap. `uvm-utils-indent = true` written +under `[lint]` is correctly refused as `` unknown key `uvm-utils-indent` +under `[lint]` (known keys: select, ignore, waivers) `` — the two tables +are genuinely separate. Read `a_format_key_climbs_the_ladder_from_off` in +`lucisv_server/src/format.rs` in full: it pins all four rungs (nobody +speaks → off; editor only → editor wins; `lucisv.toml` over the editor in +both directions; a `lucisv.toml` naming other keys stays silent about +this one) — matches the Handshakes section's description of the ladder. + +**LOW re-attacked (nested `` `uvm_object_utils_begin ``).** Ran the two +new `format_options.rs` tests — `ok` on both. Added a temporary scratch +test (removed after) with **three** nesting levels +(`uvm_object_utils_begin(c)` → `uvm_component_utils_begin(d)` → +`uvm_object_utils_begin(e)`) and an unrelated macro (`` `uvm_info ``, not +one of the four tracked names) interleaved at every level: it never +pushes or pops the stack, each `_end` closes exactly the `_begin` it +matches (printing at that `_begin`'s own column, not the run's), and the +whole thing is idempotent with the key off leaving the source untouched. +Hand-traced the stack logic in `item_seq` first to predict the expected +output, then let the test's own first run tell me the actual result to +cross-check the trace — they agreed, confirming the stack behaves as a +real matched-pair nest, not the single-level, first-`_end`-closes-all +behavior the original finding described. + +**Gates (guarded, 2026-09-07).** +`cargo build --release -p lucisv` — clean, used for every hand-attack +above. `cargo clippy --all-targets` — clean, no warnings. +`tools/guard.sh -- cargo test --workspace` (full, uncapped output, +not `| tail`) — **4 166 passed, 0 failed**; the three extra were my own +temporary scratch tests (two in `lucisv_core`, one in +`vlog_formatter/tests/format_options.rs`), all removed afterward — +4 166 − 3 = **4 163, exactly the dev's count**. +`tools/guard.sh -- tools/corpus_check.sh` — **814/820** formattable, the +same six parse errors, 0 verification errors, 0 crashes. +`cargo test -p vlog_formatter --test verification +a_comment_in_every_rtl_gap_still_formats` — `ok`; `EXPECTED_RTL_GAPS` is +505 in the source and the test passes at that count with 0 failing. + +**Byte identity.** All 860 corpus files, `format --stdout`, current tree +vs current tree with no config (both built from this uncommitted tree, +run in parallel with `xargs -P 8`): **0 differing** — the shipped default +(key off) still changes nothing. Key **on**: built a scratch copy of the +corpus (`cp -R`, not touching the real `corpus/` directory) with a +`[format]\nuvm-utils-indent = true` `lucisv.toml` at the root and inside +each vendored `.git` directory (`opentitan`, `ibex`, `common_cells`, +`picorv32` — the discovery-stop trap the work log warns about), then +diffed `format --stdout` of every corpus file against its scratch-copy +counterpart: **exactly 21 files differ**, byte-for-byte the same 21 paths +the README lists (verified by sorting and comparing the list, not just +the count). All 21 reformatted a second time from their own output +(written under the scratch tree so discovery still finds the config) are +byte-identical to the first pass — idempotent — and each keeps the same +`//`/`/*` occurrence count before and after. (First pass at this check +wrote the second-pass input to `/tmp`, outside the scratch tree the +config lives in, which silently fell back to the key-off default and +made all 21 look non-idempotent — a test-harness mistake on my part, not +a formatter bug; corrected by keeping the round-trip inside the scratch +tree and it cleared immediately.) + +**New findings.** None. Every finding from the 2026-09-07 QA pass above +was fixed exactly as described, each fix is covered by a passing test I +ran directly (not just trusted from the log), and the gate numbers match +what the work log claims to the exact digit everywhere they were +checkable (census, `EXPECTED_RTL_GAPS`, workspace test count net of my +own scratch tests, corpus 814/820, the 21-file set). The one thing worth +recording for the lead, not as a defect: `inout sig;` inside a +clocking block is accepted and printed back rather than refused, but this +predates the entire §54 lane (confirmed against `git show HEAD`) and is +consistent with the feature's own "not a legality checker" Assumption — +out of scope for this rework, not filed as a finding. + +Temporary test files/functions used for this re-check +(`qa_scratch_duplicate_format_table_header`, +`qa_scratch_format_key_under_lint_table_is_unknown` in +`crates/lucisv_core/src/config.rs`; +`qa_scratch_three_levels_nested_with_an_unrelated_macro_interleaved` in +`crates/vlog_formatter/tests/format_options.rs`) were all removed before +finishing; `git status`/`git diff` confirm neither file carries them +anymore. + +**Verdict: PASS.** + +## Review + +**2026-09-07 — lead.** Accepted after one rework; ships in 0.49.0 with +§53.2 and closes the coverage tables. The first dev stalled under machine +load and the second finished from the tree, the recipe that worked for +§49. The right calls were made where the plan was wrong: a short +comment-free enum body already one-lines, so no key was built and the +behaviour is pinned; `randsequence` was a parse error rather than an +opaque leaf, so it became real nodes with the LRM's own examples as the +cases; the slot work beyond the letter (`let`, stream concatenations, +the clocking grammar, drive strengths — one of which fixed a pre-existing +refusal) is what the gap fuzzer's zero-failure bar demands, and it stands +at 505 gaps. QA's HIGHs were exactly the two shapes the plan text named +and the dev had not reached (`edge #delay` skews; `->>`'s event control +unbound), fixed with the LRM's own two-alternative shape for a clocking +skew and the shared `bind_timing`; the config table now has the tests the +`[lint]` table always had, and the utils-macro indent tracks nesting. +`uvm-utils-indent` stays default off: 21 corpus files change with it on, +which is the project's choice, not the formatter's. Byte-identity with +the key off is 0 of 860 differing, and the opentitan sweep is identical. + +## Docs to apply at merge (lead) + +**`docs/coverage_gaps.md`.** Strike three rows: + +- **L3** — `~~| L3 | randsequence production bodies. | … |~~` — **closed + at 0.49.0 by TODO §54.2**: `randsequence` is a real statement with a + production list (`ast::randsequence`), weighted alternatives, `rand + join`, `repeat`, `if`/`else` and `case` production items and code + blocks parsed as statements; the LRM's own examples are + `tests/cases/randsequence.cases`. Corpus and opentitan occurrences: 0, + so nothing moved. +- **L6** — all seven clauses of the row are now delivered (the net-delay + clause was already struck by §43.2): `->>` with its optional delay or + event control, stream `with [range]`, the LRM's other `casting_type`s, + drive strength on a net declaration, `let` at statement position and + the `#(min:typ:max)` clocking skew — **closed at 0.49.0 by TODO + §54.1**, with `tests/cases/coverage_gaps_l6.cases` and the RTL gap + fuzzer at 499 gaps, zero failing. +- **L10** — half **ruled already delivered** (a short, comment-free enum + body has been one-lined since the body became a `Doc::Group`; measured + 2026-09-06, pinned by `tests/format_options.rs`), half **delivered + behind a key**: `` `uvm_field_* `` indentation is `[format] + uvm-utils-indent`, default off, 21 corpus files affected when on. + +**`README.md`** — the config table gains one row: + +| key | value | default | meaning | +|---|---|---|---| +| `[format] uvm-utils-indent` | `true` / `false` | `false` | Indent the `` `uvm_field_* `` macros between `` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` one level. | + +**`docs/site/`** — the same row on the configuration page, and on the +editors page the new VS Code setting: + +| setting | default | meaning | +|---|---|---| +| `lucisv.format.uvmUtilsIndent` | `false` | The editor's spelling of `[format] uvm-utils-indent`; a checked-in `lucisv.toml` outranks it. | + +**`docs/site/src/content/docs/guides/syntax.md`** — the sentence +"`randsequence` and a small set of rare expression/port forms remain +outside the formatter grammar" must drop `randsequence`; it is inside the +grammar as of 0.49.0. + +**`docs/topo.md`** — a row for this lane: `coverage-gaps-l` touches +`vlog_parser` (ast + parser + token table), `vlog_formatter`, +`vlog_semantic` (bind), `vlog_linter`, `vlog_refactor`, `lucisv_core` +(config), `lucisv_server` (settings, format) and `editors/vscode`. diff --git a/docs/site/dist/guides/editors/index.html b/docs/site/dist/guides/editors/index.html index 3a957a1..68a7903 100644 --- a/docs/site/dist/guides/editors/index.html +++ b/docs/site/dist/guides/editors/index.html @@ -101,4 +101,4 @@ come from the setting are shown locked.

The repository includes a protocol-level check that starts the server exactly as the VS Code extension does:

Terminal window
node editors/vscode/smoke.js target/release/lucisv-server

See Language tools for every advertised request and editor feature.

- \ No newline at end of file + \ No newline at end of file diff --git a/docs/site/dist/guides/syntax/index.html b/docs/site/dist/guides/syntax/index.html index 7b2ffd1..f4090f0 100644 --- a/docs/site/dist/guides/syntax/index.html +++ b/docs/site/dist/guides/syntax/index.html @@ -107,6 +107,6 @@

Some constructs are recognized structurally but emitted with their internal source layout intact: compiler directives, macro bodies, specify, UDP, checker and config blocks, and carefully recovered conditional-split declarations. Constraint, covergroup and SVA parsers also keep a byte-exact fallback for an unfamiliar body, so unsupported subgrammar does not block the surrounding file.

-

randsequence and a small set of rare expression/port forms remain outside the formatter grammar. lucisv also does not run a preprocessor, so a file that becomes valid only after cross-file macro expansion may not format as a standalone input.

+

A small set of rare expression/port forms remains outside the formatter grammar. lucisv also does not run a preprocessor, so a file that becomes valid only after cross-file macro expansion may not format as a standalone input.

\ No newline at end of file diff --git a/docs/site/dist/pagefind/fragment/en_3f32cd5.pf_fragment b/docs/site/dist/pagefind/fragment/en_3f32cd5.pf_fragment deleted file mode 100644 index f2e20fb..0000000 Binary files a/docs/site/dist/pagefind/fragment/en_3f32cd5.pf_fragment and /dev/null differ diff --git a/docs/site/dist/pagefind/fragment/en_f6c130e.pf_fragment b/docs/site/dist/pagefind/fragment/en_4e3e312.pf_fragment similarity index 79% rename from docs/site/dist/pagefind/fragment/en_f6c130e.pf_fragment rename to docs/site/dist/pagefind/fragment/en_4e3e312.pf_fragment index 9b2b195..b79adb0 100644 Binary files a/docs/site/dist/pagefind/fragment/en_f6c130e.pf_fragment and b/docs/site/dist/pagefind/fragment/en_4e3e312.pf_fragment differ diff --git a/docs/site/dist/pagefind/fragment/en_bb5e837.pf_fragment b/docs/site/dist/pagefind/fragment/en_bb5e837.pf_fragment new file mode 100644 index 0000000..b232d8a Binary files /dev/null and b/docs/site/dist/pagefind/fragment/en_bb5e837.pf_fragment differ diff --git a/docs/site/dist/pagefind/index/en_23e0d0d.pf_index b/docs/site/dist/pagefind/index/en_23e0d0d.pf_index deleted file mode 100644 index 0e87f40..0000000 Binary files a/docs/site/dist/pagefind/index/en_23e0d0d.pf_index and /dev/null differ diff --git a/docs/site/dist/pagefind/index/en_6ff1fca.pf_index b/docs/site/dist/pagefind/index/en_6ff1fca.pf_index deleted file mode 100644 index 44527c9..0000000 Binary files a/docs/site/dist/pagefind/index/en_6ff1fca.pf_index and /dev/null differ diff --git a/docs/site/dist/pagefind/index/en_aa52ccd.pf_index b/docs/site/dist/pagefind/index/en_aa52ccd.pf_index new file mode 100644 index 0000000..93f404b Binary files /dev/null and b/docs/site/dist/pagefind/index/en_aa52ccd.pf_index differ diff --git a/docs/site/dist/pagefind/index/en_fbd771d.pf_index b/docs/site/dist/pagefind/index/en_fbd771d.pf_index new file mode 100644 index 0000000..3822b7f Binary files /dev/null and b/docs/site/dist/pagefind/index/en_fbd771d.pf_index differ diff --git a/docs/site/dist/pagefind/pagefind-entry.json b/docs/site/dist/pagefind/pagefind-entry.json index afed57d..d154021 100644 --- a/docs/site/dist/pagefind/pagefind-entry.json +++ b/docs/site/dist/pagefind/pagefind-entry.json @@ -1 +1 @@ -{"version":"1.5.2","languages":{"en":{"hash":"en_ccc426eeeb","wasm":"en","page_count":12}},"include_characters":["_","‿","⁀","⁔","︳","︴","﹍","﹎","﹏","_"]} \ No newline at end of file +{"version":"1.5.2","languages":{"en":{"hash":"en_e3346e8993","wasm":"en","page_count":12}},"include_characters":["_","‿","⁀","⁔","︳","︴","﹍","﹎","﹏","_"]} \ No newline at end of file diff --git a/docs/site/dist/pagefind/pagefind.en_ccc426eeeb.pf_meta b/docs/site/dist/pagefind/pagefind.en_ccc426eeeb.pf_meta deleted file mode 100644 index 1406ab2..0000000 Binary files a/docs/site/dist/pagefind/pagefind.en_ccc426eeeb.pf_meta and /dev/null differ diff --git a/docs/site/dist/pagefind/pagefind.en_e3346e8993.pf_meta b/docs/site/dist/pagefind/pagefind.en_e3346e8993.pf_meta new file mode 100644 index 0000000..c44b94b Binary files /dev/null and b/docs/site/dist/pagefind/pagefind.en_e3346e8993.pf_meta differ diff --git a/docs/site/dist/start/configuration/index.html b/docs/site/dist/start/configuration/index.html index 4b2e9ed..c3edb45 100644 --- a/docs/site/dist/start/configuration/index.html +++ b/docs/site/dist/start/configuration/index.html @@ -95,6 +95,13 @@ CLI and server +[format].uvm-utils-indent +boolean +false +indent the `uvm_field_* macros between `uvm_*_utils_begin and `uvm_*_utils_end one level +CLI and server + + indent integer 2 @@ -195,6 +202,11 @@ not enable a rule that is off by default.

Server-driven save formatting for clients that need it +lucisv.format.uvmUtilsIndent +false +The editor’s spelling of [format] uvm-utils-indent; a checked-in lucisv.toml outranks it + + lucisv.lineLength null Editor fallback for maximum width diff --git a/docs/site/src/content/docs/guides/syntax.md b/docs/site/src/content/docs/guides/syntax.md index 42f49cd..f78e3b7 100644 --- a/docs/site/src/content/docs/guides/syntax.md +++ b/docs/site/src/content/docs/guides/syntax.md @@ -44,7 +44,7 @@ Some constructs are recognized structurally but emitted with their internal sour ## Not supported -`randsequence` and a small set of rare expression/port forms remain outside the formatter grammar. lucisv also does not run a preprocessor, so a file that becomes valid only after cross-file macro expansion may not format as a standalone input. +A small set of rare expression/port forms remains outside the formatter grammar. lucisv also does not run a preprocessor, so a file that becomes valid only after cross-file macro expansion may not format as a standalone input. :::caution[Safe failure] Whole-file formatting returns an error and writes nothing when parsing is incomplete. lucisv never emits a partially understood file. diff --git a/docs/site/src/content/docs/start/configuration.md b/docs/site/src/content/docs/start/configuration.md index d876b2b..fa552ed 100644 --- a/docs/site/src/content/docs/start/configuration.md +++ b/docs/site/src/content/docs/start/configuration.md @@ -27,6 +27,7 @@ style_regex = "[a-z_0-9]+" | Key | Type | Default | Valid values | Used by | |---|---|---:|---|---| | `line-length` | integer | `100` | `40..400` | CLI and server | +| `[format].uvm-utils-indent` | boolean | `false` | indent the `` `uvm_field_* `` macros between `` `uvm_*_utils_begin `` and `` `uvm_*_utils_end `` one level | CLI and server | | `indent` | integer | `2` | `1..8` | CLI and server | | `exclude` | string array | `[]` | path patterns | CLI walk and server index | | `filelist` | string | — | EDA `.f` path | server index | @@ -66,6 +67,7 @@ Unknown keys, out-of-range numbers, invalid values, tables other than `[lint]` a | `lucisv.inlineTemplates` | `true` | Offer structural ghost-text completions | | `lucisv.inlineInstantiation` | `true` | Offer indexed module instantiation ghost text | | `lucisv.formatOnSave` | `false` | Server-driven save formatting for clients that need it | +| `lucisv.format.uvmUtilsIndent` | `false` | The editor's spelling of `[format] uvm-utils-indent`; a checked-in `lucisv.toml` outranks it | | `lucisv.lineLength` | `null` | Editor fallback for maximum width | | `lucisv.indent` | `null` | Editor fallback for indentation | | `lucisv.exclude` | `[]` | Extra workspace index exclusions | diff --git a/docs/topo.md b/docs/topo.md index b295358..a995307 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -534,6 +534,7 @@ promise: | `vscode-hierarchy-sidebar ──▶ vlog_parser` | depends | `LineIndex::utf16_position` — byte offset to (0-based line, UTF-16 column), moved down beside the line table so the semantic index and `lucisv_server::convert::Positions` cannot answer differently. `Positions::position` is now a wrapper over it; the cross-crate equality is test-pinned. | | `vscode-hierarchy-sidebar ◀──▶ workspace-index` | handshake | `WorkspaceIndex::units_of(kind)` — file-scope declarations of one kind, in name order, walking the unit table alone. The cheap half of `workspace_symbols("")` for a caller that never wants members; 15 ms per snapshot on opentitan. | | `dut-hierarchy ──▶ vscode-hierarchy-sidebar` | depends | TODO §56 (2026-09-06): `hierarchySections.js` consumes the sidebar's model (`rootNode`, the reverse instance index memoised on the model) and its webview renderer's row menu; no edge to any Rust crate — the server is untouched. | +| `coverage-gaps-l` (TODO §54, 0.49.0) | lane | Touches `vlog_parser` (ast + parser + the `randsequence` keyword in the token table), `vlog_formatter` (arms, `[format] uvm-utils-indent`), `vlog_semantic` (bind arms), `vlog_linter`, `vlog_refactor` (match arms), `lucisv_core` (the config key), `lucisv_server` (settings, format) and `editors/vscode` (the setting, the regenerated grammar). New AST: `StmtKind::{EventTrigger, Let, RandSequence}`, `ExprKind::StreamWith`, `DataDecl::strength`, `ClockingSkew`; `size_pins` unmoved. | | `hover-line-index ──▶ port-detail-spans / index-persistence` | depends + handshake | `DeclLines { name, detail }` rides each indexed `Decl`, so ordinary and split-port hover headings do not reread a file just to compute a line. The record grew again and **`FACTS_FORMAT` went 3 → 4**; the server's bounded `FileView` cache supplies the text/`LineIndex` only when a snippet or a non-indexed position still needs it. Its four invalidation points are `set_document`, `close_document`, `update_one`, and a whole rebuild. | | `scan-interleave ◀──▶ workspace-index` | handshake | A scan is a stepped `Scan` value; staged `FileFacts` land through `WorkspaceIndex::absorb`, one whole-index merge per queue drain rather than per file. `Candidates::absorb` and `IncludeGraph::absorb` publish their tables in the same drain, so “the workspace as far as scanned” cannot mean three different prefixes. | | `scan-interleave ──▶ hover-line-index` | depends | Delivers hover-line-index's measured startup-wait request: a startup scan above 64 files drains queued messages between files. A rescan deliberately still holds requests; what an answer sees never depends on elapsed wall time. | diff --git a/editors/vscode/CHANGELOG.md b/editors/vscode/CHANGELOG.md index 002dfbf..d4f2906 100644 --- a/editors/vscode/CHANGELOG.md +++ b/editors/vscode/CHANGELOG.md @@ -10,6 +10,9 @@ number; the full engineering notes live in the - **Inline module** from the lightbulb on an instantiation: the module's body is copied in with ports and parameters substituted and every comment kept; the reverse of extract module. +- `randsequence`, `->>`, stream slices, net drive strengths, `let` + statements and clocking skews format; `lucisv.format.uvmUtilsIndent` + indents `uvm_field_*` lines inside the utils macros (off by default). ## 0.48.2 — 2026-09-06 diff --git a/editors/vscode/README.md b/editors/vscode/README.md index 8c87192..91e83a4 100644 --- a/editors/vscode/README.md +++ b/editors/vscode/README.md @@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view, then open a Verilog or SystemVerilog file. There is no separate server or CLI setup. -The current release is **0.48.2**. Its platform packages include both +The current release is **0.49.0**. Its platform packages include both `lucisv-server` and the `lucisv` command-line tool: | Package target | Machines | @@ -374,6 +374,12 @@ Every nesting color is a proper VS Code theme color: } ``` +## Release 0.49.0 highlights + +Version 0.49.0 adds inline module (the reverse of extract), the last six +language shapes from the coverage tables plus `randsequence`, and an +opt-in `uvm_field_*` indent. + ## Release 0.48.0 highlights Version 0.48.0 makes the hierarchy pane DUT-centred: star a module and diff --git a/editors/vscode/package.json b/editors/vscode/package.json index 763bd0c..5dd51a0 100644 --- a/editors/vscode/package.json +++ b/editors/vscode/package.json @@ -284,6 +284,11 @@ "scope": "window", "markdownDescription": "Modules the Hierarchy pane treats as DUTs, by name. Each one splits the pane into two more sections — the DUT with its children, and an upward tree of everything that instantiates it — ahead of the \"Other modules\" section. This is the checked-in list a team shares (`.vscode/settings.json`); starring from the pane's own menu is the per-workspace way and the two are shown together. A DUT that comes from this setting is shown locked and cannot be unstarred from the pane." }, + "lucisv.format.uvmUtilsIndent": { + "type": "boolean", + "default": false, + "markdownDescription": "Indent the `` `uvm_field_* `` macros written between `` `uvm_object_utils_begin ``/`` `uvm_component_utils_begin `` and their `` _end `` one level, the way a `begin`/`end` body would be. They are plain macro invocations with no block for the formatter to see, so it leaves them in the `_begin`'s own column unless this is on. **Off by default**: turning it on changes the formatted output of files that are already clean. A checked-in `lucisv.toml` with `[format] uvm-utils-indent = true` outranks this setting, so a project and its editors cannot disagree." + }, "lucisv.inlineTemplates": { "type": "boolean", "default": true, diff --git a/editors/vscode/syntaxes/systemverilog.tmLanguage.json b/editors/vscode/syntaxes/systemverilog.tmLanguage.json index b09ef76..89ec4a5 100644 --- a/editors/vscode/syntaxes/systemverilog.tmLanguage.json +++ b/editors/vscode/syntaxes/systemverilog.tmLanguage.json @@ -70,7 +70,7 @@ }, "keywords": { "name": "keyword.other.systemverilog", - "match": "\\b(module|macromodule|endmodule|interface|endinterface|package|endpackage|program|endprogram|modport|clocking|endclocking|input|output|inout|ref|wire|tri|tri0|tri1|wand|wor|trireg|supply0|supply1|uwire|reg|logic|bit|byte|shortint|int|longint|integer|time|realtime|real|shortreal|string|chandle|event|var|void|signed|unsigned|packed|parameter|localparam|defparam|specparam|type|typedef|enum|struct|union|assign|alias|always|always_comb|always_ff|always_latch|initial|final|begin|end|if|else|case|casex|casez|randcase|let|endcase|default|unique|unique0|priority|for|while|repeat|forever|do|foreach|break|continue|return|fork|join|join_any|join_none|disable|wait|posedge|negedge|edge|or|and|nand|nor|xor|xnor|not|buf|bufif0|bufif1|notif0|notif1|pullup|pulldown|generate|endgenerate|genvar|class|endclass|extends|implements|virtual|pure|extern|rand|randc|local|protected|constraint|covergroup|endgroup|function|endfunction|task|endtask|automatic|static|const|import|export|timeunit|timeprecision|assert|assume|cover|property|endproperty|sequence|endsequence|inside|with|iff|release|force|deassign|primitive|endprimitive|specify|endspecify|table|endtable|checker|endchecker|config|endconfig|library|small|medium|large|scalared|vectored|highz0|highz1|strong0|strong1|pull0|pull1|weak0|weak1|cmos|rcmos|nmos|pmos|rnmos|rpmos|tran|rtran|tranif0|tranif1|rtranif0|rtranif1)\\b" + "match": "\\b(module|macromodule|endmodule|interface|endinterface|package|endpackage|program|endprogram|modport|clocking|endclocking|input|output|inout|ref|wire|tri|tri0|tri1|wand|wor|trireg|supply0|supply1|uwire|reg|logic|bit|byte|shortint|int|longint|integer|time|realtime|real|shortreal|string|chandle|event|var|void|signed|unsigned|packed|parameter|localparam|defparam|specparam|type|typedef|enum|struct|union|assign|alias|always|always_comb|always_ff|always_latch|initial|final|begin|end|if|else|case|casex|casez|randcase|let|endcase|default|unique|unique0|priority|for|while|repeat|forever|do|foreach|break|continue|return|fork|join|join_any|join_none|disable|wait|posedge|negedge|edge|or|and|nand|nor|xor|xnor|not|buf|bufif0|bufif1|notif0|notif1|pullup|pulldown|generate|endgenerate|genvar|class|endclass|extends|implements|virtual|pure|extern|rand|randsequence|randc|local|protected|constraint|covergroup|endgroup|function|endfunction|task|endtask|automatic|static|const|import|export|timeunit|timeprecision|assert|assume|cover|property|endproperty|sequence|endsequence|inside|with|iff|release|force|deassign|primitive|endprimitive|specify|endspecify|table|endtable|checker|endchecker|config|endconfig|library|small|medium|large|scalared|vectored|highz0|highz1|strong0|strong1|pull0|pull1|weak0|weak1|cmos|rcmos|nmos|pmos|rnmos|rpmos|tran|rtran|tranif0|tranif1|rtranif0|rtranif1)\\b" } } }