Files
lucisv/crates/vlog_formatter/src/format.rs
T
lucioandClaude Fable 5 d2cd44c428 Normalize whole tree with cargo fmt under rustfmt.toml
One-time mechanical pass; no behavior change (full test suite green
before and after). From here on, cargo fmt --check is the standard.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-18 23:41:18 -07:00

1479 lines
54 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::printer::Printer;
use crate::verify::{verify_convergence, verify_equivalence, VerificationError};
use vlog_parser::ast::*;
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 fmt = Fmt { _cfg: config };
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,
}
/// A list element ready for comma-list layout.
struct ListItem {
leading: Vec<Comment>,
doc: Doc,
trailing: Option<String>,
blank_before: bool,
}
impl ListItem {
fn plain(doc: Doc) -> Self {
ListItem { leading: Vec::new(), doc, trailing: None, blank_before: false }
}
fn from_meta(meta: &Meta, doc: Doc) -> Self {
ListItem {
leading: meta.leading.clone(),
doc,
trailing: meta.trailing.clone(),
blank_before: meta.blank_before,
}
}
}
impl<'a> Fmt<'a> {
// ------------------------------------------------------------------
// Shared helpers
// ------------------------------------------------------------------
/// Turn possibly-multi-line raw text (comments, directives) into a Doc.
fn raw_text(&self, s: &str) -> Doc {
let lines: Vec<&str> = s.split('\n').collect();
if lines.len() == 1 {
return text(s);
}
let mut docs = Vec::new();
for (i, line) in lines.iter().enumerate() {
if i > 0 {
docs.push(Doc::HardLine);
}
docs.push(text(line.trim_end()));
}
concat(docs)
}
/// Leading comments (each on its own line) preceding a node.
fn leading(&self, meta: &Meta) -> Vec<Doc> {
let mut docs = Vec::new();
for (i, c) in meta.leading.iter().enumerate() {
if i > 0 && c.blank_before {
docs.push(Doc::BlankLine);
}
docs.push(self.raw_text(&c.text));
docs.push(Doc::HardLine);
}
for attr in &meta.attrs {
docs.push(self.raw_text(attr));
docs.push(Doc::HardLine);
}
docs
}
fn trailing(&self, meta: &Meta) -> Vec<Doc> {
match &meta.trailing {
Some(tr) => vec![text(format!(" {tr}"))],
None => Vec::new(),
}
}
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 {
if items.is_empty() {
return text(format!("{open}{close}"));
}
let mut inner: Vec<Doc> = vec![if force_break { Doc::HardLine } else { Doc::SoftLine }];
let last = items.len() - 1;
let mut close_needs_hardline = force_break;
for (i, item) in items.into_iter().enumerate() {
if i > 0 {
// separator emitted below along with the previous trailing
}
let meta = Meta {
leading: item.leading,
trailing: None,
blank_before: false,
attrs: Vec::new(),
};
inner.extend(self.leading(&meta));
inner.push(item.doc);
if i < last {
inner.push(text(","));
}
if let Some(tr) = item.trailing {
inner.push(text(format!(" {tr}")));
if i < last {
inner.push(Doc::HardLine);
} else {
close_needs_hardline = true;
}
} else if i < last {
inner.push(Doc::Line);
}
}
// 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)
}
/// `( 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/statements at one indent level, preserving single
/// blank lines between them.
fn item_seq(&self, items: &[Item]) -> Vec<Doc> {
let mut docs = Vec::new();
for (i, item) in items.iter().enumerate() {
if i > 0 {
docs.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
}
docs.push(self.item(item));
}
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 {
if c.blank_before {
docs.push(Doc::BlankLine);
} else {
docs.push(Doc::HardLine);
}
docs.push(self.raw_text(&c.text));
}
docs
}
// ------------------------------------------------------------------
// File / items
// ------------------------------------------------------------------
fn file(&self, f: &SourceFile) -> Doc {
let mut docs = self.item_seq(&f.items);
for (i, c) in f.dangling.iter().enumerate() {
if !docs.is_empty() || i > 0 {
docs.push(if c.blank_before { Doc::BlankLine } else { Doc::HardLine });
}
docs.push(self.raw_text(&c.text));
}
concat(docs)
}
fn item(&self, item: &Item) -> Doc {
self.with_meta(&item.meta, self.item_kind(&item.kind))
}
fn item_kind(&self, kind: &ItemKind) -> Doc {
match kind {
ItemKind::Module(m) => self.module(m),
ItemKind::Package { kw, name, items, dangling } => {
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(text("endpackage"));
concat(docs)
}
ItemKind::Directive(d) => self.raw_text(d),
ItemKind::Import(paths) => text(format!("import {};", paths.join(", "))),
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 {};", names.join(", "))),
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 {
docs.push(indent(vec![
Doc::HardLine,
text(format!("import {};", m.imports.join(", "))),
]));
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;
if !m.param_ports.is_empty() {
let items: Vec<ListItem> = m
.param_ports
.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("(", items, ")", false));
on_fresh_line = false;
}
match &m.ports {
PortList::None => docs.push(text(";")),
PortList::Empty => docs.push(text(if on_fresh_line { "();" } else { " ();" })),
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("(", items, ")", 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(match &m.end_label {
Some(l) => text(format!("endmodule : {l}")),
None => text("endmodule"),
});
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 {
Expr::Binary { lhs, op, rhs } => {
let tight = Self::binary_prec(op) >= 8;
let sep = if tight { op.clone() } else { format!(" {op} ") };
concat(vec![self.expr_compact(lhs), text(sep), self.expr_compact(rhs)])
}
Expr::Ternary { cond, then, els } => concat(vec![
self.expr_compact(cond),
text(" ? "),
self.expr_compact(then),
text(" : "),
self.expr_compact(els),
]),
Expr::Paren(inner) => concat(vec![text("("), self.expr_compact(inner), text(")")]),
Expr::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![indent(vec![Doc::Line, 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,
trailing: None,
blank_before: false,
attrs: Vec::new(),
});
docs.push(item.doc);
if let Some(tr) = item.trailing {
docs.push(text(format!(" {tr}")));
}
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,
trailing: None,
blank_before: false,
attrs: Vec::new(),
};
inner.extend(self.leading(&meta));
inner.push(item.doc);
if i < last {
inner.push(text(","));
}
if let Some(tr) = item.trailing {
inner.push(text(format!(" {tr}")));
if i < last {
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();
docs.push(self.delimited("{", items, "}", 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));
if let Some(tr) = &m.meta.trailing {
inner.push(text(format!(" {tr}")));
}
}
inner.extend(self.dangling(&s.dangling));
concat(vec![
text(header),
indent(inner),
Doc::HardLine,
text(format!("}} {};", t.name)),
])
}
}
}
// ------------------------------------------------------------------
// Module items
// ------------------------------------------------------------------
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| {
let d = group(vec![
self.expr(&p.lhs),
text(" ="),
indent(vec![Doc::Line, self.expr(&p.rhs)]),
]);
ListItem::from_meta(&p.meta, d)
})
.collect();
if items.len() == 1 {
let item = items.into_iter().next().unwrap();
docs.push(item.doc);
docs.push(text(";"));
if let Some(tr) = item.trailing {
docs.push(text(format!(" {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 i < last {
inner.push(text(","));
} else {
inner.push(text(";"));
}
if let Some(tr) = item.trailing {
inner.push(text(format!(" {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())];
if !inst.params.is_empty() {
let items: Vec<ListItem> = inst
.params
.iter()
.map(|c| ListItem::from_meta(&c.meta, self.connection(c)))
.collect();
docs.push(text(" #"));
docs.push(self.delimited("(", items, ")", false));
}
let single = inst.instances.len() == 1;
for (i, instance) in inst.instances.iter().enumerate() {
if i > 0 {
docs.push(text(","));
docs.push(Doc::HardLine);
} else {
docs.push(text(" "));
}
let _ = single;
docs.push(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));
}
docs.push(text(";"));
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::Empty) => text(format!(".{}()", c.name)),
Some(e) => concat(vec![
text(format!(".{}(", c.name)),
group(vec![indent(vec![Doc::SoftLine, self.expr(e)]), Doc::SoftLine]),
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(" "));
}
let items: Vec<ListItem> =
inst.args.iter().map(|a| ListItem::plain(self.expr(a))).collect();
docs.push(self.delimited("(", items, ")", false));
}
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(text("end"));
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 label = if item.labels.is_empty() {
text("default:")
} else {
let labels: Vec<Doc> = item.labels.iter().map(|l| self.expr(l)).collect();
concat(vec![concat(join(labels, text(", "))), text(":")])
};
let mut item_docs = vec![label];
self.gen_block(&mut item_docs, &item.body);
body.push(concat(item_docs));
if let Some(tr) = &item.meta.trailing {
body.push(text(format!(" {tr}")));
}
}
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, text("endfunction")])
}
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, text("endtask")])
}
// ------------------------------------------------------------------
// 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 } => {
let mut docs = vec![prefix, text(" ")];
docs.extend(self.leading(&s.meta));
docs.push(self.block_doc(label, stmts, dangling));
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]) -> 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(text("end"));
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 => text("@(*)"),
SensList::List(items) => {
let any_edge = items.iter().any(|i| i.edge.is_some());
let sep = if any_edge { text(" or ") } else { text(", ") };
let parts: Vec<Doc> = items
.iter()
.map(|i| {
let mut d = Vec::new();
if let Some(e) = &i.edge {
d.push(text(format!("{e} ")));
}
d.push(self.expr(&i.expr));
concat(d)
})
.collect();
let mut docs = vec![text("@(")];
docs.push(group(vec![
indent(vec![Doc::SoftLine, concat(join(parts, sep))]),
Doc::SoftLine,
]));
docs.push(text(")"));
concat(docs)
}
}
}
fn stmt_kind(&self, kind: &StmtKind) -> Doc {
match kind {
StmtKind::Block { label, stmts, dangling } => self.block_doc(label, stmts, dangling),
StmtKind::ForkJoin { label, join_kw, stmts, dangling } => {
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(text(join_kw.clone()));
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));
if let Some(tr) = &item.meta.trailing {
body.push(text(format!(" {tr}")));
}
}
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 } => {
docs.push(text(" "));
docs.push(self.block_doc(label, stmts, dangling));
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!("[{}])", vars.join(", "))),
]);
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(indent(vec![Doc::Line, 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),
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));
if let Some(tr) = &els.meta.trailing {
docs.push(text(format!(" {tr}")));
}
} else {
docs.push(self.stmt_as_body(text(""), els));
}
}
concat(docs)
}
fn case_item(&self, item: &CaseItem) -> Doc {
let label = if item.labels.is_empty() {
text("default:")
} else {
let labels: Vec<Doc> = item.labels.iter().map(|l| self.expr(l)).collect();
concat(vec![concat(join(labels, text(", "))), text(":")])
};
self.stmt_as_body(label, &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 {
Expr::Ident(s) => text(s.clone()),
Expr::Number(s) => text(s.clone()),
Expr::Str(s) => text(s.clone()),
Expr::Empty => text(""),
Expr::Unary { op, expr } => concat(vec![text(op.clone()), self.expr(expr)]),
Expr::Binary { .. } => self.binary_chain(e),
Expr::Ternary { cond, then, els } => group(vec![
self.expr(cond),
indent(vec![
Doc::Line,
text("? "),
self.expr(then),
Doc::Line,
text(": "),
self.expr(els),
]),
]),
Expr::Call { callee, args } => {
let items: Vec<ListItem> =
args.iter().map(|a| ListItem::plain(self.expr(a))).collect();
concat(vec![self.expr(callee), self.delimited("(", items, ")", false)])
}
Expr::Index { base, index } => {
concat(vec![self.expr(base), text("["), self.expr_compact(index), text("]")])
}
Expr::Range { base, op, msb, lsb } => concat(vec![
self.expr(base),
text("["),
self.expr_compact(msb),
text(op.clone()),
self.expr_compact(lsb),
text("]"),
]),
Expr::Member { base, name } => concat(vec![self.expr(base), text(format!(".{name}"))]),
Expr::Scope { base, name } => concat(vec![self.expr(base), text(format!("::{name}"))]),
Expr::Concat(items) => {
let items: Vec<ListItem> =
items.iter().map(|i| ListItem::plain(self.expr(i))).collect();
self.delimited("{", items, "}", false)
}
Expr::Repl { count, inner } => {
let inner_docs: Vec<Doc> = inner.iter().map(|i| self.expr(i)).collect();
concat(vec![
text("{"),
self.expr(count),
text("{"),
concat(join(inner_docs, text(", "))),
text("}}"),
])
}
Expr::Paren(inner) => self.parens(inner),
Expr::Cast { ty, expr } => {
concat(vec![text(format!("{ty}'(")), self.expr(expr), text(")")])
}
Expr::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::plain(concat(d))
})
.collect();
self.delimited("'{", items, "}", false)
}
Expr::Postfix { expr, op } => concat(vec![self.expr(expr), text(op.clone())]),
Expr::Inside { lhs, ranges } => {
let items: Vec<ListItem> =
ranges.iter().map(|r| ListItem::plain(self.expr(r))).collect();
concat(vec![
self.expr(lhs),
text(" inside "),
self.delimited("{", items, "}", false),
])
}
Expr::ValueRange { lo, hi } => {
concat(vec![text("["), self.expr(lo), text(":"), self.expr(hi), text("]")])
}
Expr::Type(ty) => self.data_type(ty).unwrap_or_else(|| text("")),
Expr::MinTypMax { min, typ, max } => {
concat(vec![self.expr(min), text(":"), self.expr(typ), text(":"), self.expr(max)])
}
}
}
/// Flatten a left-nested chain of same-precedence binary operators so
/// `a + b + c` breaks as one unit instead of stair-stepping.
fn binary_chain(&self, e: &Expr) -> Doc {
let Expr::Binary { op, .. } = e else { unreachable!() };
let prec = Self::binary_prec(op);
let mut operands: Vec<&Expr> = Vec::new();
let mut ops: Vec<&str> = Vec::new();
fn walk<'e>(e: &'e Expr, prec: u8, operands: &mut Vec<&'e Expr>, ops: &mut Vec<&'e str>) {
match e {
Expr::Binary { lhs, op, rhs } if Fmt::binary_prec(op) == prec => {
walk(lhs, prec, operands, ops);
ops.push(op);
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()) {
cont.push(text(format!(" {op}")));
cont.push(Doc::Line);
cont.push(self.expr(rhs));
}
docs.push(indent(cont));
group(docs)
}
}