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

495 lines
21 KiB
Rust

//! Instantiations: a module instance with its parameter overrides and
//! named or ordered connections, the alignment of a connection list,
//! `bind`, and gate instances.
//!
//! A connection's `(` is the one column an instance list aligns on; the
//! cells, the column spec and the planner all live here, so a change to
//! how connections align touches one file.
use crate::align::{self, Align, ColSpec, Row};
use crate::doc::*;
use vlog_parser::ast::*;
use super::comment::is_line_comment;
use super::list::ListItem;
use super::{join_names, name_doc, named, Fmt};
/// A named connection's one alignment column: the `(` of the value. It is
/// written tight when flush (`.clk(clk)`) and one space off the name when
/// aligned (`.clk (clk)`), which is Verible's spelling of both.
const CONNECTION_COLS: &[ColSpec] = &[ColSpec { flush: 0, min: 1 }];
impl<'a> Fmt<'a> {
pub(super) fn instantiation(&self, inst: &Instantiation, depth: usize) -> Doc {
let mut docs = vec![name_doc(&inst.module)];
let mut on_fresh_line = self.bracket_comments(&inst.param_comments, &mut docs, false);
// An empty `#()` was written by hand and is reprinted as `#()`; a
// missing one stays missing.
if let Some(params) = &inst.params {
let items: Vec<ListItem> = params
.iter()
.map(|c| {
self.list_elem(c, |c| {
ListItem::from_meta(&c.meta, self.connection(c)).with_comma(c.comma)
})
})
.collect();
let items = self.list_entries(items, &inst.param_directives);
let broken = !inst.param_directives.is_empty()
|| holds_verbatim_value(params)
|| self.style_breaks(params.iter().any(is_named));
docs.push(text(if on_fresh_line { "#" } else { " #" }));
self.slot_comments(&inst.after_hash, &mut docs);
docs.push(self.header_list("(", items, &[], ")", broken));
on_fresh_line = false;
}
if let [only] = &inst.instances[..] {
// The common case: no extra indent level, so a connection list
// that breaks lines up under the instance itself. The comments
// before the instance name print here — the multi-instance branch
// below has `leading` for them, and this one had nowhere at all.
if !self.bracket_comments(&only.meta.leading, &mut docs, on_fresh_line) {
docs.push(text(" "));
}
docs.push(self.instance(only, depth));
} else {
if !on_fresh_line {
docs.push(text(" "));
}
// Several instances share one declaration: keep them on one line
// if they fit, otherwise one per line, indented under the head.
let last = inst.instances.len() - 1;
let mut inner = Vec::new();
for (i, instance) in inst.instances.iter().enumerate() {
inner.extend(self.leading(&instance.meta));
inner.push(self.instance(instance, depth + 1));
if self.inline_comments(&instance.meta.before_sep, &mut inner) {
inner.push(Doc::HardLine);
}
if i < last {
inner.push(text(","));
}
if let Some(tr) = &instance.meta.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)]));
}
docs.push(self.semi(&inst.before_semi));
concat(docs)
}
/// One instance of a module instantiation: `u0 [3:0] (.a(x))`.
fn instance(&self, instance: &Instance, depth: usize) -> Doc {
let mut docs = vec![name_doc(&instance.name)];
if !instance.dims.is_empty() {
if instance.dims[0].comments.opens_clean() {
docs.push(text(" "));
}
for d in &instance.dims {
docs.push(self.dim(d));
}
}
if !self.bracket_comments(&instance.conn_comments, &mut docs, false) {
docs.push(text(" "));
}
docs.push(self.connections(&instance.conns, &instance.conn_directives, depth + 1));
concat(docs)
}
/// A connection list, with the `` `ifdef``-style directives written between
/// its entries merged back into source order. A list holding one is laid
/// out broken: a directive runs to end of line, so nothing may share it.
fn connections(&self, conns: &Connections, directives: &[ListDirective], depth: usize) -> Doc {
let mut broken = !directives.is_empty();
let items: Vec<ListItem> = match conns {
Connections::Named(list) => {
let aligns = self.connection_aligns(list, directives, self.list_depth(depth));
broken |= aligns.iter().any(Option::is_some)
|| holds_verbatim_value(list)
|| self.style_breaks(!list.is_empty());
list.iter()
.zip(&aligns)
.map(|(c, a)| {
self.list_elem(c, |c| {
ListItem::from_meta(&c.meta, self.connection_aligned(c, a.as_ref()))
.with_comma(c.comma)
})
})
.collect()
}
Connections::Ordered(list) => list
.iter()
.map(|c| {
self.list_elem(c, |c| {
let d = match &c.expr {
Some(e) => self.expr(e),
None => text(""),
};
ListItem::from_meta(&c.meta, d).with_comma(c.comma)
})
})
.collect(),
};
let items = self.list_entries(items, directives);
self.header_list("(", items, &[], ")", broken)
}
/// The alignment plan for an instance's named connection list.
fn connection_aligns(
&self,
conns: &[ListElem<Connection>],
directives: &[ListDirective],
depth: usize,
) -> Vec<Option<Align>> {
let rows: Vec<Option<Row>> = conns
.iter()
.map(|c| {
// An error element has no cells to align, so it has no row.
let c = c.ok()?;
let paren = self.open_paren_offset(c.name_span.end)?;
Self::row_of(&self.connection_cells(c), vec![paren], usize::from(c.comma))
})
.collect();
let breaks = Self::list_breaks(conns.iter().map(|c| c.ok().map(|c| &c.meta)), directives);
self.align_groups(&rows, &breaks, CONNECTION_COLS, depth)
}
/// Byte offset of the `(` opening a named connection's value.
fn open_paren_offset(&self, after_name: u32) -> Option<u32> {
let bytes = self.src.as_bytes();
let mut pos = after_name as usize;
while matches!(bytes.get(pos), Some(b' ' | b'\t' | b'\r' | b'\n')) {
pos += 1;
}
(bytes.get(pos) == Some(&b'(')).then_some(pos as u32)
}
pub(super) fn connection(&self, c: &Connection) -> Doc {
self.connection_aligned(c, None)
}
fn connection_aligned(&self, c: &Connection, align: Option<&Align>) -> Doc {
align::render(&self.connection_cells(c), CONNECTION_COLS, align)
}
/// A named connection split at its one alignment column, the `(` of the
/// value: `.data_i` and `(bus[7:0])`. Everything else — `.*`, an implicit
/// `.clk`, a positional value, a connection with comments inside its own
/// parens — is one cell and never joins a group.
fn connection_cells(&self, c: &Connection) -> Vec<Doc> {
let plain = || vec![self.connection_plain(c)];
// An attributed connection is one cell: the attribute widens the row
// by an amount no other row shares, so it never joins a group —
// `list_breaks` already ends the group at it, as it does at a
// compiler directive.
if c.name.is_empty() || c.name == "*" || !c.meta.attrs.is_empty() {
return plain();
}
// A comment written in one of the connection's own gaps makes the row
// a width no other row shares, so it never joins an alignment group.
if !c.after_dot.is_empty() || !c.before_open.is_empty() || !c.after_open.is_empty() {
return plain();
}
let Some(e) = &c.expr else { return plain() };
// A verbatim conditional region is many lines of bytes; a row that
// wide shares its width with nothing, and the `)` after it has a line
// break of its own to keep (`Fmt::verbatim_value_breaks`).
if matches!(e.kind, ExprKind::Empty(_) | ExprKind::Verbatim(_)) {
return plain();
}
let mut inner = vec![Doc::SoftLine, self.expr(e)];
let ends_line = self.inline_comments(&c.close_comments, &mut inner);
let close = if ends_line { Doc::HardLine } else { Doc::SoftLine };
vec![
text(format!(".{}", named(&c.name))),
concat(vec![text("("), group(vec![indent(inner), close]), text(")")]),
]
}
/// True when a connection's value is a **verbatim conditional region**
/// the source ended a line after — which it always does when the region
/// ends on a `` `endif ``.
///
/// A line-oriented directive runs to the end of its line (`lexer.rs`'s
/// `is_line_directive`), so a `)` printed after one on the same line is
/// swallowed into the directive's own token — a rewrite the safety net
/// refuses. The break is read back from `src` rather than stored, for the
/// reason [`Fmt::glued_null_item`] gives, and is a fixed point by
/// construction: the break printed here reads back as the same break.
fn verbatim_value_breaks(&self, c: &Connection) -> bool {
let Some(Expr { kind: ExprKind::Verbatim(raw), .. }) = &c.expr else { return false };
self.src
.get(raw.span.end as usize..c.span.end as usize)
.is_some_and(|gap| gap.contains('\n'))
}
fn connection_plain(&self, c: &Connection) -> Doc {
// `(* async *) .async_data_o (x)`: the attributes stay in front of
// the connection, on its line (corpus
// `common_cells/src/cdc_fifo_gray.sv:140`).
if !c.meta.attrs.is_empty() {
let mut docs = Vec::new();
for attr in &c.meta.attrs {
docs.push(self.raw_inline(attr));
docs.push(text(" "));
}
docs.push(self.connection_bare(c));
return concat(docs);
}
self.connection_bare(c)
}
/// A connection without its attributes: `.name(expr)`, `.name()`,
/// `.name`, `.*`, or a positional value.
fn connection_bare(&self, c: &Connection) -> Doc {
if c.name == "*" {
if c.after_dot.is_empty() {
return text(".*");
}
let mut docs = vec![text(".")];
self.slot_comments(&c.after_dot, &mut docs);
docs.push(text("*"));
return concat(docs);
}
if c.name.is_empty() {
// Positional parameter value.
return match &c.expr {
Some(e) => self.expr(e),
None => text(""),
};
}
// `.` then the name, with whatever the source wrote between them.
let head = |f: &Self| {
let mut docs = vec![text(".")];
f.slot_comments(&c.after_dot, &mut docs);
docs.push(text(named(&c.name)));
docs
};
// …and the `(` that follows the name, with its two gaps.
let open = |f: &Self, docs: &mut Vec<Doc>| {
f.slot_comments(&c.before_open, docs);
docs.push(text("("));
f.slot_comments(&c.after_open, docs);
};
match &c.expr {
None => concat(head(self)),
Some(Expr { kind: ExprKind::Empty(comments), .. }) => {
let mut docs = head(self);
open(self, &mut docs);
let mut ends_line = false;
for cm in comments {
if ends_line {
docs.push(Doc::HardLine);
}
docs.push(self.comment(cm));
ends_line = is_line_comment(&cm.text);
}
if ends_line {
docs.push(Doc::HardLine);
}
docs.push(text(")"));
concat(docs)
}
Some(e) => {
let mut inner = vec![Doc::SoftLine, self.expr(e)];
let ends_line = self.inline_comments(&c.close_comments, &mut inner);
let broke = ends_line || self.verbatim_value_breaks(c);
let close = if broke { Doc::HardLine } else { Doc::SoftLine };
let mut docs = head(self);
open(self, &mut docs);
docs.push(group(vec![indent(inner), close]));
docs.push(text(")"));
concat(docs)
}
}
}
/// `bind <target> [: u_a, u_b] <instantiation>`: the head is one flat run
/// of names, and everything after it is laid out exactly as the same
/// instantiation written on its own would be.
pub(super) fn bind(&self, b: &BindDirective, depth: usize) -> Doc {
// The comments around the head have no node of their own; each prints
// back between the two tokens it was written between.
let mut docs = vec![text("bind")];
self.inline_comments_spaced(&b.target_comments, &mut docs);
// One segment at a time, for the reason `scope_prefix` prints a `::`
// chain that way: `named` supplies the space an escaped segment needs
// to terminate, and a joined string could not carry it.
for (i, seg) in b.target.iter().enumerate() {
if i > 0 {
docs.push(text("."));
}
docs.push(text(named(&seg.name)));
if let Some(index) = &seg.index {
docs.push(text("["));
docs.push(self.expr_compact(index));
docs.push(text("]"));
}
}
if !b.instances.is_empty() {
docs.push(text(format!(" : {}", join_names(&b.instances))));
}
self.inline_comments_spaced(&b.module_comments, &mut docs);
docs.push(self.instantiation(&b.inst, depth));
concat(docs)
}
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(drive_strength(self, s));
}
if !g.delay.is_empty() {
// The gap in front of the `#` is a space unless the source wrote
// a comment in it, exactly as a net delay's `before_hash` is.
match g.before_hash.is_empty() {
true => docs.push(text(" ")),
false => self.inline_comments_spaced(&g.before_hash, &mut docs),
}
docs.push(text("#"));
self.slot_comments(&g.after_hash, &mut docs);
}
if let [delay] = g.delay.as_slice() {
// One value prints itself, brackets and all (`#5`, `#(5)`).
docs.push(self.expr(&delay.expr));
} else if !g.delay.is_empty() {
// `#(rise, fall[, turn-off])` — the parens and the commas are the
// list's own, so the comments written around them are too.
docs.push(text("("));
for (i, d) in g.delay.iter().enumerate() {
if i > 0 {
docs.push(text(","));
match d.leading.is_empty() {
true => docs.push(text(" ")),
false => self.inline_comments_spaced(&d.leading, &mut docs),
}
} else {
self.slot_comments(&d.leading, &mut docs);
}
docs.push(self.expr(&d.expr));
self.slot_comments(&d.trailing, &mut docs);
}
docs.push(text(")"));
}
let last = g.instances.len().saturating_sub(1);
// True once a trailing comment has ended the previous instance's line:
// the next instance then starts on a fresh, indented line, and the
// space that normally separates it from the `,` is not written.
let mut broke = false;
for (i, inst) in g.instances.iter().enumerate() {
// What stands between the delay (or the previous instance's `,`)
// and this instance's name — a space when nothing does.
match (broke, inst.meta.leading.is_empty()) {
(true, true) => {}
(false, true) => docs.push(text(" ")),
(_, false) => self.inline_comments_spaced(&inst.meta.leading, &mut docs),
}
broke = false;
if let Some(name) = &inst.name {
docs.push(name_doc(name));
match inst.before_args.is_empty() {
true => docs.push(text(" ")),
false => self.inline_comments_spaced(&inst.before_args, &mut docs),
}
}
docs.push(self.expr_list("(", &inst.args, ")"));
if i == last {
continue;
}
// Comments written between the instance and its `,` print on the
// instance's side of it, as every list element's do.
if self.inline_comments(&inst.meta.before_sep, &mut docs) {
docs.push(Doc::HardLine);
}
docs.push(text(","));
if let Some(tr) = &inst.meta.trailing {
docs.push(text(" "));
docs.push(self.comment(tr));
// A line comment ends the line (a `// p` would otherwise
// swallow the next instance on re-lex — §45's QA); the next
// instance continues one level in. A block comment stays
// inline, as the case table for this slot expects.
if is_line_comment(&tr.text) {
docs.push(indent(vec![Doc::HardLine]));
broke = true;
}
}
}
docs.push(self.semi(&g.before_semi));
concat(docs)
}
}
/// True when any entry of a connection or override list carries a
/// **multi-line verbatim value** — a conditional region
/// ([`ExprKind::Verbatim`]).
///
/// Such a value brings its own line breaks, which `Doc::Inline` copies
/// through without telling the enclosing group; without this the list would
/// be measured as one short line and flattened around a value that is
/// twenty lines tall. It is exactly the reason a list holding a
/// [`ListDirective`] is broken, for exactly the same construct.
fn holds_verbatim_value(list: &[ListElem<Connection>]) -> bool {
list.iter().filter_map(ListElem::ok).any(|c| match &c.expr {
Some(Expr { kind: ExprKind::Verbatim(raw), .. }) => raw.text.contains('\n'),
_ => false,
})
}
/// Whether a parameter override names what it sets (`.Width(8)`) rather
/// than giving it by position (`#(8)`): only a named list is one the style's
/// `OnePerLine` breaks.
fn is_named(c: &ListElem<Connection>) -> bool {
c.ok().is_some_and(|c| !c.name_span.is_empty())
}
/// `(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)
}