//! Expressions: the dispatch from `ExprKind` to its layout, the binary //! chain that breaks `a + b + c` as one unit, the ternary with comments //! inside it, the compact spelling used inside `[ ... ]`, and the small //! postfix forms (`base.name`, `base::name`, `lhs inside {…}`, `with`). //! //! `expr` is a dispatch table over `ExprKind` and stays whole; the //! helpers after it are the arms that grew a shape of their own. use crate::doc::*; use vlog_parser::ast::*; use vlog_parser::token::Comment; use super::comment::is_line_comment; use super::list::ListItem; use super::{name_doc, named, Fmt}; /// 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], } impl<'a> Fmt<'a> { fn binary_prec(op: &str) -> u8 { match op { "||" => 1, "&&" => 2, "|" => 3, "^" | "^~" | "~^" => 4, "&" => 5, "==" | "!=" | "===" | "!==" | "==?" | "!=?" => 6, "<" | "<=" | ">" | ">=" => 7, "<<" | ">>" | "<<<" | ">>>" => 8, "+" | "-" => 9, "*" | "/" | "%" => 10, "**" => 11, // `->` and `<->` are the lowest-precedence binary operators // (IEEE 1800 §11.3.2). This table is only ever compared for // equality — it decides which neighbours flatten into one // chain — and no other operator reaches the fallback. "->" | "<->" => 0, _ => 0, } } /// True when a call's callee is a **macro name the source separated from /// its `(`** — `` `WIDTH (a + b) ``, the expression-position spelling of /// the `` `uvm_field_int (x, y) `` an item already keeps /// (`Parser::at_spaced_macro_call`). /// /// The gap is data, not layout: `` `A (b) `` and `` `A(b) `` are one token /// each, of *different text*, so closing it is a token rewrite the safety /// net refuses — pinned in both directions by /// `verification::{tightening,loosening}_a_*_macro_call_is_rejected`. And /// lucisv cannot know which spelling was meant, because that depends on /// whether the macro was defined with formals (IEEE 1800 §22.5.1), which /// lives in a file this formatter does not read. /// /// The question is asked of `src` rather than of the AST for the reason /// [`Fmt::glued_null_item`] gives: it is a fact about the gap between two /// tokens, and this is the one place that gap is laid out. It is a fixed /// point by construction — the printed gap is one space, which reads back /// as a gap on the next pass. fn spaced_macro_callee(&self, callee: &Expr) -> bool { let ExprKind::Ident(name) = &callee.kind else { return false }; name.starts_with('`') && self .src .get(callee.span.end as usize..) .and_then(|rest| rest.chars().next()) .is_some_and(char::is_whitespace) } /// One arm per `ExprKind`. A dispatch table over the enum, so it stays /// whole past the 150-line mark: the shapes with a layout of their own /// (a binary chain, a ternary with comments, `base.name`) are the /// functions after it. pub(super) fn expr(&self, e: &Expr) -> Doc { match &e.kind { ExprKind::Ident(s) => name_doc(s), 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, comments, expr } => { let mut docs = vec![text(op.clone())]; self.slot_comments(comments, &mut docs); docs.push(self.expr(expr)); concat(docs) } 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, comments } => { let spaced = self.spaced_macro_callee(callee); if comments.is_empty() { let mut docs = vec![self.expr(callee)]; if spaced { docs.push(text(" ")); } docs.push(self.expr_list("(", args, ")")); return concat(docs); } // A comment written around the brackets prints back between // the same two tokens it was written between: after the // callee, and inside the empty `()` that had nowhere else to // put it. let mut docs = vec![self.expr(callee)]; if !comments.before_open.is_empty() { self.inline_comments_spaced(&comments.before_open, &mut docs); } else if spaced { docs.push(text(" ")); } let items: Vec = args.iter().map(|i| ListItem::from_meta(&i.meta, self.expr(&i.expr))).collect(); docs.push(self.delimited_dangling("(", items, &comments.dangling, ")", false)); concat(docs) } // `new src` — one space, never a break: the source handle is a // postfix expression that breaks internally if it must. ExprKind::New(src) => concat(vec![text("new "), self.expr(src)]), ExprKind::Index { base, index, comments } => { let mut docs = vec![self.expr(base)]; self.slot_comments(&comments.before_open, &mut docs); docs.push(self.bracket_slots(comments, self.expr_compact(index), None)); concat(docs) } ExprKind::Range { base, op, msb, lsb, comments } => { let mut docs = vec![self.expr(base)]; self.slot_comments(&comments.before_open, &mut docs); docs.push(self.bracket_slots( comments, self.expr_compact(msb), Some((op, self.expr_compact(lsb))), )); concat(docs) } ExprKind::Member { base, name, comments } => { self.chain_segment(base, ".", name, comments) } ExprKind::Scope { base, name, comments } => { self.chain_segment(base, "::", name, comments) } // Written tight, like the `::` it almost always precedes. ExprKind::Parameterized { base, params } => { concat(vec![self.expr(base), self.raw_inline(params)]) } ExprKind::Concat(items) => self.expr_list("{", items, "}"), ExprKind::Repl { count, inner } => concat(vec![ text("{"), self.expr(count), self.expr_list("{", inner, "}"), text("}"), ]), // `{<<8{v}}` — written tight, like a replication. ExprKind::Stream { dir, slice, inner } => { let mut docs = vec![text("{"), text(dir.clone())]; if let Some(s) = slice { docs.push(self.expr(s)); } docs.push(self.expr_list("{", inner, "}")); docs.push(text("}")); concat(docs) } ExprKind::Paren { inner, before, after } => { if before.is_empty() && after.is_empty() { return self.parens(inner); } let before: Vec<&Comment> = before.iter().collect(); let after: Vec<&Comment> = after.iter().collect(); self.paren_comments(inner, &before, &after) } // `ty'{...}` prints no brackets of its own: the assignment // pattern already carries the `'{` and the `}`. ExprKind::Cast { ty, comments, expr, pattern: true } => { let mut docs = vec![self.expr(ty)]; self.slot_comments(&comments.before_tick, &mut docs); self.slot_comments(&comments.after_tick, &mut docs); docs.push(self.expr(expr)); concat(docs) } ExprKind::Cast { ty, comments, expr, .. } => { if comments.is_empty() { return concat(vec![self.expr(ty), text("'("), self.expr(expr), text(")")]); } let mut docs = vec![self.expr(ty)]; self.slot_comments(&comments.before_tick, &mut docs); docs.push(text("'")); self.slot_comments(&comments.after_tick, &mut docs); docs.push(text("(")); self.slot_comments(&comments.after_open, &mut docs); docs.push(self.expr(expr)); self.slot_comments(&comments.before_close, &mut docs); docs.push(text(")")); concat(docs) } ExprKind::AssignPattern(items) => { let items: Vec = 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) } // `'{N{0}}` — written tight, like the `{N{0}}` it replicates. ExprKind::AssignPatternRepl { count, inner } => concat(vec![ text("'{"), self.expr(count), self.expr_list("{", inner, "}"), text("}"), ]), ExprKind::Postfix { expr, op, comments } => { let mut docs = vec![self.expr(expr)]; self.slot_comments(comments, &mut docs); docs.push(text(op.clone())); concat(docs) } ExprKind::With { base, arg, comments } => { concat(vec![self.with_head(base, comments), self.expr(arg)]) } ExprKind::WithConstraint { base, block, comments } => { let body = match &**block { ConstraintBody::Items(set) => self.with_constraint_block(set), ConstraintBody::Verbatim(raw) => self.with_block(raw), }; concat(vec![self.with_head(base, comments), body]) } ExprKind::Dist { expr, comments, weights } => self.dist(expr, comments, weights), ExprKind::Inside { lhs, ranges, comments } => { self.inside_head(lhs, comments, self.expr_list("{", ranges, "}")) } ExprKind::InsideMacro { lhs, set, comments } => { self.inside_head(lhs, comments, text(set.clone())) } // A named call argument, printed the way a named connection is: // `.name(value)`, tight, with a break opportunity inside. ExprKind::NamedArg { name, value, comments, .. } => match &value.kind { ExprKind::Empty(inner) => { let comments_inner = inner; let mut docs = vec![text(".")]; self.slot_comments(&comments.after_dot, &mut docs); docs.push(text(named(name))); self.slot_comments(&comments.before_open, &mut docs); docs.push(text("(")); self.slot_comments(&comments.after_open, &mut docs); let comments = comments_inner; let mut ends_line = false; for cm in comments { if ends_line { docs.push(Doc::HardLine); } docs.push(self.comment(cm)); ends_line = is_line_comment(&cm.text); } if ends_line { docs.push(Doc::HardLine); } docs.push(text(")")); concat(docs) } _ => { let mut inner = vec![Doc::SoftLine, self.expr(value)]; let ends_line = self.inline_comments(&comments.close, &mut inner); let close = if ends_line { Doc::HardLine } else { Doc::SoftLine }; let mut docs = vec![text(".")]; self.slot_comments(&comments.after_dot, &mut docs); docs.push(text(named(name))); self.slot_comments(&comments.before_open, &mut docs); docs.push(text("(")); self.slot_comments(&comments.after_open, &mut docs); docs.push(group(vec![indent(inner), close])); docs.push(text(")")); concat(docs) } }, ExprKind::ValueRange { lo, hi, comments } => { self.bracket_slots(comments, self.expr(lo), Some((":", self.expr(hi)))) } ExprKind::Type(ty) => self.data_type(ty).unwrap_or_else(|| text("")), // Byte for byte, like every other verbatim leaf, and `Inline` // rather than re-indented for the reason `raw_inline` gives: the // region never begins its own line, so a dedent-by-column would // drift instead of reaching a fixed point. ExprKind::Verbatim(raw) => self.raw_inline(raw), // Unreachable from `format_source`, as `ItemKind::Error` is: only // a tolerant parse builds this leaf, and the formatter parses // strictly. Printed verbatim so nothing is lost if that ever // changes — see `ListItem::from_raw`. ExprKind::Error(raw) => self.raw_inline(raw), ExprKind::MinTypMax { min, typ, max, comments } => { let mut docs = vec![self.expr(min)]; self.slot_comments(&comments.before_typ, &mut docs); docs.push(text(":")); self.slot_comments(&comments.after_typ, &mut docs); docs.push(self.expr(typ)); self.slot_comments(&comments.before_max, &mut docs); docs.push(text(":")); self.slot_comments(&comments.after_max, &mut docs); docs.push(self.expr(max)); concat(docs) } } } /// 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> = Vec::new(); fn walk<'e>( e: &'e Expr, prec: u8, operands: &mut Vec<&'e Expr>, ops: &mut Vec>, ) { 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 `? :` 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) } /// Compact rendering used inside `[...]` brackets: arithmetic and shift /// operators lose their surrounding spaces (`[WIDTH-1:0]`), and no line /// breaks are introduced. pub(super) 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) } // The compact spelling has nowhere to put a comment written // inside the `? :` or just inside the parentheses, so a shape // that carries one falls back to the ordinary layout, which does. ExprKind::Ternary { cond, then, els, comments } if comments.is_empty() => concat(vec![ self.expr_compact(cond), text(" ? "), self.expr_compact(then), text(" : "), self.expr_compact(els), ]), ExprKind::Paren { inner, before, after } if before.is_empty() && after.is_empty() => { concat(vec![text("("), self.expr_compact(inner), text(")")]) } ExprKind::Unary { op, comments, expr } if comments.is_empty() => { concat(vec![text(op.clone()), self.expr_compact(expr)]) } _ => self.expr(e), } } /// `base.name` / `base::name`, with the comments the source wrote on /// either side of the joining token. fn chain_segment( &self, base: &Expr, joiner: &str, name: &str, comments: &SegmentComments, ) -> Doc { if comments.is_empty() { return concat(vec![self.expr(base), text(format!("{joiner}{}", named(name)))]); } let mut docs = vec![self.expr(base)]; self.slot_comments(&comments.before_open, &mut docs); docs.push(text(joiner.to_string())); self.slot_comments(&comments.after_open, &mut docs); docs.push(text(named(name))); concat(docs) } /// `lhs inside set`, with the comments written on either side of the word /// kept on their own side of it, as every binary operator's are. fn inside_head(&self, lhs: &Expr, comments: &BinaryComments, set: Doc) -> Doc { if comments.before.is_empty() && comments.after.is_empty() { return concat(vec![self.expr(lhs), text(" inside "), set]); } let mut docs = vec![self.expr(lhs)]; self.inline_comments_spaced(&comments.before, &mut docs); docs.push(text("inside")); self.inline_comments_spaced(&comments.after, &mut docs); docs.push(set); concat(docs) } /// ` with ` — the head both postfix `with` forms share, with the /// comments written on either side of the keyword printed back where they /// were written. Anywhere else they would move across `with` and the /// safety net would reject the output. fn with_head(&self, base: &Expr, comments: &WithComments) -> Doc { let mut docs = vec![self.expr(base)]; self.inline_comments_spaced(&comments.before_kw, &mut docs); docs.push(text("with")); self.inline_comments_spaced(&comments.after_kw, &mut docs); concat(docs) } }