Files
lucisv/crates/vlog_formatter/src/format.rs
T
lucioandClaude Fable 5 1ac9746c45 Add workspace-index and name-spans (jointly: round 10)
workspace-index (vlog_semantic): cross-file resolution -- the
owner's `import pkg::*;`-anywhere requirement delivered.
WorkspaceIndex maps modules/packages/file-scope typedefs, package
exports, module ports/params and per-file define tables; built
tolerantly (broken files still contribute), deterministic by
construction (FileIds assigned after path sort). resolve_external
answers ExternalCandidates in a two-layer overlay keyed by
ReferenceId -- Semantics stays a pure single-file fact; local
declarations outrank imports. Corpus: 87% of external candidates
answered (external rate 19.6% -> 2.6% on clean files), ambiguity
kept honest (OpenTitan prim_generic/prim_xilinx), 0.7s build,
workspace_symbols substring search.

name-spans (vlog_parser): the approved vlog-semantic handshake --
the parser records every declared name's span at parse time (28
fields across 21 node kinds; Name/ImportPath bundles where parallel
Vecs could desync; ImportPath splits p::x for the index). Content-
pinned by the exhaustive walker on every source, mutation-tested
three ways, zero behavior change (corpus md5 exact, QA byte-compared
formatter output against a HEAD worktree). scan.rs is now one
consumer away from deletion (DataType span, handshake item 2).

TODO §6 foundations complete: spans, error recovery, define table,
single-file semantics, workspace index. Next: vfmt_server.

Dev: 2 Opus agents; QA: 2 Sonnet agents; reviews in
docs/features/{workspace-index,name-spans}/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-19 07:09:04 -07:00

1987 lines
76 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::doc::*;
use crate::fence::{self, Region};
use crate::printer::{contains_hard_line, Printer};
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 }
}
}
/// 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)
}
/// 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);
let fmt = Fmt { _cfg: config, src: source, regions };
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');
Ok(out)
}
struct Fmt<'a> {
_cfg: &'a Config,
/// The text the AST was parsed from — what `// verilog_format: off`
/// regions are spliced out of.
src: &'a str,
/// The fenced regions of `src`, sorted and non-overlapping.
regions: Vec<Region>,
}
/// 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>,
}
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(),
}
}
}
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)
}
/// 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 fenced region, i.e. its bytes are
/// already being emitted verbatim and it must not be formatted.
fn is_fenced(&self, span: TextRange) -> bool {
fence::region_at(&self.regions, span.start as usize).is_some()
}
/// 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 {
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);
}
if !docs.is_empty() {
docs.push(Doc::HardLine);
}
docs
}
/// Leading comments (each on its own line) preceding a node.
fn leading(&self, meta: &Meta) -> Vec<Doc> {
let mut docs = self.leading_comments(meta);
for attr in &meta.attrs {
docs.push(self.raw_text(attr));
docs.push(Doc::HardLine);
}
docs
}
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();
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 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)
}
/// 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]) -> Vec<Doc> {
let mut docs = Vec::new();
for item in items {
let item_docs = self.item_docs(item);
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);
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) -> Doc {
concat(self.item_docs(item))
}
/// One item: its leading comments, then — unless a fenced 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) -> Vec<Doc> {
let mut docs = self.leading_comments(&item.meta);
if self.is_fenced(item.span) {
// 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;
}
for attr in &item.meta.attrs {
docs.push(self.raw_text(attr));
docs.push(Doc::HardLine);
}
docs.push(self.item_kind(&item.kind));
docs.extend(self.trailing(&item.meta));
docs
}
fn item_kind(&self, kind: &ItemKind) -> Doc {
match kind {
ItemKind::Module(m) => self.module(m),
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));
}
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),
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), 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),
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));
}
body.extend(self.dangling(dangling));
concat(vec![text("generate"), indent(body), Doc::HardLine, text("endgenerate")])
}
ItemKind::GenIf(g) => self.gen_if(g),
ItemKind::GenFor(g) => self.gen_for(g),
ItemKind::GenCase(g) => self.gen_case(g),
ItemKind::Function(f) => self.function(f),
ItemKind::Task(t) => self.task(t),
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) -> 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;
// 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))).collect();
docs.push(text(if on_fresh_line { "#" } else { " #" }));
docs.push(self.delimited_dangling("(", items, &m.param_dangling, ")", false));
on_fresh_line = false;
}
match &m.ports {
PortList::None => docs.push(text(";")),
PortList::Empty => {
if !on_fresh_line {
docs.push(text(" "));
}
docs.push(self.delimited_dangling("(", Vec::new(), &m.port_dangling, ")", false));
docs.push(text(";"));
}
PortList::Ansi(_) | PortList::NonAnsi(_) => {
let items: Vec<ListItem> = match &m.ports {
PortList::Ansi(ports) => ports
.iter()
.map(|p| ListItem::from_meta(&p.meta, self.ansi_port(p)))
.collect(),
PortList::NonAnsi(ports) => ports
.iter()
.map(|p| ListItem::from_meta(&p.meta, text(p.name.clone())))
.collect(),
_ => unreachable!(),
};
if !on_fresh_line {
docs.push(text(" "));
}
docs.push(self.delimited_dangling("(", items, &m.port_dangling, ")", false));
docs.push(text(";"));
}
}
let mut body = Vec::new();
if !m.items.is_empty() {
body.push(Doc::HardLine);
body.extend(self.item_seq(&m.items));
}
body.extend(self.dangling(&m.dangling));
docs.push(indent(body));
docs.push(Doc::HardLine);
docs.push(Self::closing("endmodule", &m.end_label));
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) -> Doc {
let mut docs = Vec::new();
if let Some(dir) = &p.dir {
docs.push(text(format!("{dir} ")));
}
if let Some(net) = &p.net {
docs.push(text(format!("{net} ")));
}
if let Some(t) = self.data_type(&p.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(self.expr(d));
}
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;
}
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 {
let mut docs = vec![text("["), self.expr_compact(&d.a)];
if let Some(b) = &d.b {
docs.push(text(":"));
docs.push(self.expr_compact(b));
}
docs.push(text("]"));
concat(docs)
}
/// 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)])
}
fn param_decl(&self, d: &ParamDecl) -> Doc {
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)
}
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::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))
})
.collect();
// `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.
docs.push(self.delimited_dangling("{", items, &e.dangling, "}", false));
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) -> Doc {
let mut docs = vec![text(inst.module.clone())];
// 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))).collect();
docs.push(text(" #"));
docs.push(self.delimited("(", items, ")", false));
}
docs.push(text(" "));
if let [only] = &inst.instances[..] {
// The common case: no extra indent level, so a connection list
// that breaks lines up under the instance itself.
docs.push(self.instance(only));
} else {
// 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));
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) -> 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));
}
}
docs.push(text(" "));
docs.push(self.connections(&instance.conns));
concat(docs)
}
fn connections(&self, conns: &Connections) -> Doc {
match conns {
Connections::Named(list) => {
let items: Vec<ListItem> =
list.iter().map(|c| ListItem::from_meta(&c.meta, self.connection(c))).collect();
self.delimited("(", items, ")", false)
}
Connections::Ordered(list) => {
let items: Vec<ListItem> = list
.iter()
.map(|c| {
let d = match &c.expr {
Some(e) => self.expr(e),
None => text(""),
};
ListItem::from_meta(&c.meta, d)
})
.collect();
self.delimited("(", items, ")", false)
}
}
}
fn connection(&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) -> Doc {
let mut docs = vec![text("if "), self.parens(&g.cond)];
let mut cuddle = self.gen_block(&mut docs, &g.then);
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);
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);
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) -> 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));
}
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)])]));
false
}
}
fn gen_for(&self, g: &GenFor) -> 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);
concat(docs)
}
fn gen_case(&self, g: &GenCase) -> 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);
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)
}
fn function(&self, f: &FunctionDecl) -> Doc {
let mut header = vec![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(" "));
}
}
header.push(text(f.name.clone()));
if f.has_parens {
header.push(self.tf_args(&f.args));
}
header.push(text(";"));
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![text("task ")];
for q in &t.qualifiers {
header.push(text(format!("{q} ")));
}
header.push(text(t.name.clone()));
if t.has_parens {
header.push(self.tf_args(&t.args));
}
header.push(text(";"));
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 {
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, 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)];
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, timing, rhs } => {
let mut docs = vec![self.expr(lhs), 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));
docs.push(self.assign_rhs(concat(rhs_docs)));
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), 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}"))])
}
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, "}")])
}
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("//")
}