Files
lucisv/crates/vlog_formatter/src/format/module.rs
T
lucioandClaude Fable 5.1 a69a1cb528 Coverage gaps L3, L6, L10: six language shapes, randsequence as real nodes, an opt-in uvm_field_* indent
TODO §54 (docs/features/coverage-gaps-l); closes docs/coverage_gaps.md
L3, L6 and L10. The first dev stalled under machine load; a second
finished from the tree.

54.1 `->>` with optional delay or event control (`StmtKind::EventTrigger`),
stream `with [range]` (`ExprKind::StreamWith`), the LRM's other
`casting_type`s, drive strength on a net declaration (`DataDecl::strength`,
whose comment slots also fix a pre-existing refusal on an `assign` with
a comment before its strength), `let` at statement position
(`StmtKind::Let`), and `#(min:typ:max)` clocking skews — `ClockingSkew`
as the LRM's two alternatives, `edge [delay]` | `delay` (review rework of
QA's HIGH). Comment slots added to `let`, stream concatenations and the
clocking grammar; the RTL gap fuzzer at 505 gaps, zero failing.
54.2 `randsequence` (it was a parse error; the keyword is new):
`RandSequence` → `Production` → `Alternative` → `ProdItem` (ref, block,
if, repeat, case, rand join), code blocks by the statement grammar; one
production per line, alternatives aligned; the LRM's examples as cases.
54.3 `[format] uvm-utils-indent` / `lucisv.format.uvmUtilsIndent`, default
off, tracking nested `_begin`/`_end` pairs; 21 corpus files change with
it on, all idempotent. A short comment-free enum body already one-lines,
so no key was built — the behaviour is pinned. `[format]` table tests
added (review rework). `->>`'s event control is bound through the shared
`bind_timing` (review rework of QA's second HIGH).

0 of 820 corpus files differ from 0.48.x with the key off; the opentitan
sweep is identical; no corpus or opentitan file writes any of the new
shapes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-07 01:12:49 -05:00

451 lines
19 KiB
Rust

//! What a module or interface declares at its boundary: the header
//! through its `;` (name, imports, parameter ports, ANSI or non-ANSI
//! ports), the alignment of an ANSI port list, `modport`s and clocking
//! blocks.
//!
//! The header is split from the body (`module_head` vs `module`) so a
//! range run can keep one verbatim and lay out the other.
use crate::align::{self, Align, ColSpec, Row};
use crate::doc::*;
use vlog_parser::ast::*;
use super::list::ListItem;
use super::routine::TfHeader;
use super::{join_names, join_paths, name_doc, named, Fmt};
/// An ANSI port's one alignment column: the name, one space off the type.
const ANSI_PORT_COLS: &[ColSpec] = &[ColSpec { flush: 1, min: 1 }];
impl<'a> Fmt<'a> {
pub(super) fn module(&self, m: &Module, depth: usize) -> Doc {
let mut docs = vec![self.module_head(m, depth)];
let mut body = Vec::new();
if !m.items.is_empty() {
body.push(Doc::HardLine);
body.extend(self.item_seq(&m.items, depth + 1));
}
body.extend(self.dangling(&m.dangling));
docs.push(indent(body));
docs.push(Doc::HardLine);
docs.push(self.closing_labeled(m.end_kw(), &m.end_label, &m.end_label_comments));
concat(docs)
}
/// A module header: everything through the `;` that closes it.
///
/// Split out from the body so a range run can keep one and lay out the
/// other (`range.rs`); a whole-file run always emits both.
pub(super) fn module_head(&self, m: &Module, depth: usize) -> Doc {
let mut docs = vec![text(m.kw.clone())];
if m.before_name.is_empty() {
docs.push(text(" "));
} else {
self.inline_comments_spaced(&m.before_name, &mut docs);
}
docs.push(text(named(&m.name)));
let has_imports = !m.imports.is_empty();
if has_imports {
// One line per `import` statement the header wrote: folding two of
// them into one comma-separated statement would rewrite a `;`.
let mut lines = Vec::new();
for imp in &m.imports {
lines.push(Doc::HardLine);
lines.extend(self.leading(&imp.meta));
lines.push(text(format!("import {};", join_paths(&imp.paths))));
lines.extend(self.trailing(&imp.meta));
}
docs.push(indent(lines));
docs.push(Doc::HardLine);
}
// After an import block the header continues at column 0, so the
// usual single space before `#(`/`(` is dropped.
let mut on_fresh_line = has_imports;
on_fresh_line = self.bracket_comments(&m.param_comments, &mut docs, on_fresh_line);
// A written-but-empty `#()` is printed back; a missing one stays
// missing.
if let Some(params) = &m.param_ports {
let items: Vec<ListItem> = params
.iter()
.map(|p| {
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma)
})
})
.collect();
let items = self.list_entries(items, &m.param_directives);
let broken = !m.param_directives.is_empty();
docs.push(text(if on_fresh_line { "#" } else { " #" }));
self.slot_comments(&m.param_after_hash, &mut docs);
docs.push(self.delimited_dangling("(", items, &m.param_dangling, ")", broken));
on_fresh_line = false;
}
let on_fresh_line = self.bracket_comments(&m.port_comments, &mut docs, on_fresh_line);
// A port list whose every element sits in an `ifdef arm still holds
// directives while being `PortList::Empty`, so the two are laid out by
// the same code.
let mut broken = !m.port_directives.is_empty();
match &m.ports {
PortList::None => docs.push(self.semi(&m.before_semi)),
PortList::Empty | PortList::Ansi(_) | PortList::NonAnsi(_) => {
let items: Vec<ListItem> = match &m.ports {
PortList::Ansi(ports) => {
// An aligned list is a broken list: alignment only
// means anything one element per line.
let aligns = self.ansi_port_aligns(ports, &m.port_directives, depth + 1);
broken |= aligns.iter().any(Option::is_some);
ports
.iter()
.zip(&aligns)
.map(|(p, a)| {
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, self.ansi_port(p, a.as_ref()))
.with_comma(p.comma)
})
})
.collect()
}
PortList::NonAnsi(ports) => ports
.iter()
.map(|p| {
self.list_elem(p, |p| {
ListItem::from_meta(&p.meta, name_doc(&p.name)).with_comma(p.comma)
})
})
.collect(),
_ => Vec::new(),
};
let items = self.list_entries(items, &m.port_directives);
if !on_fresh_line {
docs.push(text(" "));
}
docs.push(self.delimited_dangling("(", items, &m.port_dangling, ")", broken));
docs.push(self.semi(&m.before_semi));
}
}
concat(docs)
}
pub(super) fn param_port(&self, p: &ParamPort) -> Doc {
let mut docs = Vec::new();
if let Some(kw) = &p.kw {
self.word_then(kw, &p.after_kw, &mut docs);
} else {
self.slot_comments(&p.after_kw, &mut docs);
}
if p.is_type {
docs.push(text("type "));
}
match self.data_type(&p.ty) {
Some(t) => {
docs.push(t);
if p.before_name.is_empty() {
docs.push(text(" "));
} else {
self.inline_comments_spaced(&p.before_name, &mut docs);
}
}
None => self.slot_comments(&p.before_name, &mut docs),
}
docs.push(name_doc(&p.name));
docs.extend(self.unpacked_dims(&p.unpacked));
if let Some(d) = &p.default {
self.eq_default(&p.eq_comments, group(vec![self.expr(d)]), &mut docs);
}
concat(docs)
}
fn ansi_port(&self, p: &AnsiPort, align: Option<&Align>) -> Doc {
align::render(&self.ansi_port_cells(p), ANSI_PORT_COLS, align)
}
/// An ANSI port split at its one alignment column, the name: the
/// direction/net/type prefix, then the name and everything after it. A
/// port with no prefix at all (a continuation port, `output a, b`) is one
/// cell, which is what takes it out of every alignment group.
fn ansi_port_cells(&self, p: &AnsiPort) -> Vec<Doc> {
// A comment in one of the port's own gaps makes the row a width no
// other row shares, so it is one cell and joins no alignment group —
// the rule an attributed connection already follows.
if !p.after_dir.is_empty() || !p.before_name.is_empty() {
return vec![self.ansi_port_plain(p)];
}
let mut prefix = Vec::new();
if let Some(dir) = &p.dir {
prefix.push(text(format!("{dir} ")));
}
if let Some(net) = &p.net {
prefix.push(text(format!("{net} ")));
}
if let Some(t) = self.data_type(&p.ty) {
prefix.push(t);
prefix.push(text(" "));
}
// The trailing space of the last prefix part is the column separator,
// which `align::render` writes instead.
if let Some(Doc::Text(last)) = prefix.last_mut() {
if last.ends_with(' ') {
last.pop();
}
}
let mut docs = vec![name_doc(&p.name)];
docs.extend(self.unpacked_dims(&p.unpacked));
if let Some(d) = &p.default {
self.eq_default(&p.eq_comments, self.expr(d), &mut docs);
}
if prefix.is_empty() {
return vec![concat(docs)];
}
vec![concat(prefix), concat(docs)]
}
/// An ANSI port written out in one piece, for the rows that carry a
/// comment in one of their own gaps and so cannot be aligned.
fn ansi_port_plain(&self, p: &AnsiPort) -> Doc {
let mut docs = Vec::new();
if let Some(dir) = &p.dir {
self.word_then(dir, &p.after_dir, &mut docs);
}
if let Some(net) = &p.net {
docs.push(text(format!("{net} ")));
}
match self.data_type(&p.ty) {
Some(t) => {
docs.push(t);
if p.before_name.is_empty() {
docs.push(text(" "));
} else {
self.inline_comments_spaced(&p.before_name, &mut docs);
}
}
None => self.slot_comments(&p.before_name, &mut docs),
}
docs.push(name_doc(&p.name));
docs.extend(self.unpacked_dims(&p.unpacked));
if let Some(d) = &p.default {
self.eq_default(&p.eq_comments, self.expr(d), &mut docs);
}
concat(docs)
}
/// The alignment plan for a module header's ANSI port list.
fn ansi_port_aligns(
&self,
ports: &[ListElem<AnsiPort>],
directives: &[ListDirective],
depth: usize,
) -> Vec<Option<Align>> {
let rows: Vec<Option<Row>> = ports
.iter()
.map(|p| {
// An error element has no cells to align, so it has no row.
let p = p.ok()?;
Self::row_of(
&self.ansi_port_cells(p),
vec![p.name_span.start],
usize::from(p.comma),
)
})
.collect();
let breaks = Self::list_breaks(ports.iter().map(|p| p.ok().map(|p| &p.meta)), directives);
self.align_groups(&rows, &breaks, ANSI_PORT_COLS, depth)
}
/// `modport a (input x, output y), b (...);` (IEEE 1800 §25.5).
///
/// Each modport's port list is a breakable group of its own, laid out
/// exactly like a header port list: one line when it fits, one entry per
/// line when it does not. A direction keyword and the names it governs are
/// one entry, so the source's grouping (`input valid, data`) survives.
pub(super) fn modport(&self, decls: &[ModportDecl]) -> Doc {
let mut docs = vec![text("modport")];
let last = decls.len().saturating_sub(1);
let mut on_fresh_line = false;
for (i, d) in decls.iter().enumerate() {
if !on_fresh_line {
docs.push(text(" "));
}
docs.extend(self.leading(&d.meta));
docs.push(text(format!("{} ", named(&d.name))));
let items: Vec<ListItem> = d
.ports
.iter()
.map(|p| ListItem::from_meta(&p.meta, self.modport_port(p)).with_comma(p.comma))
.collect();
docs.push(self.delimited_dangling("(", items, &d.dangling, ")", false));
let ends_line = self.inline_comments(&d.meta.before_sep, &mut docs);
if i < last {
if ends_line {
docs.push(Doc::HardLine);
}
docs.push(text(","));
}
on_fresh_line = false;
if let Some(tr) = &d.meta.trailing {
docs.push(text(" "));
docs.push(self.comment(tr));
if i < last {
docs.push(Doc::HardLine);
on_fresh_line = true;
}
}
}
docs.push(text(";"));
concat(docs)
}
/// One direction group of a modport port list: `input valid, data`, or an
/// `import`/`export` method prototype (`import task drive(int x)`, IEEE
/// 1800 §25.5.4) — printed through the very header printer a real `task`
/// or `function` declaration uses, so the two cannot drift apart.
fn modport_port(&self, p: &ModportPort) -> Doc {
let mut docs = vec![text(p.kw.clone())];
if p.after_kw.is_empty() {
docs.push(text(" "));
} else {
self.inline_comments_spaced(&p.after_kw, &mut docs);
}
match &p.prototype {
Some(proto) => self.tf_header(&TfHeader::of_prototype(proto), &mut docs),
None => docs.push(text(join_names(&p.names))),
}
concat(docs)
}
/// `clocking cb @(posedge clk); ... endclocking` (IEEE 1800 §14.3), one
/// 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 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),
}
// `default clocking cb;` selects an existing block: no event, no body.
let Some(event) = &c.event else {
// 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(self.sens_list(event));
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), self.semi(&item.before_semi)]));
body.extend(self.trailing(&item.meta));
}
body.extend(self.dangling(&c.dangling));
docs.push(indent(body));
if c.has_end {
docs.push(Doc::HardLine);
docs.push(self.closing_labeled("endclocking", &c.end_label, &c.end_label_comments));
}
concat(docs)
}
/// One clocking-block item. A `= expression` binding
/// (`output tms = _tms_internal;`) prints on the item's own line: the
/// bound expression is a signal name, never long enough to be worth a
/// breakable group.
fn clocking_item(&self, kind: &ClockingItemKind) -> Doc {
match kind {
ClockingItemKind::Default { input, output } => {
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, 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 {
docs.push(self.clocking_skew(skew));
match after_skew.is_empty() {
true => docs.push(text(" ")),
false => self.inline_comments_spaced(after_skew, &mut docs),
}
}
for (i, sig) in signals.iter().enumerate() {
if i > 0 {
docs.push(text(", "));
}
docs.push(name_doc(&sig.name.text));
if let Some(value) = &sig.value {
docs.push(text(" = "));
docs.push(self.expr(value));
}
}
concat(docs)
}
}
}
/// 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<Doc>) {
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)
}
}
}
}