//! Classes and constraints: the `class` header and body, and every //! constraint form — the `constraint c { ... }` declaration, a //! `randomize() with { ... }` block, the `->`/`if`/`foreach`/`solve`/ //! `unique` items, and the `dist` weight list an expression may end in. //! //! Covergroups, the other DV construct a class holds, are large enough //! to be a sibling module (`cover.rs`). use crate::doc::*; use crate::printer::contains_hard_line; use vlog_parser::ast::*; use vlog_parser::token::Comment; use super::list::ListItem; use super::{join_names, named, Fmt}; impl<'a> Fmt<'a> { /// A class: header on one line (its parameter and `extends` override /// lists break like any other list when they do not fit), body items at /// one more indent level, `endclass` with the label the source wrote. pub(super) fn class(&self, c: &ClassDecl, depth: usize) -> Doc { let mut docs = Vec::new(); self.qualifier_run(&c.prefix, &mut docs); docs.push(text("class")); // `class /*c*/ c` — and, when a lifetime was written, whatever stood // on either side of it; both gaps land in the one slot, which prints // between the keyword run and the name. if c.before_name.is_empty() { docs.push(text(" ")); } else { self.inline_comments_spaced(&c.before_name, &mut docs); } if let Some(lifetime) = &c.lifetime { docs.push(text(format!("{lifetime} "))); } docs.push(text(named(&c.name))); let on_fresh_line = self.bracket_comments(&c.param_comments, &mut docs, false); if let Some(params) = &c.param_ports { let items: Vec = params .iter() .map(|p| { self.list_elem(p, |p| { ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma) }) }) .collect(); let items = self.list_entries(items, &c.param_directives); let broken = !c.param_directives.is_empty(); docs.push(text(if on_fresh_line { "#" } else { " #" })); self.slot_comments(&c.param_after_hash, &mut docs); docs.push(self.delimited_dangling("(", items, &c.param_dangling, ")", broken)); } if let Some(ext) = &c.extends { docs.push(text(format!(" extends {}", named(&ext.name)))); let fresh = self.bracket_comments(&ext.param_comments, &mut docs, false); if let Some(params) = &ext.params { let items: Vec = params .iter() .map(|p| { self.list_elem(p, |p| { ListItem::from_meta(&p.meta, self.connection(p)).with_comma(p.comma) }) }) .collect(); let items = self.list_entries(items, &ext.param_directives); let broken = !ext.param_directives.is_empty(); docs.push(text(if fresh { "#" } else { " #" })); self.slot_comments(&ext.after_hash, &mut docs); docs.push(self.delimited("(", items, ")", broken)); } } if !c.implements.is_empty() { docs.push(text(format!(" implements {}", join_names(&c.implements)))); } docs.push(self.semi(&c.before_semi)); let mut body = Vec::new(); if !c.items.is_empty() { body.push(Doc::HardLine); body.extend(self.item_seq(&c.items, depth + 1)); } body.extend(self.dangling(&c.dangling)); docs.push(indent(body)); docs.push(Doc::HardLine); docs.push(self.closing_labeled("endclass", &c.end_label, &c.end_label_comments)); concat(docs) } /// `[qualifiers ]constraint [cls::]name { ... }`, or the `constraint c;` /// prototype. /// /// A named constraint is a *block*, so it is laid out like one: the /// header keeps the `{`, every constraint item takes a line of its own at /// one further indent, and the `}` closes back at the header's column. /// That supersedes the `classes` README's "no layout convention worth /// inventing" — there was none while the body was opaque bytes; now that /// it is navigable, one canonical shape is worth exactly what canonical /// shapes are always worth. pub(super) fn constraint(&self, c: &ConstraintDecl) -> Doc { let mut docs = Vec::new(); self.qualifier_run(&c.qualifiers, &mut docs); docs.push(text("constraint")); self.inline_comments_spaced(&c.before_name, &mut docs); self.scope_prefix(&c.scope, &mut docs); let name = named(&c.name.text); // `named` already wrote the space an escaped identifier needs; a // second one would be a gratuitous re-spacing of the header. let escaped = name.ends_with(' '); docs.push(text(name)); let ends_line = self.inline_comments(&c.after_name, &mut docs); let Some(set) = &c.body else { if ends_line { docs.push(Doc::HardLine); } docs.push(text(";")); return concat(docs); }; if ends_line { docs.push(Doc::HardLine); } else if !escaped || !c.after_name.is_empty() { docs.push(text(" ")); } docs.push(self.constraint_block(set, false)); if c.semi { if self.inline_comments(&c.before_semi, &mut docs) { docs.push(Doc::HardLine); } docs.push(text(";")); } concat(docs) } /// The `{ ... }` of a constraint body or a nested constraint set. /// /// `flat_ok` allows the whole block onto one line when nothing inside it /// forces a break — the shape a `randomize() with { addr == 0; }` is /// written in. A `constraint` declaration never passes it: a declaration /// is a block and reads as one. fn constraint_block(&self, set: &ConstraintSet, flat_ok: bool) -> Doc { let brk = if flat_ok { Doc::SoftLine } else { Doc::HardLine }; let mut body = Vec::new(); if !set.items.is_empty() { body.push(brk.clone()); body.extend(self.constraint_items(&set.items)); } body.extend(self.dangling(&set.dangling)); if body.is_empty() { return text("{}"); } group(vec![text("{"), indent(body), brk, text("}")]) } /// The block of a `randomize() with { ... }`: the same layout, but kept on /// the statement's line when the **source** wrote it on one line. /// /// A `with` block is written inside a statement, not standing as a /// declaration, and `if (!req.randomize() with { addr == 0; })` is the /// idiom every DV testbench writes. The question is asked of the source /// rather than measured, for two reasons. It is a fact about the gap /// between two tokens, which is the one thing the formatter already reads /// `src` for (`glued_null_item`, `default_has_colon`). And it is a fixed /// point by construction: a flattened block is one line, so the next pass /// flattens it again; a broken one holds newlines, so the next pass /// breaks it again. /// /// Reading the source also settles the `//` question for free: a line /// comment needs a newline to end, so a one-line block cannot hold one, /// and a flattened `}` can never land inside a comment. The /// `contains_hard_line` check is the belt to that braces — anything else /// that forces a break takes the block layout. pub(super) fn with_constraint_block(&self, set: &ConstraintSet) -> Doc { if self.src.get(set.span.as_range()).is_some_and(|s| !s.contains('\n')) { let flat = self.constraint_block(set, true); if !contains_hard_line(std::slice::from_ref(&flat)) { return flat; } } self.constraint_block(set, false) } fn constraint_items(&self, items: &[ConstraintItem]) -> Vec { 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.with_meta(&item.meta, self.constraint_item(item))); } docs } /// One constraint item, and the `;` that ends it when its kind takes one. /// /// The `;` is written here rather than in each arm so that the comments /// the source wrote in front of it have exactly one place to be printed: /// on the item's side of the separator, which is where they were /// written. [`ConstraintItemKind::takes_semi`] is the one answer both /// this and the parser read. fn constraint_item(&self, item: &ConstraintItem) -> Doc { let mut docs = vec![self.constraint_item_kind(&item.kind)]; if item.kind.takes_semi() { if self.inline_comments(&item.before_semi, &mut docs) { docs.push(Doc::HardLine); } docs.push(text(";")); } concat(docs) } fn constraint_item_kind(&self, kind: &ConstraintItemKind) -> Doc { match kind { ConstraintItemKind::Expr { soft, after_soft, expr } => { if !*soft { return self.expr(expr); } let mut docs = vec![text("soft")]; self.inline_comments_spaced(after_soft, &mut docs); docs.push(self.expr(expr)); concat(docs) } ConstraintItemKind::Implication { cond, comments, set } => { let mut head = vec![self.expr(cond)]; self.inline_comments_spaced(&comments.before, &mut head); head.push(text("->")); let ends_line = self.inline_comments(&comments.after, &mut head); if ends_line { head.push(Doc::HardLine); } self.constraint_set_as_body(concat(head), set, &[], !ends_line) } ConstraintItemKind::If { cond, comments, then, else_comments, after_else, els } => { let mut head = vec![text("if")]; self.inline_comments_spaced(&comments.after_kw, &mut head); head.push(self.constraint_parens(cond, comments)); let mut docs = vec![self.constraint_set_as_body( concat(head), then, &comments.before_body, true, )]; let Some(els) = els else { return concat(docs) }; // A braced `then` cuddles the `else` onto the `}` line, the // way a statement `if` cuddles it onto `end`. docs.push(if then.braced { text(" ") } else { Doc::HardLine }); for c in else_comments { docs.push(self.comment(c)); docs.push(Doc::HardLine); } // `else if` chains on one line, the way a statement `if` does: // an unbraced else holding exactly one `if` is the chain, and // indenting it once per link would stair-step the whole thing // off the right of the page. match Self::chained_if(els) { Some(item) => { let mut chain = vec![text("else")]; self.inline_comments_spaced(after_else, &mut chain); chain.push(self.with_meta(&item.meta, self.constraint_item(item))); docs.push(concat(chain)); } None => { docs.push(self.constraint_set_as_body(text("else"), els, after_else, true)) } } concat(docs) } ConstraintItemKind::Foreach { array, vars, var_comments, comments, set } => { let mut head = vec![text("foreach")]; self.inline_comments_spaced(&comments.after_kw, &mut head); head.push(text("(")); self.inline_comments(&comments.after_open, &mut head); if !comments.after_open.is_empty() { head.push(text(" ")); } head.push(self.expr(array)); head.push(self.foreach_vars(vars, var_comments)); if self.inline_comments(&comments.before_close, &mut head) { head.push(Doc::HardLine); } else if !comments.before_close.is_empty() { head.push(text(" ")); } head.push(text(")")); self.constraint_set_as_body(concat(head), set, &comments.before_body, true) } ConstraintItemKind::SolveBefore { solve, before_comments, before } => { let mut docs = vec![text("solve "), self.plain_expr_list(solve)]; self.inline_comments_spaced(before_comments, &mut docs); docs.push(text("before ")); docs.push(self.plain_expr_list(before)); concat(docs) } ConstraintItemKind::Unique { items, comments } => { let mut docs = vec![text("unique")]; self.inline_comments_spaced(comments, &mut docs); docs.push(self.expr_list("{", items, "}")); concat(docs) } ConstraintItemKind::DisableSoft { expr, comments } => { let mut docs = vec![text("disable")]; self.inline_comments_spaced(&comments.before, &mut docs); docs.push(text("soft")); self.inline_comments_spaced(&comments.after, &mut docs); docs.push(self.expr(expr)); concat(docs) } ConstraintItemKind::Directive(raw) => self.raw_text(raw), ConstraintItemKind::Empty => text(";"), } } /// The `( cond )` of a constraint `if`, with the comments written just /// inside either parenthesis printed back where they were written. fn constraint_parens(&self, cond: &Expr, comments: &HeaderComments) -> Doc { self.guard_parens(cond, &comments.after_open, &comments.before_close) } /// The `if` an `else` chains straight onto: the single item of an /// unbraced `else` set, when that item is itself an `if`. fn chained_if(set: &ConstraintSet) -> Option<&ConstraintItem> { if set.braced || set.items.len() != 1 { return None; } let item = set.items.first()?; matches!(item.kind, ConstraintItemKind::If { .. }).then_some(item) } /// A header followed by a constraint set: a braced set cuddles onto the /// header line, an unbraced one goes on the same line if it fits and on /// an indented next line if it does not — exactly what /// [`Fmt::stmt_as_body`] does for statements. fn constraint_set_as_body( &self, head: Doc, set: &ConstraintSet, before: &[Comment], space: bool, ) -> Doc { if set.braced { let mut docs = vec![head]; if self.inline_comments(before, &mut docs) { docs.push(Doc::HardLine); } else if space || !before.is_empty() { docs.push(text(" ")); } docs.push(self.constraint_block(set, false)); return concat(docs); } let body = match set.items.first() { Some(item) => self.with_meta(&item.meta, self.constraint_item(item)), None => text(""), }; group(vec![head, indent(vec![Doc::Line, body])]) } /// `expr dist { 0 := 5, [1:20] :/ 20 }` — the weight list laid out like /// every other braced list: one per line when it does not fit. `:=` and /// `:/` are printed back exactly as written; they mean different things. pub(super) fn dist(&self, expr: &Expr, comments: &BinaryComments, weights: &[DistItem]) -> Doc { let items: Vec = weights .iter() .map(|w| { let mut docs = vec![self.expr(&w.value)]; if let (Some(op), Some(weight)) = (&w.op, &w.weight) { self.inline_comments_spaced(&w.op_comments.before, &mut docs); docs.push(text(op.clone())); self.inline_comments_spaced(&w.op_comments.after, &mut docs); docs.push(self.expr(weight)); } ListItem::from_meta(&w.meta, concat(docs)) }) .collect(); let mut docs = vec![self.expr(expr)]; self.inline_comments_spaced(&comments.before, &mut docs); docs.push(text("dist")); self.inline_comments_spaced(&comments.after, &mut docs); docs.push(self.delimited("{", items, "}", false)); concat(docs) } }