Files
lucisv/crates/vlog_formatter/src/format/item.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

606 lines
26 KiB
Rust

//! The file and its items: a source file or fragment, the sequence of
//! items at one indent level with the blank lines the source wrote, the
//! dispatch from `ItemKind` to the construct that prints it, and the
//! items that are only containers or one-liners — `package`, the
//! generate constructs, `assign`.
//!
//! Everything with a shape worth a file of its own — the module header,
//! an instantiation, a declaration, a class — is dispatched to from
//! `item_kind` and lives in a sibling module.
use crate::align::Align;
use crate::doc::*;
use crate::range::Split;
use vlog_parser::ast::*;
use vlog_parser::token::Comment;
use super::instance::drive_strength;
use super::list::ListItem;
use super::verbatim::Slot;
use super::{join_names, join_paths, named, Fmt};
impl<'a> Fmt<'a> {
pub(super) fn file(&self, f: &SourceFile) -> Doc {
let mut docs = match &f.fragment {
Some(fragment) => self.fragment(fragment),
None => self.item_seq(&f.items, 0),
};
for c in &f.dangling {
let doc = match self.slot(c) {
Slot::Covered => continue,
Slot::Opens(r) => self.verbatim(r),
Slot::Normal => self.comment(c),
};
if !docs.is_empty() {
docs.push(if c.blank_before { Doc::BlankLine } else { Doc::HardLine });
}
docs.push(doc);
}
concat(docs)
}
/// A whole file that is the middle of some body, printed at indent 0
/// through the very printers that body uses — a statement sequence, an
/// enum's member list, a covergroup's items. Nothing here is a layout of
/// its own: the fragment is the piece of code it was written as, minus the
/// construct around it, and it must come back the way that construct would
/// have printed it. See `docs/features/fragment-mode/README.md`.
fn fragment(&self, fragment: &Fragment) -> Vec<Doc> {
match fragment {
Fragment::Statements(stmts) => self.stmt_seq(stmts),
Fragment::EnumMembers { members, directives } => {
let items = self.list_entries(self.enum_member_items(members), directives);
let mut docs = Vec::new();
// The file's own dangling comments are `SourceFile::dangling`
// and `Fmt::file` prints them, so the list has none of its own.
self.list_rows(items, &[], &mut docs);
docs
}
Fragment::CoverItems(items) => self.cover_items(items),
}
}
/// Sequence of items at one indent level, preserving single blank lines
/// between them. An item a fenced region swallowed emits nothing, and
/// contributes no separator either.
pub(super) fn item_seq(&self, items: &[Item], depth: usize) -> Vec<Doc> {
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<Doc>> = 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;
}
// 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));
}
}
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;`, `;;`.
///
/// The question is asked of the source rather than of the AST because it
/// is a layout fact about the gap between two siblings, and this is the
/// one place that gap is laid out — the same reason `eq_offset` and
/// `default_has_colon` read `src` here. A null item that begins a body has
/// no sibling to glue to and prints on its own line.
///
/// Anything that gives the `;` docs of its own — a leading comment, an
/// attribute, a blank line, a format-off fence opening on it — takes the
/// own-line path instead, so the glue only ever appends a bare `;`. Note
/// that a `//` comment cannot stand in a newline-free gap: it would
/// swallow the `;` that follows it. The only comment that fits is a
/// one-line block comment, which prints inline before the `;`, in the
/// order it was written.
fn glued_null_item(&self, prev: &Item, item: &Item) -> bool {
if !matches!(item.kind, ItemKind::Empty) {
return false;
}
if item.meta.blank_before || !item.meta.leading.is_empty() || !item.meta.attrs.is_empty() {
return false;
}
if self.is_verbatim(item.span) || self.opens_at(item.span.start as usize).is_some() {
return false;
}
self.src
.get(prev.span.end as usize..item.span.start as usize)
.is_some_and(|gap| !gap.contains('\n'))
}
fn item(&self, item: &Item, depth: usize) -> Doc {
concat(self.item_docs(item, None, depth))
}
/// One item: its leading comments, then — unless a verbatim region is
/// already emitting its bytes — its attributes, code and trailing
/// comment. Comments before the `off` fence are still emitted; comments
/// are never dropped.
fn item_docs(&self, item: &Item, align: Option<&Align>, depth: usize) -> Vec<Doc> {
if let Some(split) = self.split_at(item.span.start as usize) {
if let Some(docs) = self.split_item(item, split, depth) {
return docs;
}
}
// A verbatim run whose first item carries no leading comment opens at
// the item's own code; there is no comment to emit the bytes from.
if let Some(region) = self.opens_at(item.span.start as usize) {
return vec![self.verbatim(region)];
}
if self.is_verbatim(item.span) {
// The item's own bytes, its attributes included, are emitted
// verbatim by the fence; only its leading comments are ours.
let mut docs = self.leading_comments(&item.meta);
// The last comment asked for a line break before code that is not
// coming. Whoever emits the next unit separates it itself.
if matches!(docs.last(), Some(Doc::HardLine)) {
docs.pop();
}
return docs;
}
let mut docs = self.leading(&item.meta);
docs.push(self.item_kind(&item.kind, align, depth));
docs.extend(self.trailing(&item.meta));
docs
}
/// A scope-bearing item a range run descends into.
///
/// Its header and its closing keyword are the source's own bytes unless
/// the caller's lines reached them, and its body is laid out one item at a
/// time — which is what keeps a three-line edit from reformatting a
/// two-thousand-line module. `None` for any other item kind, which
/// `range.rs` never records a split for.
fn split_item(&self, item: &Item, split: &Split, depth: usize) -> Option<Vec<Doc>> {
let (items, dangling) = match &item.kind {
ItemKind::Module(m) => (&m.items[..], &m.dangling[..]),
ItemKind::Package { items, dangling, .. } => (&items[..], &dangling[..]),
_ => return None,
};
let mut docs = Vec::new();
match split.head {
Some(range) => docs.push(self.slice(range)),
None => {
docs.extend(self.leading(&item.meta));
docs.push(self.head_doc(&item.kind, depth)?);
}
}
let mut body = Vec::new();
if !items.is_empty() {
body.push(Doc::HardLine);
body.extend(self.item_seq(items, depth + 1));
}
body.extend(self.dangling(dangling));
docs.push(indent(body));
docs.push(Doc::HardLine);
match split.tail {
// The slice reaches over the comment written after the keyword,
// so the trailing comment must not be printed a second time.
Some(range) => docs.push(self.slice(range)),
None => {
docs.push(self.tail_doc(&item.kind)?);
docs.extend(self.trailing(&item.meta));
}
}
Some(docs)
}
/// A split item's header, laid out.
fn head_doc(&self, kind: &ItemKind, depth: usize) -> Option<Doc> {
match kind {
ItemKind::Module(m) => Some(self.module_head(m, depth)),
ItemKind::Package { kw, before_name, name, before_semi, .. } => {
Some(self.package_head(kw, before_name, name, before_semi))
}
_ => None,
}
}
/// A split item's closing keyword, laid out.
fn tail_doc(&self, kind: &ItemKind) -> Option<Doc> {
match kind {
ItemKind::Module(m) => {
Some(self.closing_labeled(m.end_kw(), &m.end_label, &m.end_label_comments))
}
ItemKind::Package { end_label, end_label_comments, .. } => {
Some(self.closing_labeled("endpackage", end_label, end_label_comments))
}
_ => None,
}
}
pub(super) fn item_kind(&self, kind: &ItemKind, align: Option<&Align>, depth: usize) -> Doc {
match kind {
ItemKind::Module(m) => self.module(m, depth),
ItemKind::Package {
kw,
before_name,
name,
before_semi,
items,
dangling,
end_label,
end_label_comments,
..
} => {
let mut docs = vec![self.package_head(kw, before_name, name, before_semi)];
let mut body = Vec::new();
if !items.is_empty() {
body.push(Doc::HardLine);
body.extend(self.item_seq(items, depth + 1));
}
body.extend(self.dangling(dangling));
docs.push(indent(body));
docs.push(Doc::HardLine);
docs.push(self.closing_labeled("endpackage", end_label, end_label_comments));
concat(docs)
}
ItemKind::Directive(d) => self.raw_text(d),
// Only error-tolerant parsing builds these, and `format_source`
// parses strictly, so this arm exists to keep the match total.
ItemKind::Error(d) => self.raw_text(d),
ItemKind::MacroItem(m) => self.macro_call(m),
// Printed exactly like the statement it looks like; the call's own
// argument group supplies the line breaks.
ItemKind::ElabTask(e) => concat(vec![self.expr(e), text(";")]),
ItemKind::Import(paths) => text(format!("import {};", join_paths(paths))),
ItemKind::Export(e) => Self::export(e),
ItemKind::Timeunit(t) => text(format!("{t};")),
ItemKind::Typedef(t) => self.typedef(t),
ItemKind::ParamDecl(d) => concat(vec![self.param_decl(d, align), text(";")]),
ItemKind::DataDecl(d) => concat(vec![self.data_decl(d), text(";")]),
ItemKind::PortDecl(d) => concat(vec![self.port_decl(d), text(";")]),
ItemKind::ContAssign(a) => self.cont_assign(a),
ItemKind::Always { kw, stmt } => self.stmt_as_body(text(kw.clone()), stmt),
ItemKind::Initial(s) => self.stmt_as_body(text("initial"), s),
ItemKind::Final(s) => self.stmt_as_body(text("final"), s),
ItemKind::Instantiation(inst) => self.instantiation(inst, depth),
ItemKind::Bind(b) => self.bind(b, depth),
ItemKind::GateInstantiation(g) => self.gate_instantiation(g),
ItemKind::Genvar(names) => text(format!("genvar {};", join_names(names))),
ItemKind::GenerateRegion { items, dangling } => {
let mut body = Vec::new();
if !items.is_empty() {
body.push(Doc::HardLine);
body.extend(self.item_seq(items, depth + 1));
}
body.extend(self.dangling(dangling));
concat(vec![text("generate"), indent(body), Doc::HardLine, text("endgenerate")])
}
// A bare `begin … end` standing where an item belongs. Never
// reached from `format_source`: the parser records a diagnostic
// beside it and a file with a diagnostic is emitted unchanged.
// The arm exists so a range or tolerant printer has nothing to
// invent — the block prints the way a generate block's does,
// without the separator `gen_block` puts in front of the keyword
// for the header it usually hangs off.
ItemKind::GenBlock(b) => {
let mut docs = Vec::new();
if self.inline_comments(&b.before_kw, &mut docs) {
docs.push(Doc::HardLine);
}
self.begin_block(&mut docs, b, depth);
concat(docs)
}
ItemKind::GenIf(g) => self.gen_if(g, depth),
ItemKind::GenFor(g) => self.gen_for(g, depth),
ItemKind::GenCase(g) => self.gen_case(g, depth),
ItemKind::Function(f) => self.function(f),
ItemKind::Task(t) => self.task(t),
ItemKind::Let(l) => self.let_decl(l),
ItemKind::Class(c) => self.class(c, depth),
ItemKind::Modport(decls) => self.modport(decls),
ItemKind::Clocking(c) => self.clocking(c),
ItemKind::Constraint(c) => self.constraint(c),
ItemKind::Covergroup(c) => self.covergroup(c),
ItemKind::PropSeqDecl(d) => self.prop_seq_decl(d),
ItemKind::Assertion(a) => self.assertion(a),
ItemKind::DefaultDisable(d) => self.default_disable(d),
ItemKind::Verbatim(raw) => self.raw_text(raw),
// A null item is its `;`. Whether it keeps the previous item's
// line or takes one of its own is `item_seq`'s call.
ItemKind::Empty => text(";"),
ItemKind::Defparam(pairs) => {
let parts: Vec<Doc> = pairs
.iter()
.map(|(l, r)| concat(vec![self.expr(l), text(" = "), self.expr(r)]))
.collect();
let mut docs = vec![text("defparam ")];
docs.extend(join(parts, text(", ")));
docs.push(text(";"));
concat(docs)
}
// `alias a = b = c;` — one line, one space around every `=`, the
// spacing every other assignment-shaped item already uses.
ItemKind::Alias(nets) => {
let mut docs = vec![text("alias ")];
docs.extend(join(nets.iter().map(|n| self.expr(n)).collect(), text(" = ")));
docs.push(text(";"));
concat(docs)
}
}
}
/// `package p;` — the two comment slots a package header owns.
fn package_head(
&self,
kw: &str,
before_name: &[Comment],
name: &str,
before_semi: &[Comment],
) -> Doc {
let mut docs = vec![text(kw.to_string())];
if before_name.is_empty() {
docs.push(text(" "));
} else {
self.inline_comments_spaced(before_name, &mut docs);
}
docs.push(text(named(name)));
docs.push(self.semi(before_semi));
concat(docs)
}
fn cont_assign(&self, a: &ContAssign) -> Doc {
// `assign /*c*/ y = x;` — the first pair's own leading comments were
// 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(delay) = &a.delay {
docs.push(text("#"));
self.slot_comments(&a.after_hash, &mut docs);
docs.push(self.expr(delay));
match a.after_delay.is_empty() {
true => docs.push(text(" ")),
false => self.inline_comments_spaced(&a.after_delay, &mut docs),
}
}
let items: Vec<ListItem> = a
.assigns
.iter()
.enumerate()
.map(|(i, p)| {
// The first pair's leading comments are printed above, after
// the keyword; printing them twice would duplicate them.
let skip = usize::from(i == 0) * lead.len();
let mut item = ListItem::from_meta(&p.meta, self.assign_pair(p));
item.leading.drain(..skip.min(item.leading.len()));
item
})
.collect();
if items.len() == 1 {
let item = items.into_iter().next().unwrap();
docs.push(item.doc);
// The last pair's separator is the `;`, so its `before_sep`
// comments print in front of it.
if self.inline_comments(&item.before_sep, &mut docs) {
docs.push(Doc::HardLine);
}
docs.push(text(";"));
if let Some(tr) = item.trailing {
docs.push(text(" "));
docs.push(self.comment(&tr));
}
} else {
let last = items.len() - 1;
let mut inner = Vec::new();
for (i, item) in items.into_iter().enumerate() {
inner.push(item.doc);
if self.inline_comments(&item.before_sep, &mut inner) {
inner.push(Doc::HardLine);
}
if i < last {
inner.push(text(","));
} else {
inner.push(text(";"));
}
if let Some(tr) = item.trailing {
inner.push(text(" "));
inner.push(self.comment(&tr));
if i < last {
inner.push(Doc::HardLine);
}
} else if i < last {
inner.push(Doc::Line);
}
}
docs.push(group(vec![indent(inner)]));
}
concat(docs)
}
/// `lhs = rhs`, with any comments written after the `=` printed on the
/// `=`'s line so they stay on that side of the value.
fn assign_pair(&self, p: &AssignPair) -> Doc {
// `y /*c*/ =` — the comments stay on the operator's left.
let mut head = vec![self.expr(&p.lhs)];
self.slot_comments(&p.op_comments, &mut head);
head.push(text(if p.op_comments.is_empty() { " =" } else { "=" }));
if p.rhs_comments.is_empty() {
head.push(self.assign_rhs(self.expr(&p.rhs)));
return group(head);
}
let mut inner = Vec::new();
let ends_line = self.inline_comments(&p.rhs_comments, &mut inner);
inner.push(if ends_line { Doc::HardLine } else { text(" ") });
inner.push(self.expr(&p.rhs));
head.push(indent(inner));
group(head)
}
fn gen_if(&self, g: &GenIf, depth: usize) -> Doc {
let mut docs = vec![text("if "), self.parens(&g.cond)];
let mut cuddle = self.gen_block(&mut docs, &g.then, depth);
let mut els = &g.els;
while let Some(e) = els {
match e.as_ref() {
GenElse::If(_meta, gi) => {
if cuddle {
docs.push(text(" else if "));
} else {
docs.push(Doc::HardLine);
docs.push(text("else if "));
}
docs.push(self.parens(&gi.cond));
cuddle = self.gen_block(&mut docs, &gi.then, depth);
els = &gi.els;
}
GenElse::Block(b) => {
if cuddle {
docs.push(text(" else"));
} else {
docs.push(Doc::HardLine);
docs.push(text("else"));
}
self.gen_block(&mut docs, b, depth);
break;
}
}
}
concat(docs)
}
/// Append a generate block; returns true if it ended with `end` (so
/// `else` can cuddle).
fn gen_block(&self, docs: &mut Vec<Doc>, b: &GenBlock, depth: usize) -> bool {
if b.is_block {
if b.before_kw.is_empty() {
docs.push(text(" "));
} else {
self.inline_comments_spaced(&b.before_kw, docs);
}
self.begin_block(docs, b, depth);
true
} else {
let item = &b.items[0];
docs.push(group(vec![indent(vec![Doc::Line, self.item(item, depth + 1)])]));
false
}
}
/// A generate block's `begin … end` and everything between, from the
/// keyword on — the separator in front of it is the caller's, because a
/// block hanging off an `if (…)` header needs one and a block standing on
/// its own as an item ([`ItemKind::GenBlock`]) does not.
fn begin_block(&self, docs: &mut Vec<Doc>, b: &GenBlock, depth: usize) {
docs.push(text("begin"));
if let Some(l) = &b.label {
self.slot_comments(&b.before_colon, docs);
docs.push(text(if b.before_colon.is_empty() { " :" } else { ":" }));
if b.after_colon.is_empty() {
docs.push(text(" "));
} else {
self.inline_comments_spaced(&b.after_colon, docs);
}
docs.push(text(named(l)));
}
let mut body = Vec::new();
if !b.items.is_empty() {
body.push(Doc::HardLine);
body.extend(self.item_seq(&b.items, depth + 1));
}
body.extend(self.dangling(&b.dangling));
docs.push(indent(body));
docs.push(Doc::HardLine);
docs.push(self.closing_labeled("end", &b.end_label, &b.end_label_comments));
}
fn gen_for(&self, g: &GenFor, depth: usize) -> Doc {
let mut header = Vec::new();
self.for_open(&g.comments, &mut header);
if g.init_genvar {
header.push(text("genvar"));
if g.after_genvar.is_empty() {
header.push(text(" "));
} else {
self.inline_comments_spaced(&g.after_genvar, &mut header);
}
}
self.simple_assign(&g.init, &mut header);
self.for_semi(&g.comments.before_first_semi, &g.comments.after_first_semi, &mut header);
header.push(self.expr(&g.cond));
self.for_semi(&g.comments.before_second_semi, &g.comments.after_second_semi, &mut header);
header.push(self.for_step(&g.step));
self.slot_comments(&g.comments.before_close, &mut header);
header.push(text(")"));
let mut docs = vec![concat(header)];
self.gen_block(&mut docs, &g.body, depth);
concat(docs)
}
fn gen_case(&self, g: &GenCase, depth: usize) -> Doc {
let mut docs = vec![text("case "), self.parens(&g.expr)];
let mut body = Vec::new();
for item in &g.items {
body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
body.extend(self.leading(&item.meta));
let mut item_docs = vec![self.case_labels(&item.labels, &item.before_colon, item.span)];
self.gen_block(&mut item_docs, &item.body, depth + 1);
body.push(concat(item_docs));
body.extend(self.trailing(&item.meta));
}
body.extend(self.dangling(&g.dangling));
docs.push(indent(body));
docs.push(Doc::HardLine);
docs.push(text("endcase"));
concat(docs)
}
}