Files
lucisv/crates/vlog_formatter/src/format/stmt.rs
T
Guoliang ChenandClaude Mythos 5.2 80017a59f2
release / build-and-publish (push) Successful in 5m22s
Release 0.65.5: named formatting styles
TODO §71.5. One setting picks a house layout — [format] style in
lucisv.toml, --style, the lucisv.format.style drop-down, the server and MCP:
lucisv (default), google, lowrisc, ansi, microsoft, nxp, and auto. Seven
layout rules (indent, width, begin placement, else placement, else after a
labelled end, one-per-line lists, list indent, alignment), one row per style
in one table in crates/vlog_formatter/src/style.rs. google and lowrisc follow
those published guides; ansi, microsoft and nxp are lucisv's guesses and say
so. auto formats with each preset and keeps the result that changes the
fewest lines (crates/vlog_formatter/src/auto.rs); the language server
remembers each document's preset (lucisv_server/src/auto_style.rs) so
selection and on-type formatting do not repeat the search. The style is part
of the format cache key.

Proof: default output byte-identical to 0.65.4 on 4 921 files (corpus +
OpenTitan hw) against an independently rebuilt 0.65.4; every style formatted
three times over the same files with no verification error, crash, token or
comment difference (independent lexer) or second-run change. verify.rs is
untouched.

Dev (three rounds), QA (two rounds, pass with findings) and lead review are
in docs/features/format-styles/README.md. Three one-line calls were added to
lucisv_server/src/server/notification.rs for the memory's invalidation.
TODO.md files the pre-existing bugs QA met on the way.

Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.65.5) and
editors/vscode/CHANGELOG.md.

Gates: tools/gates.sh PASS on this tree; vlog_formatter 376/0,
lucisv_server 1996/0, corpus 814/6.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 07:03:20 -08:00

656 lines
28 KiB
Rust

//! Statements: the `begin … end` block, a statement as the body of a
//! header (a cuddled block or an indented line), the dispatch from
//! `StmtKind` to its layout, `case` items, and the
//! timing controls and sensitivity lists that head an `always` block or
//! a clocking event.
//!
//! `stmt_kind` is a dispatch table over `StmtKind` — one arm per
//! statement form — and stays whole; `case` has a layout of its own in the
//! functions after it, `if` in `branch.rs`.
use crate::doc::*;
use vlog_parser::ast::*;
use vlog_parser::span::TextRange;
use vlog_parser::token::Comment;
use super::branch::before_keyword;
use super::comment::is_line_comment;
use super::{join_paths, named, skip_trivia, Fmt};
use crate::style::Placement;
/// The pieces of a `begin … end` block a printer needs, gathered so the
/// two spellings (a statement, and a body cuddled onto a header) pass one
/// argument instead of six.
struct BlockDoc<'a> {
label_comments: &'a LabelComments,
label: &'a Option<String>,
stmts: &'a [Stmt],
dangling: &'a [Comment],
end_label_comments: &'a LabelComments,
end_label: &'a Option<String>,
}
impl<'a> Fmt<'a> {
fn stmt(&self, s: &Stmt) -> Doc {
concat(self.stmt_docs(s))
}
/// One statement: its leading comments, then — unless a verbatim region is
/// already emitting its bytes — its code and trailing comment. The
/// statement twin of `Fmt::item_docs`, with the same two rules: comments
/// written before the `off` fence are still emitted, because comments are
/// never dropped, and a statement the region swallowed emits nothing.
fn stmt_docs(&self, s: &Stmt) -> Vec<Doc> {
// A verbatim run whose first statement carries no leading comment opens
// at the statement's own code; there is no comment to emit it from.
if let Some(region) = self.opens_at(s.span.start as usize) {
return vec![self.verbatim(region)];
}
if self.is_verbatim(s.span) {
// The statement's own bytes, its attributes included, are emitted
// verbatim by the fence; only its leading comments are ours.
let mut docs = self.leading_comments(&s.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;
}
vec![self.with_meta(&s.meta, self.stmt_kind(&s.kind, &s.before_semi))]
}
/// Sequence of statements at one indent level, preserving single blank
/// lines between them. A statement a fenced region swallowed emits
/// nothing, and contributes no separator either.
pub(super) fn stmt_seq(&self, stmts: &[Stmt]) -> Vec<Doc> {
let mut docs = Vec::new();
for s in stmts {
let stmt_docs = self.stmt_docs(s);
if stmt_docs.is_empty() {
continue;
}
if !docs.is_empty() {
docs.push(if s.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
}
docs.extend(stmt_docs);
}
docs
}
/// Prefix (e.g. `always_ff`, `if (...)`) followed by a body statement:
/// blocks cuddle onto the prefix line, single statements go on the same
/// line if they fit, otherwise indented on the next line.
pub(super) fn stmt_as_body(&self, prefix: Doc, s: &Stmt) -> Doc {
self.stmt_as_body_from(prefix, s, 0)
}
/// The same, skipping the body's first `skip` leading comments because
/// `prefix` already printed them inside its parentheses. See
/// [`Fmt::header_parens`].
pub(super) fn stmt_as_body_from(&self, prefix: Doc, s: &Stmt, skip: usize) -> Doc {
self.body_after(prefix, s, skip, self.cfg.style.begin)
}
/// The layout behind both: a block's `begin` goes where `begin` says —
/// the style's choice for a statement header, always the label's line
/// for a `case` item.
fn body_after(&self, prefix: Doc, s: &Stmt, skip: usize, begin: Placement) -> Doc {
match &s.kind {
StmtKind::Block {
label_comments,
label,
stmts,
dangling,
end_label_comments,
end_label,
..
} => {
let mut docs = vec![prefix, before_keyword(begin)];
docs.extend(self.leading_from(&s.meta, skip));
docs.push(self.block_doc(BlockDoc {
label_comments,
label,
stmts,
dangling,
end_label_comments,
end_label,
}));
docs.extend(self.trailing(&s.meta));
concat(docs)
}
StmtKind::Timing { control, stmt: Some(inner) } => {
// e.g. `always @(posedge clk) begin ... end`
let mut docs = vec![prefix, text(" ")];
docs.extend(self.leading_from(&s.meta, skip));
let control_doc = self.timing_control(control);
docs.push(self.body_after(control_doc, inner, 0, begin));
docs.extend(self.trailing(&s.meta));
concat(docs)
}
// The same three parts `stmt` prints, with the skip applied.
_ => {
let mut body = self.leading_from(&s.meta, skip);
body.push(self.stmt_kind(&s.kind, &s.before_semi));
body.extend(self.trailing(&s.meta));
group(vec![prefix, indent(vec![Doc::Line, concat(body)])])
}
}
}
fn block_doc(&self, b: BlockDoc<'_>) -> Doc {
let mut docs = vec![text("begin")];
self.label_tail(b.label, b.label_comments, &mut docs);
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));
docs.push(indent(body));
docs.push(Doc::HardLine);
docs.push(self.closing_labeled("end", b.end_label, b.end_label_comments));
concat(docs)
}
fn timing_control(&self, tc: &TimingControl) -> Doc {
match tc {
TimingControl::Delay { after_hash, expr } => {
let mut docs = vec![text("#")];
self.slot_comments(after_hash, &mut docs);
docs.push(self.expr(expr));
concat(docs)
}
TimingControl::Event(sens) => self.sens_list(sens),
}
}
pub(super) fn sens_list(&self, sens: &SensList) -> Doc {
match sens {
// Written without parens, printed without parens: `@ev`,
// `@a.b` — inventing a `( ... )` changes the token stream.
SensList::Bare { expr, after_at } => {
let mut docs = vec![text("@")];
self.slot_comments(after_at, &mut docs);
docs.push(self.expr(expr));
concat(docs)
}
SensList::Star { before, after } => {
if before.is_empty() && after.is_empty() {
return text("@(*)");
}
// Comments written inside the parens stay inside them, on the
// side of the `*` they were written on.
let mut inner = Vec::new();
if before.is_empty() {
// `(*` directly followed by anything but `)` lexes as an
// attribute instance, so keep the `*` off the paren.
inner.push(text(" "));
}
for c in before {
inner.push(self.comment(c));
inner.push(if is_line_comment(&c.text) { Doc::HardLine } else { text(" ") });
}
inner.push(text("*"));
for c in after {
inner.push(text(" "));
inner.push(self.comment(c));
if is_line_comment(&c.text) {
inner.push(Doc::HardLine);
}
}
concat(vec![text("@("), indent(inner), text(")")])
}
SensList::List { items, after_at } => {
// Each separator is printed as it was written: `,` and `or`
// mean the same thing but are different tokens, and rewriting
// one as the other is a token change the safety net rejects.
let mut parts: Vec<Doc> = Vec::new();
for i in items {
match i.sep {
Some(SensSep::Comma) => parts.push(text(", ")),
Some(SensSep::Or) => parts.push(text(" or ")),
None => {}
}
for c in &i.meta.leading {
parts.push(self.comment(c));
parts.push(if is_line_comment(&c.text) {
Doc::HardLine
} else {
text(" ")
});
}
if let Some(e) = &i.edge {
parts.push(text(e.clone()));
if i.after_edge.is_empty() {
parts.push(text(" "));
} else {
self.inline_comments_spaced(&i.after_edge, &mut parts);
}
}
parts.push(self.expr(&i.expr));
// `posedge clk iff enable` — the gate belongs to this
// term, so it prints before the separator, not after it.
if let Some(iff) = &i.iff {
parts.push(text(" iff "));
parts.push(self.expr(iff));
}
if self.inline_comments(&i.meta.before_sep, &mut parts) {
parts.push(Doc::HardLine);
}
}
let mut docs = vec![text("@")];
self.slot_comments(after_at, &mut docs);
docs.push(text("("));
docs.push(group(vec![indent(vec![Doc::SoftLine, concat(parts)]), Doc::SoftLine]));
docs.push(text(")"));
concat(docs)
}
}
}
/// One arm per `StmtKind`. A dispatch table over the enum, so it stays
/// whole past the 150-line mark: the forms that grew a layout of their
/// own (`if`, `case`) are the functions after it, and every remaining
/// arm is a few lines of spelling.
fn stmt_kind(&self, kind: &StmtKind, before_semi: &[Comment]) -> Doc {
match kind {
StmtKind::Block {
label_comments,
label,
stmts,
dangling,
end_label_comments,
end_label,
..
} => self.block_doc(BlockDoc {
label_comments,
label,
stmts,
dangling,
end_label_comments,
end_label,
}),
StmtKind::ForkJoin {
label_comments,
label,
join_kw,
stmts,
dangling,
end_label_comments,
end_label,
..
} => {
let mut docs = vec![text("fork")];
self.label_tail(label, label_comments, &mut docs);
let mut body = Vec::new();
if !stmts.is_empty() {
body.push(Doc::HardLine);
body.extend(self.stmt_seq(stmts));
}
body.extend(self.dangling(dangling));
docs.push(indent(body));
docs.push(Doc::HardLine);
docs.push(self.closing_labeled(join_kw, end_label, end_label_comments));
concat(docs)
}
StmtKind::If { qualifier, after_kw, cond, then, else_comments, els } => {
self.if_stmt(qualifier, after_kw, cond, then, else_comments, els)
}
StmtKind::Case { qualifier, kw, after_kw, expr, inside, items, dangling } => {
let mut docs = Vec::new();
if let Some(q) = qualifier {
docs.push(text(format!("{q} ")));
}
self.word_then(kw, after_kw, &mut docs);
let (parens, taken) = match items.first() {
Some(first) => self.header_parens(expr, &first.meta),
None => (self.parens(expr), 0),
};
docs.push(parens);
if *inside {
docs.push(text(" inside"));
}
docs.push(self.case_body(items, dangling, taken));
concat(docs)
}
// `randcase` is a `case` body with weights for labels and no
// selector, so it shares the body layout.
StmtKind::RandCase { items, dangling } => {
concat(vec![text("randcase"), self.case_body(items, dangling, 0)])
}
StmtKind::For { init, cond, step, comments, body } => {
let mut header = Vec::new();
self.for_open(comments, &mut header);
let init_parts: Vec<Doc> = init
.iter()
.map(|fi| {
let mut d = Vec::new();
if let Some(ty) = &fi.ty {
if let Some(t) = self.data_type(ty) {
d.push(t);
if fi.before_name.is_empty() {
d.push(text(" "));
} else {
self.inline_comments_spaced(&fi.before_name, &mut d);
}
}
} else {
self.slot_comments(&fi.before_name, &mut d);
}
self.simple_assign(&fi.assign, &mut d);
concat(d)
})
.collect();
header.extend(join(init_parts, text(", ")));
self.for_semi(&comments.before_first_semi, &comments.after_first_semi, &mut header);
if let Some(c) = cond {
header.push(self.expr(c));
}
self.for_semi(
&comments.before_second_semi,
&comments.after_second_semi,
&mut header,
);
let step_parts: Vec<Doc> = step.iter().map(|s| self.for_step(s)).collect();
header.extend(join(step_parts, text(", ")));
self.slot_comments(&comments.before_close, &mut header);
header.push(text(")"));
self.stmt_as_body(concat(header), body)
}
StmtKind::While { cond, body } => {
let (parens, taken) = self.header_parens(cond, &body.meta);
self.stmt_as_body_from(concat(vec![text("while "), parens]), body, taken)
}
StmtKind::DoWhile { body, cond, comments } => {
let mut docs = vec![text("do")];
match &body.kind {
StmtKind::Block {
label_comments,
label,
stmts,
dangling,
end_label_comments,
end_label,
..
} => {
docs.push(text(" "));
docs.push(self.block_doc(BlockDoc {
label_comments,
label,
stmts,
dangling,
end_label_comments,
end_label,
}));
docs.push(text(" "));
self.word_then("while", &comments.after_kw, &mut docs);
}
_ => {
docs.push(group(vec![indent(vec![Doc::Line, self.stmt(body)])]));
docs.push(Doc::HardLine);
self.word_then("while", &comments.after_kw, &mut docs);
}
}
docs.push(self.header_slots(cond, comments));
docs.push(self.semi(before_semi));
concat(docs)
}
StmtKind::Repeat { count, body } => {
let (parens, taken) = self.header_parens(count, &body.meta);
self.stmt_as_body_from(concat(vec![text("repeat "), parens]), body, taken)
}
StmtKind::Forever { body } => self.stmt_as_body(text("forever"), body),
StmtKind::Foreach { target, vars, var_comments, comments, body } => {
let mut head = vec![text("foreach")];
self.slot_comments(&comments.after_kw, &mut head);
if comments.after_kw.is_empty() {
head.push(text(" "));
}
head.push(text("("));
self.slot_comments(&comments.after_open, &mut head);
head.push(self.expr(target));
head.push(self.foreach_vars(vars, var_comments));
self.slot_comments(&comments.before_close, &mut head);
head.push(text(")"));
self.stmt_as_body(concat(head), body)
}
StmtKind::Assign { lhs, op, op_comments, rhs_comments, timing, rhs } => {
let mut docs = vec![self.expr(lhs)];
// Comments written before the operator print before it, each
// kept on its own side (`x[6:0] /* opcode */ = v;`).
if self.inline_comments(op_comments, &mut docs) {
docs.push(Doc::HardLine);
docs.push(text(op.clone()));
} else {
docs.push(text(format!(" {op}")));
}
let mut rhs_docs = Vec::new();
if let Some(tc) = timing {
rhs_docs.push(self.timing_control(tc));
rhs_docs.push(text(" "));
}
rhs_docs.push(self.expr(rhs));
if rhs_comments.is_empty() {
docs.push(self.assign_rhs(concat(rhs_docs)));
} else {
// As in a continuous assignment: the comments stay on the
// operator's line, and a line comment pushes the value
// onto the next one.
let mut inner = Vec::new();
let ends_line = self.inline_comments(rhs_comments, &mut inner);
inner.push(if ends_line { Doc::HardLine } else { text(" ") });
inner.push(concat(rhs_docs));
docs.push(indent(inner));
}
concat(vec![group(docs), self.semi(before_semi)])
}
StmtKind::ForceRelease { kw, lhs, rhs } => {
let mut docs = vec![text(format!("{kw} ")), self.expr(lhs)];
if let Some(r) = rhs {
docs.push(text(" = "));
docs.push(self.expr(r));
}
docs.push(self.semi(before_semi));
concat(docs)
}
StmtKind::Timing { control, stmt } => {
let control_doc = self.timing_control(control);
match stmt {
Some(s) => self.stmt_as_body(control_doc, s),
None => concat(vec![control_doc, self.semi(before_semi)]),
}
}
StmtKind::Wait { cond, stmt } => match stmt {
Some(s) => {
let (parens, taken) = self.header_parens(cond, &s.meta);
self.stmt_as_body_from(concat(vec![text("wait "), parens]), s, taken)
}
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(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)])
}
StmtKind::PortDecl(d) => concat(vec![self.port_decl(d), self.semi(before_semi)]),
StmtKind::Return { after_kw, expr } => match expr {
Some(e) => {
let mut docs = Vec::new();
self.word_then("return", after_kw, &mut docs);
docs.push(self.expr(e));
docs.push(self.semi(before_semi));
concat(docs)
}
None => concat(vec![text("return"), self.semi(before_semi)]),
},
StmtKind::Break => concat(vec![text("break"), self.semi(before_semi)]),
StmtKind::Continue => concat(vec![text("continue"), self.semi(before_semi)]),
StmtKind::Disable { name, .. } => {
concat(vec![text(format!("disable {}", named(name))), self.semi(before_semi)])
}
StmtKind::WaitFork => concat(vec![text("wait fork"), self.semi(before_semi)]),
StmtKind::Import(paths) => text(format!("import {};", join_paths(paths))),
// A statement label prints tight against its `:`, the way a case
// label does: `check_decode: assert (...)`.
StmtKind::Labeled { name, stmt, .. } => {
concat(vec![text(format!("{}: ", named(name))), self.stmt(stmt)])
}
StmtKind::Directive(d) => self.raw_text(d),
// See `ItemKind::Error`: unreachable from `format_source`, present
// so the match stays total.
StmtKind::Error(d) => self.raw_text(d),
StmtKind::MacroStmt(m) => self.macro_call(m),
// A concurrent assertion: verbatim source, like its item twin.
StmtKind::Verbatim(raw) => self.raw_text(raw),
StmtKind::Assertion(a) => self.assertion(a),
StmtKind::Assert { kw, cond, then, els } => {
let mut docs = vec![text(format!("{kw} ")), self.parens(cond)];
match (then, els) {
(None, None) => docs.push(self.semi(before_semi)),
(Some(t), None) => {
docs.push(group(vec![indent(vec![Doc::Line, self.stmt(t)])]));
}
(None, Some(e)) => {
docs.push(text(" else"));
docs.push(group(vec![indent(vec![Doc::Line, self.stmt(e)])]));
}
(Some(t), Some(e)) => {
docs.push(group(vec![indent(vec![Doc::Line, self.stmt(t)])]));
docs.push(Doc::HardLine);
docs.push(text("else"));
docs.push(group(vec![indent(vec![Doc::Line, self.stmt(e)])]));
}
}
concat(docs)
}
StmtKind::Null => text(";"),
}
}
/// The `A, B:` head of a case item — `default:` when the list is empty.
/// Labels normally share one line; as soon as any of them carries a
/// comment they go one per line, so a comment written between two labels
/// is printed between the same two labels instead of drifting past them.
pub(super) fn case_labels(
&self,
labels: &[ExprItem],
before_colon: &[Comment],
item: TextRange,
) -> Doc {
if labels.is_empty() {
if !self.default_has_colon(item) {
return text("default");
}
let mut docs = vec![text("default")];
self.slot_comments(before_colon, &mut docs);
docs.push(text(":"));
return concat(docs);
}
let plain = labels.iter().all(|l| {
l.meta.leading.is_empty() && l.meta.before_sep.is_empty() && l.meta.trailing.is_none()
});
if plain {
let docs: Vec<Doc> = labels.iter().map(|l| self.expr(&l.expr)).collect();
return concat(vec![concat(join(docs, text(", "))), text(":")]);
}
let last = labels.len() - 1;
let mut docs = Vec::new();
for (i, l) in labels.iter().enumerate() {
if i > 0 {
docs.push(Doc::HardLine);
}
for c in &l.meta.leading {
docs.push(self.comment(c));
docs.push(Doc::HardLine);
}
docs.push(self.expr(&l.expr));
let ends_line = self.inline_comments(&l.meta.before_sep, &mut docs);
if i < last {
if ends_line {
docs.push(Doc::HardLine);
}
docs.push(text(","));
} else if ends_line {
docs.push(Doc::HardLine);
}
if let Some(tr) = &l.meta.trailing {
docs.push(text(" "));
docs.push(self.comment(tr));
if i == last && is_line_comment(&tr.text) {
docs.push(Doc::HardLine);
}
}
}
docs.push(text(":"));
concat(docs)
}
fn case_item(&self, item: &CaseItem) -> Doc {
// `default;` — the colon IEEE 1800 §12.5 makes optional, with a null
// body. The `;` closes the keyword rather than standing as a body of
// its own, so it hugs instead of going through `stmt_as_body`.
if item.labels.is_empty()
&& matches!(item.stmt.kind, StmtKind::Null)
&& is_bare(&item.stmt.meta)
&& !self.default_has_colon(item.span)
{
return text("default;");
}
let labels = self.case_labels(&item.labels, &item.before_colon, item.span);
self.body_after(labels, &item.stmt, 0, Placement::SameLine)
}
/// The items of a `case`/`randcase` body. `skip` is the number of leading
/// comments of the *first* item the `case (...)` header already printed
/// inside its parentheses (see [`Fmt::header_parens`]).
fn case_body(&self, items: &[CaseItem], dangling: &[Comment], skip: usize) -> Doc {
let mut body = Vec::new();
for (i, item) in items.iter().enumerate() {
body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
body.extend(self.leading_from(&item.meta, if i == 0 { skip } else { 0 }));
body.push(self.case_item(item));
body.extend(self.trailing(&item.meta));
}
body.extend(self.dangling(dangling));
concat(vec![indent(body), Doc::HardLine, text("endcase")])
}
/// True when the source wrote the optional `:` after a `default` case
/// label. IEEE 1800 §12.5 makes it optional — `default;` is legal — and
/// the token stream has to come back with exactly what was written.
fn default_has_colon(&self, span: TextRange) -> bool {
let after = span.start as usize + "default".len();
matches!(skip_trivia(self.src, after), Some(i) if self.src.as_bytes()[i] == b':')
}
}
/// True when a node carries no trivia at all, so printing it cannot move a
/// comment anywhere.
fn is_bare(meta: &Meta) -> bool {
meta.leading.is_empty()
&& meta.trailing.is_none()
&& meta.before_sep.is_empty()
&& meta.attrs.is_empty()
}