Files
lucisv/crates/vlog_formatter/src/format.rs
T
lucioandClaude Fable 5 f52beff48f Add item-misc: spaced macro calls, line-aware macro items, `error, elab tasks
Macro invocations with whitespace before the argument list, a bare macro on its own line followed by a declaration, `error/`warning directives, and $error/$fatal/$warning/$info as module/generate items.

Coverage loop round 1, cluster 1: 636 -> 661 / 820 (77.6% -> 80.6%).
Feature README: docs/features/item-misc/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-20 22:54:47 -07:00

2737 lines
110 KiB
Rust

//! Formatting rules: AST → Doc.
//!
//! Style follows Verible's defaults: 2-space indent, 100-column lines,
//! one-element-per-line port/connection lists when a construct does not fit
//! on a single line, cuddled `begin`/`end`.
use crate::align::{self, Align, ColSpec, Row};
use crate::doc::*;
use crate::fence::{self, Region};
use crate::printer::{contains_hard_line, Printer};
use crate::range::{self, Split};
use crate::verify::{
line_starts_inside_string, verify_convergence, verify_equivalence, VerificationError,
};
use vlog_parser::ast::*;
use vlog_parser::span::TextRange;
use vlog_parser::token::Comment;
#[derive(Debug, Clone)]
pub struct Config {
pub max_width: usize,
pub indent_width: usize,
}
impl Default for Config {
fn default() -> Self {
Config { max_width: 100, indent_width: 2 }
}
}
/// An ANSI port's one alignment column: the name, one space off the type.
const ANSI_PORT_COLS: &[ColSpec] = &[ColSpec { flush: 1, min: 1 }];
/// 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 }];
/// A `parameter`/`localparam` declaration's two alignment columns: the name,
/// and the `=` of its value.
const PARAM_DECL_COLS: &[ColSpec] = &[ColSpec { flush: 1, min: 1 }, ColSpec { flush: 1, min: 1 }];
/// Everything that can stop the formatter from producing output.
#[derive(Debug)]
pub enum FormatError {
/// The input could not be lexed or parsed.
Source(vlog_parser::Error),
/// A safety check failed; the formatted text was discarded.
Verification(VerificationError),
}
impl std::fmt::Display for FormatError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FormatError::Source(e) => write!(f, "{e}"),
FormatError::Verification(e) => write!(f, "{e}"),
}
}
}
impl std::error::Error for FormatError {}
impl From<vlog_parser::Error> for FormatError {
fn from(e: vlog_parser::Error) -> Self {
FormatError::Source(e)
}
}
impl From<VerificationError> for FormatError {
fn from(e: VerificationError) -> Self {
FormatError::Verification(e)
}
}
/// Format `source`, verifying the result before handing it back.
///
/// The output is only returned if it re-lexes to the same token stream as the
/// input (comments included) and formatting it again is a fixed point;
/// otherwise the caller gets an error and must leave the original text alone.
pub fn format_source(source: &str, config: &Config) -> Result<String, FormatError> {
let output = format_once(source, config).map_err(FormatError::Source)?;
verify_equivalence(source, &output)?;
let again = format_once(&output, config).map_err(VerificationError::Reparse)?;
verify_convergence(&output, &again)?;
Ok(output)
}
/// Format only the constructs intersecting `lines`, emitting every other byte
/// exactly as it was written.
///
/// The safety net is the same one and it still runs over the *whole* output:
/// the spliced bytes are source text, the laid-out islands are ordinary
/// formatter output, and both checks are global. Convergence is checked by
/// replaying the same per-item decisions against the output — see
/// `docs/features/range-formatting/README.md`.
pub fn format_range(
source: &str,
config: &Config,
lines: &range::LineRanges,
) -> Result<String, FormatError> {
let file = vlog_parser::parse_source(source).map_err(FormatError::Source)?;
let selection = range::select(source, &file, lines);
let output = format_selected(source, config, &selection).map_err(FormatError::Source)?;
verify_equivalence(source, &output)?;
let again = format_selected(&output, config, &selection).map_err(VerificationError::Reparse)?;
verify_convergence(&output, &again)?;
Ok(output)
}
/// A single unverified formatting pass: parse, lay out, print.
fn format_once(source: &str, config: &Config) -> Result<String, vlog_parser::Error> {
let file = vlog_parser::parse_source(source)?;
let regions = fence::collect(source, &file);
Ok(render(&Fmt { cfg: config, src: source, regions, splits: Vec::new() }, &file, config))
}
/// The same pass, restricted to the units `selection` picked out.
fn format_selected(
source: &str,
config: &Config,
selection: &range::Selection,
) -> Result<String, vlog_parser::Error> {
let file = vlog_parser::parse_source(source)?;
let plan = range::plan(source, &file, selection);
let fmt = Fmt { cfg: config, src: source, regions: plan.regions, splits: plan.splits };
Ok(render(&fmt, &file, config))
}
/// Lay the file out and print it, ending in exactly one newline.
fn render(fmt: &Fmt, file: &SourceFile, config: &Config) -> String {
let doc = fmt.file(file);
let printer = Printer { max_width: config.max_width, indent_width: config.indent_width };
let mut out = printer.print(&doc);
// Normalize trailing whitespace: exactly one final newline.
while out.ends_with('\n') || out.ends_with(' ') {
out.pop();
}
out.push('\n');
out
}
struct Fmt<'a> {
cfg: &'a Config,
/// The text the AST was parsed from — what `// verilog_format: off`
/// regions and `--lines` runs are spliced out of.
src: &'a str,
/// The byte ranges of `src` emitted exactly as written, sorted and
/// non-overlapping: fenced regions, plus whatever a range run left alone.
regions: Vec<Region>,
/// Scope-bearing items a range run descends into. Empty for a whole-file
/// run.
splits: Vec<Split>,
}
/// What a comment turns into: itself, the verbatim region it opens, or
/// nothing at all because a region already covers its bytes.
enum Slot<'r> {
Normal,
Opens(&'r Region),
Covered,
}
/// One operator of a flattened binary chain, with the comments written on
/// either side of it.
struct BinaryOp<'e> {
op: &'e str,
before: &'e [Comment],
after: &'e [Comment],
}
/// A list element ready for comma-list layout. Blank lines between elements
/// are deliberately dropped, so only the comments ride along.
struct ListItem {
leading: Vec<Comment>,
doc: Doc,
/// Comments written between the element and the separator that follows.
before_sep: Vec<Comment>,
trailing: Option<Comment>,
/// Whether a `,` follows this entry. `None` means "decide from the
/// position" — the last entry of the list gets none — which is right for
/// every list that cannot hold a compiler directive. The three that can
/// (a header's parameter ports and ports, an enum's members) set it from
/// the source, because a directive between two elements can move the
/// comma to the other side of it.
comma: Option<bool>,
/// True for a `` `ifdef``-style entry. A directive runs to end of line,
/// so whatever follows it — a comma included — starts a new line.
directive: bool,
}
impl ListItem {
fn from_meta(meta: &Meta, doc: Doc) -> Self {
ListItem {
leading: meta.leading.clone(),
doc,
before_sep: meta.before_sep.clone(),
trailing: meta.trailing.clone(),
comma: None,
directive: false,
}
}
/// Record the `,` the source wrote after this element, instead of letting
/// the list derive one from the element's position.
fn with_comma(mut self, comma: bool) -> Self {
self.comma = Some(comma);
self
}
}
impl<'a> Fmt<'a> {
// ------------------------------------------------------------------
// Shared helpers
// ------------------------------------------------------------------
/// Verbatim text — a directive, an attribute, or a macro invocation —
/// ready to be re-indented.
///
/// A token that carries a string literal across a line break is emitted
/// completely untouched instead: the leading whitespace of such a
/// continuation line is part of the string's *value*, and re-indenting it
/// would rewrite the string. Emitting the text as a single `Doc::Text`
/// means the printer copies the newlines through without adding indent,
/// so nothing changes and the result is a fixed point by construction.
fn raw_text(&self, raw: &RawText) -> Doc {
if crosses_line_inside_string(&raw.text) {
return text(raw.text.clone());
}
self.raw_lines(&raw.text, raw.col)
}
/// Verbatim text that does *not* start the line it is printed on: the
/// `#( ... )` of a parameterized type or class reference.
///
/// It is emitted exactly as written, continuation lines included.
/// `raw_lines`'s dedent-by-column only reaches a fixed point when the text
/// begins its own line — the dedent has to cancel the indent the printer
/// adds back — and this text never does, so re-indenting it would drift.
/// Emitting it unchanged is idempotent by construction.
fn raw_inline(&self, raw: &RawText) -> Doc {
text(raw.text.clone())
}
/// A macro invocation standing as an item or a statement. The invocation
/// itself is verbatim source — we do not expand macros, so re-spacing the
/// argument list would be guesswork — and the trailing `;` is reproduced
/// only if the source wrote one.
fn macro_call(&self, call: &MacroCall) -> Doc {
let body = self.raw_text(&call.raw);
if call.semi {
concat(vec![body, text(";")])
} else {
body
}
}
/// A comment, ready to be re-indented at the printer's current level.
fn comment(&self, c: &Comment) -> Doc {
self.raw_lines(&c.text, c.col)
}
/// Multi-line raw text that originally started at column `col`. Every
/// continuation line is dedented by `col - 1` before the printer prepends
/// the current indent; without that, each pass would stack another indent
/// on top of the previous one and formatting would never converge.
fn raw_lines(&self, s: &str, col: u32) -> Doc {
if !s.contains('\n') {
return text(s);
}
let dedent = col.saturating_sub(1) as usize;
let mut docs = Vec::new();
for (i, line) in s.split('\n').enumerate() {
let line = if i == 0 {
line
} else {
docs.push(Doc::HardLine);
strip_blanks(line, dedent)
};
docs.push(text(line.trim_end()));
}
concat(docs)
}
/// A closing keyword with its optional block label: `end`, `end : main`.
/// Matches the `endmodule : m` spelling used for module footers.
fn closing(kw: &str, label: &Option<String>) -> Doc {
match label {
Some(l) => text(format!("{kw} : {l}")),
None => text(kw),
}
}
// ------------------------------------------------------------------
// Format-off fences
// ------------------------------------------------------------------
/// What to do with one comment, given the fenced regions of the source.
fn slot(&self, c: &Comment) -> Slot<'_> {
match fence::region_at(&self.regions, c.span.start as usize) {
None => Slot::Normal,
Some(r) if r.fence == c.span.start as usize => Slot::Opens(r),
Some(_) => Slot::Covered,
}
}
/// True if this node's code is inside a verbatim region, i.e. its bytes
/// are already being emitted as written and it must not be laid out.
fn is_verbatim(&self, span: TextRange) -> bool {
fence::region_at(&self.regions, span.start as usize).is_some()
}
/// The verbatim region this byte offset *opens*, if it opens one.
///
/// A region's opener is the first byte of the first unit it covers: a
/// fence comment, the first leading comment of a run's first item, or —
/// when that item has no leading comments — the item's own code.
fn opens_at(&self, at: usize) -> Option<&Region> {
fence::region_at(&self.regions, at).filter(|r| r.fence == at)
}
/// The split recorded for the item starting at this byte offset.
fn split_at(&self, at: usize) -> Option<&Split> {
self.splits.iter().find(|s| s.item == at)
}
/// A verbatim slice of the source, by byte range.
fn slice(&self, (start, end): (usize, usize)) -> Doc {
Doc::Verbatim(self.src.get(start..end).unwrap_or_default().to_string())
}
/// A fenced region's source bytes.
///
/// A slice that is not on a character boundary cannot happen — every
/// offset comes from a span or from a scan over ASCII delimiters — but if
/// it ever did, an empty region loses tokens and `verify_equivalence`
/// rejects the output, which is the failsafe. Better that than a panic.
fn verbatim(&self, r: &Region) -> Doc {
Doc::Verbatim(self.src.get(r.start..r.end).unwrap_or_default().to_string())
}
/// Leading comments (each on its own line) preceding a node, with any
/// fenced region they open spliced in as source bytes.
///
/// The break between two comments is emitted *before* the second one, not
/// after the first: a `HardLine` followed by a `BlankLine` is three
/// newlines, so writing both turned one blank line between two comments
/// into two. The list still ends with the `HardLine` that puts the node
/// itself on a fresh line.
fn leading_comments(&self, meta: &Meta) -> Vec<Doc> {
let mut docs = Vec::new();
for c in &meta.leading {
self.push_comment(&mut docs, c);
}
if !docs.is_empty() {
docs.push(Doc::HardLine);
}
docs
}
/// Append one leading comment — or, when it opens a fenced region, that
/// region's source bytes — with the break that separates it from whatever
/// precedes it. Covered comments are already inside emitted bytes.
fn push_comment(&self, docs: &mut Vec<Doc>, c: &Comment) {
let doc = match self.slot(c) {
Slot::Covered => return,
Slot::Opens(r) => self.verbatim(r),
Slot::Normal => self.comment(c),
};
Self::push_leading(docs, doc, c.blank_before);
}
/// Leading comments and `(* ... *)` attributes preceding a node, each on
/// its own line, in the order the source wrote them.
///
/// The two are stored in separate lists but interleave in the source
/// (`(* keep *)` ⏎ `// why` ⏎ `logic x;`), so they are merged by span:
/// printing every comment and then every attribute moves a comment across
/// an attribute in the token stream, which the safety net rejects.
fn leading(&self, meta: &Meta) -> Vec<Doc> {
let mut docs = Vec::new();
let mut attrs = meta.attrs.iter().peekable();
for c in &meta.leading {
while let Some(attr) = attrs.next_if(|a| a.span.start < c.span.start) {
Self::push_leading(&mut docs, self.raw_text(attr), false);
}
self.push_comment(&mut docs, c);
}
for attr in attrs {
Self::push_leading(&mut docs, self.raw_text(attr), false);
}
if !docs.is_empty() {
docs.push(Doc::HardLine);
}
docs
}
/// Append one leading comment or attribute, with the break that separates
/// it from the previous one. The break goes *before* the second entry
/// rather than after the first: a `HardLine` followed by a `BlankLine` is
/// three newlines, so writing both turned one blank line into two.
fn push_leading(docs: &mut Vec<Doc>, doc: Doc, blank_before: bool) {
if !docs.is_empty() {
docs.push(if blank_before { Doc::BlankLine } else { Doc::HardLine });
}
docs.push(doc);
}
/// Comments written between a construct's head and the bracket that opens
/// one of its lists (`module m` ⏎ `// why` ⏎ `#(`, `sub u` ⏎ `// why` ⏎
/// `(...)`). They print on the head's side of the bracket, which is where
/// the source put them.
///
/// `on_fresh_line` says whether the caller has already broken the line;
/// the return value says the same for whatever it emits next, since a line
/// comment runs to end of line and the bracket cannot follow it.
fn bracket_comments(
&self,
comments: &[Comment],
docs: &mut Vec<Doc>,
on_fresh_line: bool,
) -> bool {
let mut fresh = on_fresh_line;
for c in comments {
if !fresh {
docs.push(text(" "));
}
docs.push(self.comment(c));
fresh = is_line_comment(&c.text);
if fresh {
docs.push(Doc::HardLine);
}
}
fresh
}
fn trailing(&self, meta: &Meta) -> Vec<Doc> {
let mut docs = Vec::new();
let ends_line = self.inline_comments(&meta.before_sep, &mut docs);
if let Some(tr) = &meta.trailing {
docs.push(if ends_line { Doc::HardLine } else { text(" ") });
docs.push(self.comment(tr));
}
docs
}
/// Append comments written between two tokens of an expression, each
/// spaced off what precedes it. A line comment runs to end of line, so
/// anything after it starts a new one — including the next comment, which
/// would otherwise be swallowed into the first one's text.
///
/// Returns true when the last comment was a line comment, i.e. the caller
/// must put whatever it emits next on a fresh line.
fn inline_comments(&self, comments: &[Comment], docs: &mut Vec<Doc>) -> bool {
let mut ends_line = false;
for c in comments {
docs.push(if ends_line { Doc::HardLine } else { text(" ") });
docs.push(self.comment(c));
ends_line = is_line_comment(&c.text);
}
ends_line
}
/// The same, plus the separator that keeps the next thing off the last
/// comment: a space, or a line break after a line comment.
fn inline_comments_spaced(&self, comments: &[Comment], docs: &mut Vec<Doc>) {
if self.inline_comments(comments, docs) {
docs.push(Doc::HardLine);
} else {
docs.push(text(" "));
}
}
fn with_meta(&self, meta: &Meta, doc: Doc) -> Doc {
let mut docs = self.leading(meta);
docs.push(doc);
docs.extend(self.trailing(meta));
concat(docs)
}
/// Comma-separated list inside `open`/`close`, one per line when broken.
/// `force_break` lays every element on its own line regardless of width.
fn delimited(&self, open: &str, items: Vec<ListItem>, close: &str, force_break: bool) -> Doc {
self.delimited_dangling(open, items, &[], close, force_break)
}
/// The same, plus the comments written after the last element and before
/// `close`. They are printed inside the brackets, each on its own line:
/// printed after `close` they would move across it in the token stream,
/// and a `/* verilator lint_on */`-style pragma would cover the wrong
/// region.
fn delimited_dangling(
&self,
open: &str,
items: Vec<ListItem>,
dangling: &[Comment],
close: &str,
force_break: bool,
) -> Doc {
if items.is_empty() && dangling.is_empty() {
return text(format!("{open}{close}"));
}
let mut inner: Vec<Doc> = Vec::new();
if !items.is_empty() {
inner.push(if force_break { Doc::HardLine } else { Doc::SoftLine });
}
let last = items.len().saturating_sub(1);
let mut close_needs_hardline = force_break;
for (i, item) in items.into_iter().enumerate() {
let meta = Meta { leading: item.leading, ..Meta::default() };
inner.extend(self.leading(&meta));
inner.push(item.doc);
// Comments written before the separator print on this element's
// side of it, which is where the source put them.
let has_before_sep = !item.before_sep.is_empty();
// A directive swallows the rest of its line, so its comma — and
// any comment written before that comma — must start a new one.
// (A comment itself may share the line: the lexer stops the
// directive's capture before a `//` or `/*`.)
let ends_line = self.inline_comments(&item.before_sep, &mut inner) || item.directive;
if item.comma.unwrap_or(i < last) {
if ends_line {
inner.push(Doc::HardLine);
}
inner.push(text(","));
} else if has_before_sep {
close_needs_hardline = true;
}
if let Some(tr) = item.trailing {
inner.push(text(" "));
inner.push(self.comment(&tr));
if i < last {
inner.push(Doc::HardLine);
} else {
close_needs_hardline = true;
}
} else if i < last {
inner.push(Doc::Line);
}
}
for c in dangling {
inner.push(Doc::HardLine);
inner.push(self.comment(c));
close_needs_hardline = true;
}
// Peek at blank_before flags is handled by leading comments already;
// blank lines inside bracketed lists are dropped deliberately.
let mut docs = vec![text(open), indent(inner)];
docs.push(if close_needs_hardline { Doc::HardLine } else { Doc::SoftLine });
docs.push(text(close));
group(docs)
}
/// Put a list's elements and the `` `ifdef``-style directives written
/// between them back into source order.
///
/// A directive is an entry like any other except that it never takes a
/// comma of its own unless the source wrote one after it, and that it
/// forces the list open: `delimited_dangling`'s `force_break` must be set
/// whenever the result holds one, or the printer could put the next entry
/// on the directive's line, where the lexer would swallow it.
fn list_entries(&self, elements: Vec<ListItem>, directives: &[ListDirective]) -> Vec<ListItem> {
if directives.is_empty() {
return elements;
}
let mut out = Vec::with_capacity(elements.len() + directives.len());
let mut pending = directives.iter().peekable();
for (i, element) in elements.into_iter().enumerate() {
while let Some(d) = pending.next_if(|d| d.before <= i) {
out.push(self.directive_entry(d));
}
out.push(element);
}
for d in pending {
out.push(self.directive_entry(d));
}
out
}
/// One directive standing between list elements, verbatim.
///
/// Its trailing comment goes in `before_sep` rather than `trailing`
/// because that is where the source put it — between the directive and
/// the comma that may follow it. `Parser::take_before_sep` already moves a
/// trailing comment into `before_sep` in source order, so at most one of
/// the two is ever populated and appending keeps the source's order.
fn directive_entry(&self, d: &ListDirective) -> ListItem {
let mut before_sep = d.meta.before_sep.clone();
before_sep.extend(d.meta.trailing.clone());
ListItem {
leading: d.meta.leading.clone(),
doc: self.raw_text(&d.raw),
before_sep,
trailing: None,
comma: Some(d.comma),
directive: true,
}
}
// ------------------------------------------------------------------
// Alignment inference
// ------------------------------------------------------------------
/// Plan the alignment of a sequence of candidate rows.
///
/// `rows[i]` is `None` for an element that cannot be aligned, and
/// `breaks[i]` is true for one that starts a new group. Both split the
/// sequence into maximal runs, and every element of a run that is planned
/// aligned gets the same [`Align`] — the padding is a property of the
/// group, never of one line.
fn align_groups(
&self,
rows: &[Option<Row>],
breaks: &[bool],
specs: &[ColSpec],
depth: usize,
) -> Vec<Option<Align>> {
// What is left of the line once the rows' own indentation is paid
// for. `depth` comes from the AST's nesting, so it is the same on
// every pass — which is what keeps the verdict stable.
let budget = self.cfg.max_width.saturating_sub(depth * self.cfg.indent_width);
let mut out = vec![None; rows.len()];
let mut i = 0;
while i < rows.len() {
if rows[i].is_none() {
i += 1;
continue;
}
let mut j = i + 1;
while j < rows.len() && rows[j].is_some() && !breaks[j] {
j += 1;
}
let run: Vec<&Row> = rows[i..j].iter().flatten().collect();
if let Some(plan) = align::plan(self.src, &run, specs, budget) {
for slot in &mut out[i..j] {
*slot = Some(plan.clone());
}
}
i = j;
}
out
}
/// Measure one candidate row. `None` — meaning "cannot be aligned" — when
/// the cells did not split at every column, or when one of them holds a
/// comment and so has no flat width.
fn row_of(cells: &[Doc], anchors: Vec<u32>, tail: usize) -> Option<Row> {
if cells.len() != anchors.len() + 1 {
return None;
}
let widths: Option<Vec<usize>> = cells.iter().map(align::flat_width).collect();
Some(Row { widths: widths?, anchors, tail })
}
/// Which elements of a bracketed list start a new alignment group: those
/// with a comment or an attribute of their own — both print on their own
/// line — and those a compiler directive was written in front of.
///
/// A blank line is deliberately *not* a boundary here: `delimited` drops
/// blank lines between list elements, so a boundary drawn at one would
/// vanish from the output and the next pass would group differently.
fn list_breaks<'m>(
metas: impl Iterator<Item = &'m Meta>,
directives: &[ListDirective],
) -> Vec<bool> {
let mut breaks: Vec<bool> =
metas.map(|m| !m.leading.is_empty() || !m.attrs.is_empty()).collect();
for d in directives {
if let Some(b) = breaks.get_mut(d.before) {
*b = true;
}
}
breaks
}
/// The alignment plan for a module header's ANSI port list.
fn ansi_port_aligns(
&self,
ports: &[AnsiPort],
directives: &[ListDirective],
depth: usize,
) -> Vec<Option<Align>> {
let rows: Vec<Option<Row>> = ports
.iter()
.map(|p| {
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.meta), directives);
self.align_groups(&rows, &breaks, ANSI_PORT_COLS, depth)
}
/// The alignment plan for an instance's named connection list.
fn connection_aligns(
&self,
conns: &[Connection],
directives: &[ListDirective],
depth: usize,
) -> Vec<Option<Align>> {
let rows: Vec<Option<Row>> = conns
.iter()
.map(|c| {
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.meta), directives);
self.align_groups(&rows, &breaks, CONNECTION_COLS, depth)
}
/// The alignment plan for the `parameter`/`localparam` declarations among
/// a run of module (or package, or class) items.
fn param_decl_aligns(&self, items: &[Item], depth: usize) -> Vec<Option<Align>> {
let rows: Vec<Option<Row>> = items.iter().map(|i| self.param_decl_row(i)).collect();
if rows.iter().all(Option::is_none) {
return vec![None; items.len()];
}
// Unlike a bracketed list, an item sequence prints the blank lines the
// source wrote, so a blank line is a boundary the next pass sees too.
let breaks: Vec<bool> = items
.iter()
.map(|i| i.meta.blank_before || !i.meta.leading.is_empty() || !i.meta.attrs.is_empty())
.collect();
self.align_groups(&rows, &breaks, PARAM_DECL_COLS, depth)
}
/// Measure a `parameter`/`localparam` item as an alignment row.
///
/// Only the plain shape joins a group: one declarator, with a value, no
/// comments of its own, not inside a fenced region. Anything else formats
/// the way it always has and splits the group in two.
fn param_decl_row(&self, item: &Item) -> Option<Row> {
let ItemKind::ParamDecl(d) = &item.kind else { return None };
if !item.meta.attrs.is_empty() || self.is_verbatim(item.span) {
return None;
}
let [decl] = &d.declarators[..] else { return None };
if !decl.meta.leading.is_empty()
|| !decl.meta.before_sep.is_empty()
|| decl.meta.trailing.is_some()
{
return None;
}
let init = decl.init.as_ref()?;
let eq = self.eq_offset(init.span.start, decl.name_span.end)?;
// The tail is the `;` the item ends with.
Self::row_of(&self.param_decl_cells(d, decl, init), vec![decl.name_span.start, eq], 1)
}
/// Byte offset of the `=` between a declarator's name and its value, or
/// `None` when anything but whitespace stands between the two.
fn eq_offset(&self, value_start: u32, after_name: u32) -> Option<u32> {
let bytes = self.src.as_bytes();
let mut pos = value_start as usize;
while pos > 0 && matches!(bytes[pos - 1], b' ' | b'\t' | b'\r' | b'\n') {
pos -= 1;
}
(pos > after_name as usize && bytes.get(pos - 1) == Some(&b'=')).then_some(pos as u32 - 1)
}
/// 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)
}
/// A bracketed expression list (concatenation, call arguments, `inside`
/// set). Comments on an element ride along and break the list open.
fn expr_list(&self, open: &str, items: &[ExprItem], close: &str) -> Doc {
let items: Vec<ListItem> =
items.iter().map(|i| ListItem::from_meta(&i.meta, self.expr(&i.expr))).collect();
self.delimited(open, items, close, false)
}
/// The right-hand side of an `=`: normally a break opportunity that moves
/// the value to an indented next line, but a value that already contains a
/// forced break (a comment inside it) keeps `= {` on the head line, the
/// way a broken port list keeps `module m (` on its own.
fn assign_rhs(&self, doc: Doc) -> Doc {
if contains_hard_line(std::slice::from_ref(&doc)) {
concat(vec![text(" "), doc])
} else {
indent(vec![Doc::Line, doc])
}
}
/// `( expr )` with break opportunity inside.
fn parens(&self, e: &Expr) -> Doc {
group(vec![text("("), indent(vec![Doc::SoftLine, self.expr(e)]), Doc::SoftLine, text(")")])
}
/// 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.
fn item_seq(&self, items: &[Item], depth: usize) -> Vec<Doc> {
let aligns = self.param_decl_aligns(items, depth);
let mut docs = Vec::new();
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() {
docs.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
}
docs.extend(item_docs);
}
docs
}
fn stmt_seq(&self, stmts: &[Stmt]) -> Vec<Doc> {
let mut docs = Vec::new();
for (i, s) in stmts.iter().enumerate() {
if i > 0 {
docs.push(if s.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
}
docs.push(self.stmt(s));
}
docs
}
fn dangling(&self, comments: &[Comment]) -> Vec<Doc> {
let mut docs = Vec::new();
for c in comments {
let doc = match self.slot(c) {
Slot::Covered => continue,
Slot::Opens(r) => self.verbatim(r),
Slot::Normal => self.comment(c),
};
docs.push(if c.blank_before { Doc::BlankLine } else { Doc::HardLine });
docs.push(doc);
}
docs
}
// ------------------------------------------------------------------
// File / items
// ------------------------------------------------------------------
fn file(&self, f: &SourceFile) -> Doc {
let mut docs = 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)
}
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, name, .. } => Some(text(format!("{kw} {name};"))),
_ => None,
}
}
/// A split item's closing keyword, laid out.
fn tail_doc(kind: &ItemKind) -> Option<Doc> {
match kind {
ItemKind::Module(m) => Some(Self::closing("endmodule", &m.end_label)),
ItemKind::Package { end_label, .. } => Some(Self::closing("endpackage", end_label)),
_ => None,
}
}
fn item_kind(&self, kind: &ItemKind, align: Option<&Align>, depth: usize) -> Doc {
match kind {
ItemKind::Module(m) => self.module(m, depth),
ItemKind::Package { kw, name, items, dangling, end_label, .. } => {
let mut docs = vec![text(format!("{kw} {name};"))];
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("endpackage", end_label));
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::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::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")])
}
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::Class(c) => self.class(c, depth),
ItemKind::Verbatim(raw) => self.raw_text(raw),
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)
}
}
}
// ------------------------------------------------------------------
// Module
// ------------------------------------------------------------------
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("endmodule", &m.end_label));
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.
fn module_head(&self, m: &Module, depth: usize) -> Doc {
let mut docs = vec![text(format!("{} {}", m.kw, 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| 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 { " #" }));
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(text(";")),
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)| {
ListItem::from_meta(&p.meta, self.ansi_port(p, a.as_ref()))
.with_comma(p.comma)
})
.collect()
}
PortList::NonAnsi(ports) => ports
.iter()
.map(|p| {
ListItem::from_meta(&p.meta, text(p.name.clone())).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(text(";"));
}
}
concat(docs)
}
fn param_port(&self, p: &ParamPort) -> Doc {
let mut parts: Vec<String> = Vec::new();
if let Some(kw) = &p.kw {
parts.push(kw.clone());
}
if p.is_type {
parts.push("type".to_string());
}
let mut docs = Vec::new();
let ty = self.data_type(&p.ty);
let prefix = parts.join(" ");
if !prefix.is_empty() {
docs.push(text(prefix));
docs.push(text(" "));
}
if let Some(t) = ty {
docs.push(t);
docs.push(text(" "));
}
docs.push(text(p.name.clone()));
docs.extend(self.unpacked_dims(&p.unpacked));
if let Some(d) = &p.default {
docs.push(text(" = "));
docs.push(group(vec![self.expr(d)]));
}
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> {
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![text(p.name.clone())];
docs.extend(self.unpacked_dims(&p.unpacked));
if let Some(d) = &p.default {
docs.push(text(" = "));
docs.push(self.expr(d));
}
if prefix.is_empty() {
return vec![concat(docs)];
}
vec![concat(prefix), concat(docs)]
}
// ------------------------------------------------------------------
// Types and declarations
// ------------------------------------------------------------------
/// Format a data type; `None` if fully implicit.
fn data_type(&self, ty: &DataType) -> Option<Doc> {
if ty.is_implicit() {
return None;
}
let mut docs = Vec::new();
let mut need_space = false;
if !ty.name.is_empty() {
docs.push(text(ty.name.clone()));
need_space = true;
}
// `uvm_analysis_port #(bit [31:0]) port;` — spaced before the `#(`,
// like an instantiation's overrides and unlike the tight `#(` of a
// parameterized name in expression position.
if let Some(params) = &ty.params {
if need_space {
docs.push(text(" "));
}
docs.push(self.raw_inline(params));
need_space = true;
}
if let Some(s) = &ty.signing {
if need_space {
docs.push(text(" "));
}
docs.push(text(s.clone()));
need_space = true;
}
if !ty.packed.is_empty() {
if need_space {
docs.push(text(" "));
}
for d in &ty.packed {
docs.push(self.dim(d));
}
}
Some(concat(docs))
}
fn dim(&self, d: &Dim) -> Doc {
match &d.kind {
DimKind::Range { a, b } => {
let mut docs = vec![text("["), self.expr_compact(a)];
if let Some(b) = b {
docs.push(text(":"));
docs.push(self.expr_compact(b));
}
docs.push(text("]"));
concat(docs)
}
DimKind::Dynamic => text("[]"),
DimKind::Wildcard => text("[*]"),
}
}
/// Compact rendering used inside `[...]` brackets: arithmetic and shift
/// operators lose their surrounding spaces (`[WIDTH-1:0]`), and no line
/// breaks are introduced.
fn expr_compact(&self, e: &Expr) -> Doc {
match &e.kind {
ExprKind::Binary { lhs, op, rhs, comments } => {
if comments.before.is_empty() && comments.after.is_empty() {
let tight = Self::binary_prec(op) >= 8;
let sep = if tight { op.clone() } else { format!(" {op} ") };
return concat(vec![self.expr_compact(lhs), text(sep), self.expr_compact(rhs)]);
}
// A comment written next to the operator has nowhere to go in
// the tight spelling, so the operator gets its spaces back;
// a line comment pushes what follows onto the next line.
let mut docs = vec![self.expr_compact(lhs)];
self.inline_comments_spaced(&comments.before, &mut docs);
docs.push(text(op.clone()));
self.inline_comments_spaced(&comments.after, &mut docs);
docs.push(self.expr_compact(rhs));
concat(docs)
}
ExprKind::Ternary { cond, then, els, .. } => concat(vec![
self.expr_compact(cond),
text(" ? "),
self.expr_compact(then),
text(" : "),
self.expr_compact(els),
]),
ExprKind::Paren { inner, .. } => {
concat(vec![text("("), self.expr_compact(inner), text(")")])
}
ExprKind::Unary { op, expr } => concat(vec![text(op.clone()), self.expr_compact(expr)]),
_ => self.expr(e),
}
}
fn unpacked_dims(&self, dims: &[Dim]) -> Vec<Doc> {
let mut docs = Vec::new();
if !dims.is_empty() {
docs.push(text(" "));
for d in dims {
docs.push(self.dim(d));
}
}
docs
}
fn declarators(&self, decls: &[Declarator]) -> Doc {
let items: Vec<ListItem> = decls
.iter()
.map(|d| {
let mut docs = vec![text(d.name.clone())];
docs.extend(self.unpacked_dims(&d.unpacked));
if let Some(init) = &d.init {
docs.push(text(" ="));
docs.push(group(vec![self.assign_rhs(self.expr(init))]));
}
ListItem::from_meta(&d.meta, concat(docs))
})
.collect();
if items.len() == 1 {
let item = items.into_iter().next().unwrap();
let mut docs = self.leading(&Meta { leading: item.leading, ..Meta::default() });
docs.push(item.doc);
let mut ends_line = self.inline_comments(&item.before_sep, &mut docs);
if let Some(tr) = item.trailing {
docs.push(if ends_line { Doc::HardLine } else { text(" ") });
docs.push(self.comment(&tr));
ends_line = is_line_comment(&tr.text);
}
// The caller appends the `;`; a line comment runs to end of line,
// so it has to go on the next one.
if ends_line {
docs.push(Doc::HardLine);
}
return concat(docs);
}
// Multiple declarators: allow one-per-line continuation.
let mut inner = Vec::new();
let last = items.len() - 1;
for (i, item) in items.into_iter().enumerate() {
let meta = Meta { leading: item.leading, ..Meta::default() };
inner.extend(self.leading(&meta));
inner.push(item.doc);
let ends_line = self.inline_comments(&item.before_sep, &mut inner);
if i < last {
if ends_line {
inner.push(Doc::HardLine);
}
inner.push(text(","));
} else if ends_line {
inner.push(Doc::HardLine);
}
if let Some(tr) = item.trailing {
inner.push(text(" "));
inner.push(self.comment(&tr));
if i < last || is_line_comment(&tr.text) {
inner.push(Doc::HardLine);
}
} else if i < last {
inner.push(Doc::Line);
}
}
group(vec![indent(inner)])
}
/// A `parameter`/`localparam` declaration. With an alignment plan it is
/// laid out as cells padded to the group's columns; without one it takes
/// the flush path every other declaration takes.
///
/// The two must agree byte-for-byte when the padding collapses, because
/// that is exactly what the printer's line-limit fallback does — and the
/// next pass, seeing no excess spaces, comes back through the flush path.
fn param_decl(&self, d: &ParamDecl, align: Option<&Align>) -> Doc {
if let (Some(a), [decl]) = (align, &d.declarators[..]) {
if let Some(init) = &decl.init {
return align::render(
&self.param_decl_cells(d, decl, init),
PARAM_DECL_COLS,
Some(a),
);
}
}
let mut docs = vec![text(d.kw.clone()), text(" ")];
if let Some(t) = self.data_type(&d.ty) {
docs.push(t);
docs.push(text(" "));
}
docs.push(self.declarators(&d.declarators));
concat(docs)
}
/// A `parameter`/`localparam` declaration split at its two alignment
/// columns: the keyword and type, the name, and the `= value`.
fn param_decl_cells(&self, d: &ParamDecl, decl: &Declarator, init: &Expr) -> Vec<Doc> {
let mut prefix = vec![text(d.kw.clone())];
if let Some(t) = self.data_type(&d.ty) {
prefix.push(text(" "));
prefix.push(t);
}
let mut name = vec![text(decl.name.clone())];
name.extend(self.unpacked_dims(&decl.unpacked));
vec![
concat(prefix),
concat(name),
concat(vec![text("="), group(vec![self.assign_rhs(self.expr(init))])]),
]
}
fn data_decl(&self, d: &DataDecl) -> Doc {
let mut docs = Vec::new();
if let Some(net) = &d.net {
docs.push(text(format!("{net} ")));
}
if let Some(delay) = &d.delay {
docs.push(text("#"));
docs.push(self.expr(delay));
docs.push(text(" "));
}
for q in &d.qualifiers {
docs.push(text(format!("{q} ")));
}
if let Some(t) = self.data_type(&d.ty) {
docs.push(t);
docs.push(text(" "));
}
docs.push(self.declarators(&d.declarators));
concat(docs)
}
fn port_decl(&self, d: &PortDecl) -> Doc {
let mut docs = vec![text(format!("{} ", d.dir))];
if let Some(net) = &d.net {
docs.push(text(format!("{net} ")));
}
if let Some(t) = self.data_type(&d.ty) {
docs.push(t);
docs.push(text(" "));
}
docs.push(self.declarators(&d.declarators));
concat(docs)
}
fn typedef(&self, t: &Typedef) -> Doc {
match &t.kind {
TypedefKind::ForwardClass => text(format!("typedef class {};", t.name)),
TypedefKind::Alias(ty) => {
let mut docs = vec![text("typedef ")];
if let Some(d) = self.data_type(ty) {
docs.push(d);
docs.push(text(" "));
}
docs.push(text(t.name.clone()));
docs.extend(self.unpacked_dims(&t.unpacked));
docs.push(text(";"));
concat(docs)
}
TypedefKind::Enum(e) => {
let mut docs = vec![text("typedef enum")];
if let Some(base) = &e.base {
if let Some(d) = self.data_type(base) {
docs.push(text(" "));
docs.push(d);
}
}
docs.push(text(" "));
let items: Vec<ListItem> = e
.members
.iter()
.map(|m| {
let mut d = vec![text(m.name.clone())];
if let Some(v) = &m.value {
d.push(text(" = "));
d.push(self.expr(v));
}
ListItem::from_meta(&m.meta, concat(d)).with_comma(m.comma)
})
.collect();
let items = self.list_entries(items, &e.directives);
// `e.dangling` — comments written before the closing `}` —
// is printed inside the braces; the enum has no other place
// to put it, and dropping it loses a comment.
let broken = !e.directives.is_empty();
docs.push(self.delimited_dangling("{", items, &e.dangling, "}", broken));
docs.push(text(format!(" {};", t.name)));
concat(docs)
}
TypedefKind::Struct(s) => {
let mut header = format!("typedef {}", s.kw);
if s.packed {
header.push_str(" packed");
}
if let Some(sig) = &s.signing {
header.push(' ');
header.push_str(sig);
}
header.push_str(" {");
let mut inner = Vec::new();
for m in &s.members {
inner.push(Doc::HardLine);
inner.extend(self.leading(&m.meta));
let mut d = Vec::new();
if let Some(ty) = self.data_type(&m.ty) {
d.push(ty);
d.push(text(" "));
}
d.push(self.declarators(&m.declarators));
d.push(text(";"));
inner.push(concat(d));
inner.extend(self.trailing(&m.meta));
}
inner.extend(self.dangling(&s.dangling));
concat(vec![
text(header),
indent(inner),
Doc::HardLine,
text(format!("}} {};", t.name)),
])
}
}
}
// ------------------------------------------------------------------
// Module items
// ------------------------------------------------------------------
/// `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 {
if p.rhs_comments.is_empty() {
return group(vec![self.expr(&p.lhs), text(" ="), self.assign_rhs(self.expr(&p.rhs))]);
}
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));
group(vec![self.expr(&p.lhs), text(" ="), indent(inner)])
}
fn cont_assign(&self, a: &ContAssign) -> Doc {
let mut docs = vec![text("assign ")];
if let Some(delay) = &a.delay {
docs.push(text("#"));
docs.push(self.expr(delay));
docs.push(text(" "));
}
let items: Vec<ListItem> =
a.assigns.iter().map(|p| ListItem::from_meta(&p.meta, self.assign_pair(p))).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)
}
fn instantiation(&self, inst: &Instantiation, depth: usize) -> Doc {
let mut docs = vec![text(inst.module.clone())];
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| 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();
docs.push(text(if on_fresh_line { "#" } else { " #" }));
docs.push(self.delimited("(", 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(text(";"));
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![text(instance.name.clone())];
if !instance.dims.is_empty() {
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, depth);
broken |= aligns.iter().any(Option::is_some);
list.iter()
.zip(&aligns)
.map(|(c, a)| {
ListItem::from_meta(&c.meta, self.connection_aligned(c, a.as_ref()))
.with_comma(c.comma)
})
.collect()
}
Connections::Ordered(list) => list
.iter()
.map(|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.delimited("(", items, ")", broken)
}
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)];
if c.name.is_empty() || c.name == "*" {
return plain();
}
let Some(e) = &c.expr else { return plain() };
if matches!(e.kind, ExprKind::Empty(_)) {
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!(".{}", c.name)),
concat(vec![text("("), group(vec![indent(inner), close]), text(")")]),
]
}
fn connection_plain(&self, c: &Connection) -> Doc {
if c.name == "*" {
return text(".*");
}
if c.name.is_empty() {
// Positional parameter value.
return match &c.expr {
Some(e) => self.expr(e),
None => text(""),
};
}
match &c.expr {
None => text(format!(".{}", c.name)),
Some(Expr { kind: ExprKind::Empty(comments), .. }) => {
let mut docs = vec![text(format!(".{}(", c.name))];
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 close = if ends_line { Doc::HardLine } else { Doc::SoftLine };
concat(vec![
text(format!(".{}(", c.name)),
group(vec![indent(inner), close]),
text(")"),
])
}
}
}
fn gate_instantiation(&self, g: &GateInstantiation) -> Doc {
let mut docs = vec![text(g.gate.clone())];
if let Some(delay) = &g.delay {
docs.push(text(" #"));
docs.push(self.expr(delay));
}
for (i, inst) in g.instances.iter().enumerate() {
docs.push(if i > 0 { text(", ") } else { text(" ") });
if let Some(name) = &inst.name {
docs.push(text(name.clone()));
docs.push(text(" "));
}
docs.push(self.expr_list("(", &inst.args, ")"));
}
docs.push(text(";"));
concat(docs)
}
// ------------------------------------------------------------------
// Generate constructs
// ------------------------------------------------------------------
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 {
match &b.label {
Some(l) => docs.push(text(format!(" begin : {l}"))),
None => docs.push(text(" begin")),
}
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("end", &b.end_label));
true
} else {
let item = &b.items[0];
docs.push(group(vec![indent(vec![Doc::Line, self.item(item, depth + 1)])]));
false
}
}
fn gen_for(&self, g: &GenFor, depth: usize) -> Doc {
let mut header = vec![text("for (")];
if g.init_genvar {
header.push(text("genvar "));
}
header.push(self.expr(&g.init.lhs));
header.push(text(format!(" {} ", g.init.op)));
header.push(self.expr(&g.init.rhs));
header.push(text("; "));
header.push(self.expr(&g.cond));
header.push(text("; "));
header.push(self.for_step(&g.step));
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)];
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)
}
fn for_step(&self, step: &ForStep) -> Doc {
match step {
ForStep::Assign(a) => {
concat(vec![self.expr(&a.lhs), text(format!(" {} ", a.op)), self.expr(&a.rhs)])
}
ForStep::Expr(e) => self.expr(e),
}
}
// ------------------------------------------------------------------
// Functions and tasks
// ------------------------------------------------------------------
fn tf_args(&self, args: &[TfArg]) -> Doc {
let items: Vec<ListItem> = args
.iter()
.map(|a| {
let mut docs = Vec::new();
if let Some(dir) = &a.dir {
docs.push(text(format!("{dir} ")));
}
if let Some(t) = self.data_type(&a.ty) {
docs.push(t);
docs.push(text(" "));
}
docs.push(text(a.name.clone()));
docs.extend(self.unpacked_dims(&a.unpacked));
if let Some(d) = &a.default {
docs.push(text(" = "));
docs.push(self.expr(d));
}
ListItem::from_meta(&a.meta, concat(docs))
})
.collect();
self.delimited("(", items, ")", false)
}
/// A class: header on one line (its parameter and `extends` override
/// lists break like any other list when they do not fit), body items at
/// one more indent level, `endclass` with the label the source wrote.
fn class(&self, c: &ClassDecl, depth: usize) -> Doc {
let mut head = String::new();
for q in &c.prefix {
head.push_str(q);
head.push(' ');
}
head.push_str("class ");
if let Some(lifetime) = &c.lifetime {
head.push_str(lifetime);
head.push(' ');
}
head.push_str(&c.name);
let mut docs = vec![text(head)];
let on_fresh_line = self.bracket_comments(&c.param_comments, &mut docs, false);
if let Some(params) = &c.param_ports {
let items: Vec<ListItem> = params
.iter()
.map(|p| ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma))
.collect();
let items = self.list_entries(items, &c.param_directives);
let broken = !c.param_directives.is_empty();
docs.push(text(if on_fresh_line { "#" } else { " #" }));
docs.push(self.delimited_dangling("(", items, &c.param_dangling, ")", broken));
}
if let Some(ext) = &c.extends {
docs.push(text(format!(" extends {}", ext.name)));
let fresh = self.bracket_comments(&ext.param_comments, &mut docs, false);
if let Some(params) = &ext.params {
let items: Vec<ListItem> = params
.iter()
.map(|p| ListItem::from_meta(&p.meta, self.connection(p)).with_comma(p.comma))
.collect();
let items = self.list_entries(items, &ext.param_directives);
let broken = !ext.param_directives.is_empty();
docs.push(text(if fresh { "#" } else { " #" }));
docs.push(self.delimited("(", items, ")", broken));
}
}
if !c.implements.is_empty() {
docs.push(text(format!(" implements {}", join_names(&c.implements))));
}
docs.push(text(";"));
let mut body = Vec::new();
if !c.items.is_empty() {
body.push(Doc::HardLine);
body.extend(self.item_seq(&c.items, depth + 1));
}
body.extend(self.dangling(&c.dangling));
docs.push(indent(body));
docs.push(Doc::HardLine);
docs.push(Self::closing("endclass", &c.end_label));
concat(docs)
}
fn function(&self, f: &FunctionDecl) -> Doc {
let mut header = Vec::new();
for q in &f.prefix {
header.push(text(format!("{q} ")));
}
header.push(text("function "));
for q in &f.qualifiers {
header.push(text(format!("{q} ")));
}
if let Some(ret) = &f.ret {
if let Some(t) = self.data_type(ret) {
header.push(t);
header.push(text(" "));
}
}
if let Some(scope) = &f.scope {
header.push(text(format!("{scope}::")));
}
header.push(text(f.name.clone()));
if f.has_parens {
header.push(self.tf_args(&f.args));
}
header.push(text(";"));
// A prototype (`extern`/`pure virtual`) is the header and nothing
// else: no body, no `endfunction`.
if f.is_prototype {
return concat(header);
}
let mut body = Vec::new();
if !f.stmts.is_empty() {
body.push(Doc::HardLine);
body.extend(self.stmt_seq(&f.stmts));
}
body.extend(self.dangling(&f.dangling));
concat(vec![
concat(header),
indent(body),
Doc::HardLine,
Self::closing("endfunction", &f.end_label),
])
}
fn task(&self, t: &TaskDecl) -> Doc {
let mut header = Vec::new();
for q in &t.prefix {
header.push(text(format!("{q} ")));
}
header.push(text("task "));
for q in &t.qualifiers {
header.push(text(format!("{q} ")));
}
if let Some(scope) = &t.scope {
header.push(text(format!("{scope}::")));
}
header.push(text(t.name.clone()));
if t.has_parens {
header.push(self.tf_args(&t.args));
}
header.push(text(";"));
if t.is_prototype {
return concat(header);
}
let mut body = Vec::new();
if !t.stmts.is_empty() {
body.push(Doc::HardLine);
body.extend(self.stmt_seq(&t.stmts));
}
body.extend(self.dangling(&t.dangling));
concat(vec![
concat(header),
indent(body),
Doc::HardLine,
Self::closing("endtask", &t.end_label),
])
}
// ------------------------------------------------------------------
// Statements
// ------------------------------------------------------------------
fn stmt(&self, s: &Stmt) -> Doc {
self.with_meta(&s.meta, self.stmt_kind(&s.kind))
}
/// 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.
fn stmt_as_body(&self, prefix: Doc, s: &Stmt) -> Doc {
match &s.kind {
StmtKind::Block { label, stmts, dangling, end_label, .. } => {
let mut docs = vec![prefix, text(" ")];
docs.extend(self.leading(&s.meta));
docs.push(self.block_doc(label, stmts, dangling, 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(&s.meta));
let control_doc = self.timing_control(control);
docs.push(self.stmt_as_body(control_doc, inner));
docs.extend(self.trailing(&s.meta));
concat(docs)
}
_ => group(vec![prefix, indent(vec![Doc::Line, self.stmt(s)])]),
}
}
fn block_doc(
&self,
label: &Option<String>,
stmts: &[Stmt],
dangling: &[Comment],
end_label: &Option<String>,
) -> Doc {
let mut docs = vec![match label {
Some(l) => text(format!("begin : {l}")),
None => text("begin"),
}];
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("end", end_label));
concat(docs)
}
fn timing_control(&self, tc: &TimingControl) -> Doc {
match tc {
TimingControl::Delay(e) => concat(vec![text("#"), self.expr(e)]),
TimingControl::Event(sens) => self.sens_list(sens),
}
}
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(e) => concat(vec![text("@"), self.expr(e)]),
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) => {
// 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(format!("{e} ")));
}
parts.push(self.expr(&i.expr));
if self.inline_comments(&i.meta.before_sep, &mut parts) {
parts.push(Doc::HardLine);
}
}
let mut docs = vec![text("@(")];
docs.push(group(vec![indent(vec![Doc::SoftLine, concat(parts)]), Doc::SoftLine]));
docs.push(text(")"));
concat(docs)
}
}
}
fn stmt_kind(&self, kind: &StmtKind) -> Doc {
match kind {
StmtKind::Block { label, stmts, dangling, end_label, .. } => {
self.block_doc(label, stmts, dangling, end_label)
}
StmtKind::ForkJoin { label, join_kw, stmts, dangling, end_label, .. } => {
let mut docs = vec![match label {
Some(l) => text(format!("fork : {l}")),
None => text("fork"),
}];
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(join_kw, end_label));
concat(docs)
}
StmtKind::If { qualifier, cond, then, els } => self.if_stmt(qualifier, cond, then, els),
StmtKind::Case { qualifier, kw, expr, inside, items, dangling } => {
let mut head = String::new();
if let Some(q) = qualifier {
head.push_str(q);
head.push(' ');
}
head.push_str(kw);
head.push(' ');
let mut docs = vec![text(head), self.parens(expr)];
if *inside {
docs.push(text(" inside"));
}
let mut body = Vec::new();
for item in items {
body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
body.extend(self.leading(&item.meta));
body.push(self.case_item(item));
body.extend(self.trailing(&item.meta));
}
body.extend(self.dangling(dangling));
docs.push(indent(body));
docs.push(Doc::HardLine);
docs.push(text("endcase"));
concat(docs)
}
StmtKind::For { init, cond, step, body } => {
let mut header = vec![text("for (")];
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);
d.push(text(" "));
}
}
d.push(self.expr(&fi.assign.lhs));
d.push(text(format!(" {} ", fi.assign.op)));
d.push(self.expr(&fi.assign.rhs));
concat(d)
})
.collect();
header.extend(join(init_parts, text(", ")));
header.push(text("; "));
if let Some(c) = cond {
header.push(self.expr(c));
}
header.push(text("; "));
let step_parts: Vec<Doc> = step.iter().map(|s| self.for_step(s)).collect();
header.extend(join(step_parts, text(", ")));
header.push(text(")"));
self.stmt_as_body(concat(header), body)
}
StmtKind::While { cond, body } => {
self.stmt_as_body(concat(vec![text("while "), self.parens(cond)]), body)
}
StmtKind::DoWhile { body, cond } => {
let mut docs = vec![text("do")];
match &body.kind {
StmtKind::Block { label, stmts, dangling, end_label, .. } => {
docs.push(text(" "));
docs.push(self.block_doc(label, stmts, dangling, end_label));
docs.push(text(" while "));
}
_ => {
docs.push(group(vec![indent(vec![Doc::Line, self.stmt(body)])]));
docs.push(Doc::HardLine);
docs.push(text("while "));
}
}
docs.push(self.parens(cond));
docs.push(text(";"));
concat(docs)
}
StmtKind::Repeat { count, body } => {
self.stmt_as_body(concat(vec![text("repeat "), self.parens(count)]), body)
}
StmtKind::Forever { body } => self.stmt_as_body(text("forever"), body),
StmtKind::Foreach { target, vars, body } => {
let head = concat(vec![
text("foreach ("),
self.expr(target),
text(format!("[{}])", join_names(vars))),
]);
self.stmt_as_body(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), text(";")])
}
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(text(";"));
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, text(";")]),
}
}
StmtKind::Wait { cond, stmt } => {
let head = concat(vec![text("wait "), self.parens(cond)]);
match stmt {
Some(s) => self.stmt_as_body(head, s),
None => concat(vec![head, text(";")]),
}
}
StmtKind::ExprStmt(e) => concat(vec![self.expr(e), text(";")]),
StmtKind::EventTrigger(e) => concat(vec![text("-> "), self.expr(e), text(";")]),
StmtKind::VarDecl(d) => concat(vec![self.data_decl(d), text(";")]),
StmtKind::ParamDecl(d) => concat(vec![self.param_decl(d, None), text(";")]),
StmtKind::PortDecl(d) => concat(vec![self.port_decl(d), text(";")]),
StmtKind::Return(e) => match e {
Some(e) => concat(vec![text("return "), self.expr(e), text(";")]),
None => text("return;"),
},
StmtKind::Break => text("break;"),
StmtKind::Continue => text("continue;"),
StmtKind::Disable(name) => text(format!("disable {name};")),
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),
StmtKind::Assert { kw, cond, then, els } => {
let mut docs = vec![text(format!("{kw} ")), self.parens(cond)];
match (then, els) {
(None, None) => docs.push(text(";")),
(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(";"),
}
}
fn if_stmt(
&self,
qualifier: &Option<String>,
cond: &Expr,
then: &Stmt,
els: &Option<Box<Stmt>>,
) -> Doc {
let mut head = String::new();
if let Some(q) = qualifier {
head.push_str(q);
head.push(' ');
}
head.push_str("if ");
let prefix = concat(vec![text(head), self.parens(cond)]);
let then_is_block = matches!(then.kind, StmtKind::Block { .. });
let mut docs = vec![self.stmt_as_body(prefix, then)];
if let Some(els) = els {
if then_is_block {
docs.push(text(" else"));
} else {
docs.push(Doc::HardLine);
docs.push(text("else"));
}
// `else if` chains stay flat.
if let StmtKind::If { qualifier: eq, cond: ec, then: et, els: ee } = &els.kind {
docs.push(text(" "));
let mut meta_docs = self.leading(&els.meta);
docs.append(&mut meta_docs);
docs.push(self.if_stmt(eq, ec, et, ee));
docs.extend(self.trailing(&els.meta));
} else {
docs.push(self.stmt_as_body(text(""), els));
}
}
concat(docs)
}
/// 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.
fn case_labels(&self, labels: &[ExprItem]) -> Doc {
if labels.is_empty() {
return text("default:");
}
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 {
self.stmt_as_body(self.case_labels(&item.labels), &item.stmt)
}
// ------------------------------------------------------------------
// Expressions
// ------------------------------------------------------------------
fn binary_prec(op: &str) -> u8 {
match op {
"||" => 1,
"&&" => 2,
"|" => 3,
"^" | "^~" | "~^" => 4,
"&" => 5,
"==" | "!=" | "===" | "!==" | "==?" | "!=?" => 6,
"<" | "<=" | ">" | ">=" => 7,
"<<" | ">>" | "<<<" | ">>>" => 8,
"+" | "-" => 9,
"*" | "/" | "%" => 10,
"**" => 11,
_ => 0,
}
}
fn expr(&self, e: &Expr) -> Doc {
match &e.kind {
ExprKind::Ident(s) => text(s.clone()),
ExprKind::Number(s) => text(s.clone()),
ExprKind::Str(s) => text(s.clone()),
// Only reachable through `connection`, which handles the comments.
ExprKind::Empty(_) => text(""),
ExprKind::Unary { op, expr } => concat(vec![text(op.clone()), self.expr(expr)]),
ExprKind::Binary { .. } => self.binary_chain(e),
ExprKind::Ternary { cond, then, els, comments } => {
if comments.is_empty() {
return group(vec![
self.expr(cond),
indent(vec![
Doc::Line,
text("? "),
self.expr(then),
Doc::Line,
text(": "),
self.expr(els),
]),
]);
}
self.ternary_with_comments(cond, then, els, comments)
}
ExprKind::Call { callee, args } => {
concat(vec![self.expr(callee), self.expr_list("(", args, ")")])
}
ExprKind::Index { base, index } => {
concat(vec![self.expr(base), text("["), self.expr_compact(index), text("]")])
}
ExprKind::Range { base, op, msb, lsb } => concat(vec![
self.expr(base),
text("["),
self.expr_compact(msb),
text(op.clone()),
self.expr_compact(lsb),
text("]"),
]),
ExprKind::Member { base, name } => {
concat(vec![self.expr(base), text(format!(".{name}"))])
}
ExprKind::Scope { base, name } => {
concat(vec![self.expr(base), text(format!("::{name}"))])
}
// Written tight, like the `::` it almost always precedes.
ExprKind::Parameterized { base, params } => {
concat(vec![self.expr(base), self.raw_inline(params)])
}
ExprKind::Concat(items) => self.expr_list("{", items, "}"),
ExprKind::Repl { count, inner } => concat(vec![
text("{"),
self.expr(count),
self.expr_list("{", inner, "}"),
text("}"),
]),
ExprKind::Paren { inner, before, after } => {
if before.is_empty() && after.is_empty() {
return self.parens(inner);
}
// A comment inside the parens forces them open, the same way
// a comment inside a port list does.
let mut docs = vec![Doc::SoftLine];
for c in before {
docs.push(self.comment(c));
docs.push(Doc::HardLine);
}
docs.push(self.expr(inner));
let mut outer = vec![text("("), indent(docs)];
for c in after {
outer.push(text(" "));
outer.push(self.comment(c));
}
let ends_line = after.iter().any(|c| is_line_comment(&c.text));
outer.push(if ends_line { Doc::HardLine } else { Doc::SoftLine });
outer.push(text(")"));
group(outer)
}
ExprKind::Cast { ty, expr } => {
concat(vec![text(format!("{ty}'(")), self.expr(expr), text(")")])
}
ExprKind::AssignPattern(items) => {
let items: Vec<ListItem> = items
.iter()
.map(|pi| {
let mut d = Vec::new();
if let Some(k) = &pi.key {
d.push(self.expr(k));
d.push(text(": "));
}
d.push(self.expr(&pi.value));
ListItem::from_meta(&pi.meta, concat(d))
})
.collect();
self.delimited("'{", items, "}", false)
}
ExprKind::Postfix { expr, op } => concat(vec![self.expr(expr), text(op.clone())]),
ExprKind::Inside { lhs, ranges } => {
concat(vec![self.expr(lhs), text(" inside "), self.expr_list("{", ranges, "}")])
}
// A named call argument, printed the way a named connection is:
// `.name(value)`, tight, with a break opportunity inside.
ExprKind::NamedArg { name, value, close_comments, .. } => match &value.kind {
ExprKind::Empty(comments) => {
let mut docs = vec![text(format!(".{name}("))];
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)
}
_ => {
let mut inner = vec![Doc::SoftLine, self.expr(value)];
let ends_line = self.inline_comments(close_comments, &mut inner);
let close = if ends_line { Doc::HardLine } else { Doc::SoftLine };
concat(vec![
text(format!(".{name}(")),
group(vec![indent(inner), close]),
text(")"),
])
}
},
ExprKind::ValueRange { lo, hi } => {
concat(vec![text("["), self.expr(lo), text(":"), self.expr(hi), text("]")])
}
ExprKind::Type(ty) => self.data_type(ty).unwrap_or_else(|| text("")),
ExprKind::MinTypMax { min, typ, max } => {
concat(vec![self.expr(min), text(":"), self.expr(typ), text(":"), self.expr(max)])
}
}
}
/// A `? :` with comments written inside it. Each comment stays between the
/// two tokens it was written between, and a line comment forces the break
/// that follows it, so the layout can never fold a comment over the `?`,
/// the `:` or an operand.
fn ternary_with_comments(
&self,
cond: &Expr,
then: &Expr,
els: &Expr,
comments: &TernaryComments,
) -> Doc {
let mut head = vec![self.expr(cond)];
let hard = self.inline_comments(&comments.before_question, &mut head);
let mut inner = vec![if hard { Doc::HardLine } else { Doc::Line }];
inner.push(text("?"));
let hard = self.inline_comments(&comments.after_question, &mut inner);
inner.push(if hard { Doc::HardLine } else { text(" ") });
inner.push(self.expr(then));
let hard = self.inline_comments(&comments.before_colon, &mut inner);
inner.push(if hard { Doc::HardLine } else { Doc::Line });
inner.push(text(":"));
let hard = self.inline_comments(&comments.after_colon, &mut inner);
inner.push(if hard { Doc::HardLine } else { text(" ") });
inner.push(self.expr(els));
head.push(indent(inner));
group(head)
}
/// Flatten a left-nested chain of same-precedence binary operators so
/// `a + b + c` breaks as one unit instead of stair-stepping. An operator
/// carrying comments (written after the operand before it) starts its own
/// line, so the comment stays last on the line it was written on.
fn binary_chain(&self, e: &Expr) -> Doc {
let ExprKind::Binary { op, .. } = &e.kind else { unreachable!() };
let prec = Self::binary_prec(op);
let mut operands: Vec<&Expr> = Vec::new();
let mut ops: Vec<BinaryOp<'_>> = Vec::new();
fn walk<'e>(
e: &'e Expr,
prec: u8,
operands: &mut Vec<&'e Expr>,
ops: &mut Vec<BinaryOp<'e>>,
) {
match &e.kind {
ExprKind::Binary { lhs, op, rhs, comments } if Fmt::binary_prec(op) == prec => {
walk(lhs, prec, operands, ops);
ops.push(BinaryOp { op, before: &comments.before, after: &comments.after });
operands.push(rhs);
}
_ => operands.push(e),
}
}
walk(e, prec, &mut operands, &mut ops);
let mut docs = vec![self.expr(operands[0])];
let mut cont = Vec::new();
for (op, rhs) in ops.iter().zip(operands[1..].iter()) {
// Comments written before the operator stay on the left operand's
// line; the operator then starts a new one.
self.inline_comments(op.before, &mut cont);
if op.before.is_empty() {
cont.push(text(format!(" {}", op.op)));
} else {
cont.push(Doc::HardLine);
cont.push(text(op.op.to_string()));
}
// Comments written after the operator stay on the operator's line;
// the right operand then starts a new one.
let hard = self.inline_comments(op.after, &mut cont);
if hard {
cont.push(Doc::HardLine);
} else if !op.after.is_empty() || !op.before.is_empty() {
cont.push(text(" "));
} else {
cont.push(Doc::Line);
}
cont.push(self.expr(rhs));
}
docs.push(indent(cont));
group(docs)
}
}
/// A comma-separated list of names, as the source wrote them. The parser
/// keeps each name's byte range alongside its text, so the joined spelling is
/// rebuilt here rather than stored.
fn join_names(names: &[Name]) -> String {
names.iter().map(|n| n.text.as_str()).collect::<Vec<_>>().join(", ")
}
/// The same for a list of `pkg::item` import paths.
fn join_paths(paths: &[ImportPath]) -> String {
paths.iter().map(ImportPath::text).collect::<Vec<_>>().join(", ")
}
/// Drop up to `n` leading spaces or tabs.
/// True if any line break in `text` falls inside a string literal, making
/// every byte of the following line part of that string's value rather than
/// layout. See [`crate::verify::line_starts_inside_string`].
fn crosses_line_inside_string(text: &str) -> bool {
text.contains('\n') && line_starts_inside_string(text).iter().skip(1).any(|&inside| inside)
}
fn strip_blanks(line: &str, n: usize) -> &str {
let mut rest = line;
for _ in 0..n {
match rest.strip_prefix(' ').or_else(|| rest.strip_prefix('\t')) {
Some(shorter) => rest = shorter,
None => break,
}
}
rest
}
/// True for `// ...` comments, which must end their line.
fn is_line_comment(text: &str) -> bool {
text.starts_with("//")
}