//! Formatting rules: AST → Doc. //! //! Style follows Verible's defaults: 2-space indent, 100-column lines, //! one-element-per-line port/connection lists when a construct does not fit //! on a single line, cuddled `begin`/`end`. use crate::align::{self, Align, ColSpec, Row}; use crate::doc::*; use crate::fence::{self, Region}; use crate::printer::{contains_hard_line, Printer}; use crate::range::{self, Split}; use crate::verify::{ line_starts_inside_string, verify_convergence, verify_equivalence, VerificationError, }; use vlog_parser::ast::*; use vlog_parser::span::TextRange; use vlog_parser::token::Comment; #[derive(Debug, Clone)] pub struct Config { pub max_width: usize, pub indent_width: usize, } impl Default for Config { fn default() -> Self { Config { max_width: 100, indent_width: 2 } } } /// An ANSI port's one alignment column: the name, one space off the type. const ANSI_PORT_COLS: &[ColSpec] = &[ColSpec { flush: 1, min: 1 }]; /// A named connection's one alignment column: the `(` of the value. It is /// written tight when flush (`.clk(clk)`) and one space off the name when /// aligned (`.clk (clk)`), which is Verible's spelling of both. const CONNECTION_COLS: &[ColSpec] = &[ColSpec { flush: 0, min: 1 }]; /// A `parameter`/`localparam` declaration's two alignment columns: the name, /// and the `=` of its value. const PARAM_DECL_COLS: &[ColSpec] = &[ColSpec { flush: 1, min: 1 }, ColSpec { flush: 1, min: 1 }]; /// Everything that can stop the formatter from producing output. #[derive(Debug)] pub enum FormatError { /// The input could not be lexed or parsed. Source(vlog_parser::Error), /// A safety check failed; the formatted text was discarded. Verification(VerificationError), } impl std::fmt::Display for FormatError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { FormatError::Source(e) => write!(f, "{e}"), FormatError::Verification(e) => write!(f, "{e}"), } } } impl std::error::Error for FormatError {} impl From for FormatError { fn from(e: vlog_parser::Error) -> Self { FormatError::Source(e) } } impl From 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. /// /// Parses `source` (twice, for verification), so call this only on a thread /// with at least `vlog_parser::PARSE_STACK_SIZE` of stack — a smaller one /// lets sufficiently nested input abort the process instead of returning /// `Err` (see `docs/features/recursion-limit/README.md`). pub fn format_source(source: &str, config: &Config) -> Result { let output = format_once(source, config).map_err(FormatError::Source)?; verify_equivalence(source, &output)?; let again = format_once(&output, config).map_err(VerificationError::Reparse)?; verify_convergence(&output, &again)?; Ok(output) } /// Format only the constructs intersecting `lines`, emitting every other byte /// exactly as it was written. /// /// The safety net is the same one and it still runs over the *whole* output: /// the spliced bytes are source text, the laid-out islands are ordinary /// formatter output, and both checks are global. Convergence is checked by /// replaying the same per-item decisions against the output — see /// `docs/features/range-formatting/README.md`. /// /// Same stack requirement as [`format_source`]: needs a thread with at least /// `vlog_parser::PARSE_STACK_SIZE` of stack. pub fn format_range( source: &str, config: &Config, lines: &range::LineRanges, ) -> Result { let file = vlog_parser::parse_source(source).map_err(FormatError::Source)?; let selection = range::select(source, &file, lines); let output = format_selected(source, config, &selection).map_err(FormatError::Source)?; verify_equivalence(source, &output)?; let again = format_selected(&output, config, &selection).map_err(VerificationError::Reparse)?; verify_convergence(&output, &again)?; Ok(output) } /// A single unverified formatting pass: parse, lay out, print. fn format_once(source: &str, config: &Config) -> Result { let file = vlog_parser::parse_source(source)?; let regions = fence::collect(source, &file); Ok(render(&Fmt { cfg: config, src: source, regions, splits: Vec::new() }, &file, config)) } /// The same pass, restricted to the units `selection` picked out. fn format_selected( source: &str, config: &Config, selection: &range::Selection, ) -> Result { let file = vlog_parser::parse_source(source)?; let plan = range::plan(source, &file, selection); let fmt = Fmt { cfg: config, src: source, regions: plan.regions, splits: plan.splits }; Ok(render(&fmt, &file, config)) } /// Lay the file out and print it, ending in exactly one newline. fn render(fmt: &Fmt, file: &SourceFile, config: &Config) -> String { let doc = fmt.file(file); let printer = Printer { max_width: config.max_width, indent_width: config.indent_width }; let mut out = printer.print(&doc); // Normalize trailing whitespace: exactly one final newline. while out.ends_with('\n') || out.ends_with(' ') { out.pop(); } out.push('\n'); out } struct Fmt<'a> { cfg: &'a Config, /// The text the AST was parsed from — what `// verilog_format: off` /// regions and `--lines` runs are spliced out of. src: &'a str, /// The byte ranges of `src` emitted exactly as written, sorted and /// non-overlapping: fenced regions, plus whatever a range run left alone. regions: Vec, /// Scope-bearing items a range run descends into. Empty for a whole-file /// run. splits: Vec, } /// 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, doc: Doc, /// Comments written between the element and the separator that follows. before_sep: Vec, trailing: Option, /// Whether a `,` follows this entry. `None` means "decide from the /// position" — the last entry of the list gets none — which is right for /// every list that cannot hold a compiler directive. The three that can /// (a header's parameter ports and ports, an enum's members) set it from /// the source, because a directive between two elements can move the /// comma to the other side of it. comma: Option, /// True for a `` `ifdef``-style entry. A directive runs to end of line, /// so whatever follows it — a comma included — starts a new line. directive: bool, } impl ListItem { fn from_meta(meta: &Meta, doc: Doc) -> Self { ListItem { leading: meta.leading.clone(), doc, before_sep: meta.before_sep.clone(), trailing: meta.trailing.clone(), comma: None, directive: false, } } /// Record the `,` the source wrote after this element, instead of letting /// the list derive one from the element's position. fn with_comma(mut self, comma: bool) -> Self { self.comma = Some(comma); self } } impl<'a> Fmt<'a> { // ------------------------------------------------------------------ // Shared helpers // ------------------------------------------------------------------ /// Verbatim text — a directive, an attribute, or a macro invocation — /// ready to be re-indented. /// /// A token that carries a string literal across a line break is emitted /// completely untouched instead: the leading whitespace of such a /// continuation line is part of the string's *value*, and re-indenting it /// would rewrite the string. Emitting the text as a `Doc::Inline` means /// the printer copies the newlines through without adding indent — so /// nothing changes and the result is a fixed point by construction — /// while its column tracking resumes from the text's own last line /// (`Doc::Text` must not contain newlines). fn raw_text(&self, raw: &RawText) -> Doc { if crosses_line_inside_string(&raw.text) { return Doc::Inline(raw.text.clone()); } self.raw_lines(&raw.text, raw.col) } /// Verbatim text that does *not* start the line it is printed on: the /// `#( ... )` of a parameterized type or class reference. /// /// It is emitted exactly as written, continuation lines included. /// `raw_lines`'s dedent-by-column only reaches a fixed point when the text /// begins its own line — the dedent has to cancel the indent the printer /// adds back — and this text never does, so re-indenting it would drift. /// Emitting it unchanged is idempotent by construction. `Doc::Inline` /// rather than `Doc::Text` so a multi-line `#( ... )` keeps the printer's /// column honest (`Doc::Text` must not contain newlines). fn raw_inline(&self, raw: &RawText) -> Doc { Doc::Inline(raw.text.clone()) } /// The `{ ... }` of a `randomize() with { ... }`: verbatim source spliced /// into the middle of a line. /// /// Like [`Fmt::raw_inline`] it is reproduced byte for byte — the block is /// a constraint body lucisv does not model, so there is no layout to apply /// and re-indenting it would only drift on every pass — but the printer /// is told about the line breaks inside it, so the expression around it /// is still measured against the line width correctly. fn with_block(&self, raw: &RawText) -> Doc { Doc::Inline(raw.text.clone()) } /// ` 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) } /// 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) -> Doc { match label { Some(l) => text(format!("{kw} : {l}")), None => text(kw), } } // ------------------------------------------------------------------ // Format-off fences // ------------------------------------------------------------------ /// What to do with one comment, given the fenced regions of the source. fn slot(&self, c: &Comment) -> Slot<'_> { match fence::region_at(&self.regions, c.span.start as usize) { None => Slot::Normal, Some(r) if r.fence == c.span.start as usize => Slot::Opens(r), Some(_) => Slot::Covered, } } /// True if this node's code is inside a verbatim region, i.e. its bytes /// are already being emitted as written and it must not be laid out. fn is_verbatim(&self, span: TextRange) -> bool { fence::region_at(&self.regions, span.start as usize).is_some() } /// The verbatim region this byte offset *opens*, if it opens one. /// /// A region's opener is the first byte of the first unit it covers: a /// fence comment, the first leading comment of a run's first item, or — /// when that item has no leading comments — the item's own code. fn opens_at(&self, at: usize) -> Option<&Region> { fence::region_at(&self.regions, at).filter(|r| r.fence == at) } /// The split recorded for the item starting at this byte offset. fn split_at(&self, at: usize) -> Option<&Split> { self.splits.iter().find(|s| s.item == at) } /// A verbatim slice of the source, by byte range. fn slice(&self, (start, end): (usize, usize)) -> Doc { Doc::Verbatim(self.src.get(start..end).unwrap_or_default().to_string()) } /// A fenced region's source bytes. /// /// A slice that is not on a character boundary cannot happen — every /// offset comes from a span or from a scan over ASCII delimiters — but if /// it ever did, an empty region loses tokens and `verify_equivalence` /// rejects the output, which is the failsafe. Better that than a panic. fn verbatim(&self, r: &Region) -> Doc { Doc::Verbatim(self.src.get(r.start..r.end).unwrap_or_default().to_string()) } /// Leading comments (each on its own line) preceding a node, with any /// fenced region they open spliced in as source bytes. /// /// The break between two comments is emitted *before* the second one, not /// after the first: a `HardLine` followed by a `BlankLine` is three /// newlines, so writing both turned one blank line between two comments /// into two. The list still ends with the `HardLine` that puts the node /// itself on a fresh line. fn leading_comments(&self, meta: &Meta) -> Vec { let mut docs = Vec::new(); for c in &meta.leading { self.push_comment(&mut docs, c); } if !docs.is_empty() { docs.push(Doc::HardLine); } docs } /// Append one leading comment — or, when it opens a fenced region, that /// region's source bytes — with the break that separates it from whatever /// precedes it. Covered comments are already inside emitted bytes. fn push_comment(&self, docs: &mut Vec, c: &Comment) { let doc = match self.slot(c) { Slot::Covered => return, Slot::Opens(r) => self.verbatim(r), Slot::Normal => self.comment(c), }; Self::push_leading(docs, doc, c.blank_before); } /// Leading comments and `(* ... *)` attributes preceding a node, each on /// its own line, in the order the source wrote them. /// /// The two are stored in separate lists but interleave in the source /// (`(* keep *)` ⏎ `// why` ⏎ `logic x;`), so they are merged by span: /// printing every comment and then every attribute moves a comment across /// an attribute in the token stream, which the safety net rejects. fn leading(&self, meta: &Meta) -> Vec { self.leading_from(meta, 0) } /// The same, minus the first `skip` leading comments — the ones a /// statement header already printed inside its own parentheses. See /// [`Fmt::header_parens`]. fn leading_from(&self, meta: &Meta, skip: usize) -> Vec { let mut docs = Vec::new(); let mut attrs = meta.attrs.iter().peekable(); for c in meta.leading.iter().skip(skip) { while let Some(attr) = attrs.next_if(|a| a.span.start < c.span.start) { Self::push_leading(&mut docs, self.raw_text(attr), false); } self.push_comment(&mut docs, c); } for attr in attrs { Self::push_leading(&mut docs, self.raw_text(attr), false); } if !docs.is_empty() { docs.push(Doc::HardLine); } docs } /// Append one leading comment or attribute, with the break that separates /// it from the previous one. The break goes *before* the second entry /// rather than after the first: a `HardLine` followed by a `BlankLine` is /// three newlines, so writing both turned one blank line into two. fn push_leading(docs: &mut Vec, doc: Doc, blank_before: bool) { if !docs.is_empty() { docs.push(if blank_before { Doc::BlankLine } else { Doc::HardLine }); } docs.push(doc); } /// Comments written between a construct's head and the bracket that opens /// one of its lists (`module m` ⏎ `// why` ⏎ `#(`, `sub u` ⏎ `// why` ⏎ /// `(...)`). They print on the head's side of the bracket, which is where /// the source put them. /// /// `on_fresh_line` says whether the caller has already broken the line; /// the return value says the same for whatever it emits next, since a line /// comment runs to end of line and the bracket cannot follow it. fn bracket_comments( &self, comments: &[Comment], docs: &mut Vec, on_fresh_line: bool, ) -> bool { let mut fresh = on_fresh_line; for c in comments { if !fresh { docs.push(text(" ")); } docs.push(self.comment(c)); fresh = is_line_comment(&c.text); if fresh { docs.push(Doc::HardLine); } } fresh } fn trailing(&self, meta: &Meta) -> Vec { 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) -> 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) { 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, 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, dangling: &[Comment], close: &str, force_break: bool, ) -> Doc { if items.is_empty() && dangling.is_empty() { return text(format!("{open}{close}")); } let mut inner: Vec = Vec::new(); if !items.is_empty() { inner.push(if force_break { Doc::HardLine } else { Doc::SoftLine }); } let last = items.len().saturating_sub(1); let mut close_needs_hardline = force_break; for (i, item) in items.into_iter().enumerate() { let meta = Meta { leading: item.leading, ..Meta::default() }; inner.extend(self.leading(&meta)); inner.push(item.doc); // Comments written before the separator print on this element's // side of it, which is where the source put them. let has_before_sep = !item.before_sep.is_empty(); // A directive swallows the rest of its line, so its comma — and // any comment written before that comma — must start a new one. // (A comment itself may share the line: the lexer stops the // directive's capture before a `//` or `/*`.) let ends_line = self.inline_comments(&item.before_sep, &mut inner) || item.directive; if item.comma.unwrap_or(i < last) { if ends_line { inner.push(Doc::HardLine); } inner.push(text(",")); } else if has_before_sep { close_needs_hardline = true; } if let Some(tr) = item.trailing { inner.push(text(" ")); inner.push(self.comment(&tr)); if i < last { inner.push(Doc::HardLine); } else { close_needs_hardline = true; } } else if i < last { inner.push(Doc::Line); } } for c in dangling { inner.push(Doc::HardLine); inner.push(self.comment(c)); close_needs_hardline = true; } // Peek at blank_before flags is handled by leading comments already; // blank lines inside bracketed lists are dropped deliberately. let mut docs = vec![text(open), indent(inner)]; docs.push(if close_needs_hardline { Doc::HardLine } else { Doc::SoftLine }); docs.push(text(close)); group(docs) } /// Put a list's elements and the `` `ifdef``-style directives written /// between them back into source order. /// /// A directive is an entry like any other except that it never takes a /// comma of its own unless the source wrote one after it, and that it /// forces the list open: `delimited_dangling`'s `force_break` must be set /// whenever the result holds one, or the printer could put the next entry /// on the directive's line, where the lexer would swallow it. fn list_entries(&self, elements: Vec, directives: &[ListDirective]) -> Vec { if directives.is_empty() { return elements; } let mut out = Vec::with_capacity(elements.len() + directives.len()); let mut pending = directives.iter().peekable(); for (i, element) in elements.into_iter().enumerate() { while let Some(d) = pending.next_if(|d| d.before <= i) { out.push(self.directive_entry(d)); } out.push(element); } for d in pending { out.push(self.directive_entry(d)); } out } /// One directive standing between list elements, verbatim. /// /// Its trailing comment goes in `before_sep` rather than `trailing` /// because that is where the source put it — between the directive and /// the comma that may follow it. `Parser::take_before_sep` already moves a /// trailing comment into `before_sep` in source order, so at most one of /// the two is ever populated and appending keeps the source's order. fn directive_entry(&self, d: &ListDirective) -> ListItem { let mut before_sep = d.meta.before_sep.clone(); before_sep.extend(d.meta.trailing.clone()); ListItem { leading: d.meta.leading.clone(), doc: self.raw_text(&d.raw), before_sep, trailing: None, comma: Some(d.comma), directive: true, } } // ------------------------------------------------------------------ // Alignment inference // ------------------------------------------------------------------ /// Plan the alignment of a sequence of candidate rows. /// /// `rows[i]` is `None` for an element that cannot be aligned, and /// `breaks[i]` is true for one that starts a new group. Both split the /// sequence into maximal runs, and every element of a run that is planned /// aligned gets the same [`Align`] — the padding is a property of the /// group, never of one line. fn align_groups( &self, rows: &[Option], breaks: &[bool], specs: &[ColSpec], depth: usize, ) -> Vec> { // What is left of the line once the rows' own indentation is paid // for. `depth` comes from the AST's nesting, so it is the same on // every pass — which is what keeps the verdict stable. let budget = self.cfg.max_width.saturating_sub(depth * self.cfg.indent_width); let mut out = vec![None; rows.len()]; let mut i = 0; while i < rows.len() { if rows[i].is_none() { i += 1; continue; } let mut j = i + 1; while j < rows.len() && rows[j].is_some() && !breaks[j] { j += 1; } let run: Vec<&Row> = rows[i..j].iter().flatten().collect(); if let Some(plan) = align::plan(self.src, &run, specs, budget) { for slot in &mut out[i..j] { *slot = Some(plan.clone()); } } i = j; } out } /// Measure one candidate row. `None` — meaning "cannot be aligned" — when /// the cells did not split at every column, or when one of them holds a /// comment and so has no flat width. fn row_of(cells: &[Doc], anchors: Vec, tail: usize) -> Option { if cells.len() != anchors.len() + 1 { return None; } let widths: Option> = cells.iter().map(align::flat_width).collect(); Some(Row { widths: widths?, anchors, tail }) } /// Which elements of a bracketed list start a new alignment group: those /// with a comment or an attribute of their own — both print on their own /// line — and those a compiler directive was written in front of. /// /// A blank line is deliberately *not* a boundary here: `delimited` drops /// blank lines between list elements, so a boundary drawn at one would /// vanish from the output and the next pass would group differently. fn list_breaks<'m>( metas: impl Iterator, directives: &[ListDirective], ) -> Vec { let mut breaks: Vec = metas.map(|m| !m.leading.is_empty() || !m.attrs.is_empty()).collect(); for d in directives { if let Some(b) = breaks.get_mut(d.before) { *b = true; } } breaks } /// The alignment plan for a module header's ANSI port list. fn ansi_port_aligns( &self, ports: &[AnsiPort], directives: &[ListDirective], depth: usize, ) -> Vec> { let rows: Vec> = ports .iter() .map(|p| { Self::row_of( &self.ansi_port_cells(p), vec![p.name_span.start], usize::from(p.comma), ) }) .collect(); let breaks = Self::list_breaks(ports.iter().map(|p| &p.meta), directives); self.align_groups(&rows, &breaks, ANSI_PORT_COLS, depth) } /// The alignment plan for an instance's named connection list. fn connection_aligns( &self, conns: &[Connection], directives: &[ListDirective], depth: usize, ) -> Vec> { let rows: Vec> = conns .iter() .map(|c| { let paren = self.open_paren_offset(c.name_span.end)?; Self::row_of(&self.connection_cells(c), vec![paren], usize::from(c.comma)) }) .collect(); let breaks = Self::list_breaks(conns.iter().map(|c| &c.meta), directives); self.align_groups(&rows, &breaks, CONNECTION_COLS, depth) } /// The alignment plan for the `parameter`/`localparam` declarations among /// a run of module (or package, or class) items. fn param_decl_aligns(&self, items: &[Item], depth: usize) -> Vec> { let rows: Vec> = items.iter().map(|i| self.param_decl_row(i)).collect(); if rows.iter().all(Option::is_none) { return vec![None; items.len()]; } // Unlike a bracketed list, an item sequence prints the blank lines the // source wrote, so a blank line is a boundary the next pass sees too. let breaks: Vec = items .iter() .map(|i| i.meta.blank_before || !i.meta.leading.is_empty() || !i.meta.attrs.is_empty()) .collect(); self.align_groups(&rows, &breaks, PARAM_DECL_COLS, depth) } /// Measure a `parameter`/`localparam` item as an alignment row. /// /// Only the plain shape joins a group: one declarator, with a value, no /// comments of its own, not inside a fenced region. Anything else formats /// the way it always has and splits the group in two. fn param_decl_row(&self, item: &Item) -> Option { let ItemKind::ParamDecl(d) = &item.kind else { return None }; if !item.meta.attrs.is_empty() || self.is_verbatim(item.span) { return None; } let [decl] = &d.declarators[..] else { return None }; if !decl.meta.leading.is_empty() || !decl.meta.before_sep.is_empty() || decl.meta.trailing.is_some() { return None; } let init = decl.init.as_ref()?; let eq = self.eq_offset(init.span.start, decl.name_span.end)?; // The tail is the `;` the item ends with. Self::row_of(&self.param_decl_cells(d, decl, init), vec![decl.name_span.start, eq], 1) } /// Byte offset of the `=` between a declarator's name and its value, or /// `None` when anything but whitespace stands between the two. fn eq_offset(&self, value_start: u32, after_name: u32) -> Option { let bytes = self.src.as_bytes(); let mut pos = value_start as usize; while pos > 0 && matches!(bytes[pos - 1], b' ' | b'\t' | b'\r' | b'\n') { pos -= 1; } (pos > after_name as usize && bytes.get(pos - 1) == Some(&b'=')).then_some(pos as u32 - 1) } /// Byte offset of the `(` opening a named connection's value. fn open_paren_offset(&self, after_name: u32) -> Option { let bytes = self.src.as_bytes(); let mut pos = after_name as usize; while matches!(bytes.get(pos), Some(b' ' | b'\t' | b'\r' | b'\n')) { pos += 1; } (bytes.get(pos) == Some(&b'(')).then_some(pos as u32) } /// A bracketed expression list (concatenation, call arguments, `inside` /// set). Comments on an element ride along and break the list open. fn expr_list(&self, open: &str, items: &[ExprItem], close: &str) -> Doc { let items: Vec = 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(")")]) } /// `( expr )` with the comments the source wrote just inside the /// parentheses. A comment there forces them open, the same way a comment /// inside a port list does. fn paren_comments(&self, inner: &Expr, before: &[&Comment], after: &[&Comment]) -> Doc { 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) } /// The `(cond)` of a statement header, taking back the comments the parser /// handed to the construct's *body* because they were written before the /// closing `)`. /// /// Nothing between `(` and `)` owns trivia, so a comment written inside a /// header's parentheses stays queued and lands on the next node that takes /// meta — the body statement, or a `case`'s first item. Printed there it /// would sit *after* a `)` it was written before, and `verify.rs` refuses /// the file, rightly: the comment moved across a token. /// /// Returns the header doc and how many of `body`'s leading comments it /// consumed, which the caller must then skip. When the source does not /// have the expected shape nothing is taken and the plain parentheses are /// printed, so an unrecognized header is left exactly as it was. fn header_parens(&self, cond: &Expr, body: &Meta) -> (Doc, usize) { let close = match skip_trivia(self.src, cond.span.end as usize) { Some(i) if self.src.as_bytes().get(i) == Some(&b')') => i as u32, _ => return (self.parens(cond), 0), }; let taken = body.leading.iter().take_while(|c| c.span.start < close).count(); if taken == 0 { return (self.parens(cond), 0); } let (before, after): (Vec<&Comment>, Vec<&Comment>) = body.leading[..taken].iter().partition(|c| c.span.start < cond.span.start); (self.paren_comments(cond, &before, &after), taken) } /// True when the source wrote the optional `:` after a `default` case /// label. IEEE 1800 §12.5 makes it optional — `default;` is legal — and /// the token stream has to come back with exactly what was written. fn default_has_colon(&self, span: TextRange) -> bool { let after = span.start as usize + "default".len(); matches!(skip_trivia(self.src, after), Some(i) if self.src.as_bytes()[i] == b':') } /// Sequence of items at one indent level, preserving single blank lines /// between them. An item a fenced region swallowed emits nothing, and /// contributes no separator either. fn item_seq(&self, items: &[Item], depth: usize) -> Vec { let aligns = self.param_decl_aligns(items, depth); let mut docs = Vec::new(); for (item, align) in items.iter().zip(&aligns) { let item_docs = self.item_docs(item, align.as_ref(), depth); if item_docs.is_empty() { continue; } if !docs.is_empty() { docs.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); } docs.extend(item_docs); } docs } fn stmt_seq(&self, stmts: &[Stmt]) -> Vec { 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 { let mut docs = Vec::new(); for c in comments { let doc = match self.slot(c) { Slot::Covered => continue, Slot::Opens(r) => self.verbatim(r), Slot::Normal => self.comment(c), }; docs.push(if c.blank_before { Doc::BlankLine } else { Doc::HardLine }); docs.push(doc); } docs } // ------------------------------------------------------------------ // File / items // ------------------------------------------------------------------ fn file(&self, f: &SourceFile) -> Doc { let mut docs = self.item_seq(&f.items, 0); for c in &f.dangling { let doc = match self.slot(c) { Slot::Covered => continue, Slot::Opens(r) => self.verbatim(r), Slot::Normal => self.comment(c), }; if !docs.is_empty() { docs.push(if c.blank_before { Doc::BlankLine } else { Doc::HardLine }); } docs.push(doc); } concat(docs) } fn item(&self, item: &Item, depth: usize) -> Doc { concat(self.item_docs(item, None, depth)) } /// One item: its leading comments, then — unless a verbatim region is /// already emitting its bytes — its attributes, code and trailing /// comment. Comments before the `off` fence are still emitted; comments /// are never dropped. fn item_docs(&self, item: &Item, align: Option<&Align>, depth: usize) -> Vec { if let Some(split) = self.split_at(item.span.start as usize) { if let Some(docs) = self.split_item(item, split, depth) { return docs; } } // A verbatim run whose first item carries no leading comment opens at // the item's own code; there is no comment to emit the bytes from. if let Some(region) = self.opens_at(item.span.start as usize) { return vec![self.verbatim(region)]; } if self.is_verbatim(item.span) { // The item's own bytes, its attributes included, are emitted // verbatim by the fence; only its leading comments are ours. let mut docs = self.leading_comments(&item.meta); // The last comment asked for a line break before code that is not // coming. Whoever emits the next unit separates it itself. if matches!(docs.last(), Some(Doc::HardLine)) { docs.pop(); } return docs; } let mut docs = self.leading(&item.meta); docs.push(self.item_kind(&item.kind, align, depth)); docs.extend(self.trailing(&item.meta)); docs } /// A scope-bearing item a range run descends into. /// /// Its header and its closing keyword are the source's own bytes unless /// the caller's lines reached them, and its body is laid out one item at a /// time — which is what keeps a three-line edit from reformatting a /// two-thousand-line module. `None` for any other item kind, which /// `range.rs` never records a split for. fn split_item(&self, item: &Item, split: &Split, depth: usize) -> Option> { let (items, dangling) = match &item.kind { ItemKind::Module(m) => (&m.items[..], &m.dangling[..]), ItemKind::Package { items, dangling, .. } => (&items[..], &dangling[..]), _ => return None, }; let mut docs = Vec::new(); match split.head { Some(range) => docs.push(self.slice(range)), None => { docs.extend(self.leading(&item.meta)); docs.push(self.head_doc(&item.kind, depth)?); } } let mut body = Vec::new(); if !items.is_empty() { body.push(Doc::HardLine); body.extend(self.item_seq(items, depth + 1)); } body.extend(self.dangling(dangling)); docs.push(indent(body)); docs.push(Doc::HardLine); match split.tail { // The slice reaches over the comment written after the keyword, // so the trailing comment must not be printed a second time. Some(range) => docs.push(self.slice(range)), None => { docs.push(Self::tail_doc(&item.kind)?); docs.extend(self.trailing(&item.meta)); } } Some(docs) } /// A split item's header, laid out. fn head_doc(&self, kind: &ItemKind, depth: usize) -> Option { match kind { ItemKind::Module(m) => Some(self.module_head(m, depth)), ItemKind::Package { kw, name, .. } => Some(text(format!("{kw} {name};"))), _ => None, } } /// A split item's closing keyword, laid out. fn tail_doc(kind: &ItemKind) -> Option { match kind { ItemKind::Module(m) => Some(Self::closing(m.end_kw(), &m.end_label)), ItemKind::Package { end_label, .. } => Some(Self::closing("endpackage", end_label)), _ => None, } } fn item_kind(&self, kind: &ItemKind, align: Option<&Align>, depth: usize) -> Doc { match kind { ItemKind::Module(m) => self.module(m, depth), ItemKind::Package { kw, name, items, dangling, end_label, .. } => { let mut docs = vec![text(format!("{kw} {name};"))]; let mut body = Vec::new(); if !items.is_empty() { body.push(Doc::HardLine); body.extend(self.item_seq(items, depth + 1)); } body.extend(self.dangling(dangling)); docs.push(indent(body)); docs.push(Doc::HardLine); docs.push(Self::closing("endpackage", end_label)); concat(docs) } ItemKind::Directive(d) => self.raw_text(d), // Only error-tolerant parsing builds these, and `format_source` // parses strictly, so this arm exists to keep the match total. ItemKind::Error(d) => self.raw_text(d), ItemKind::MacroItem(m) => self.macro_call(m), // Printed exactly like the statement it looks like; the call's own // argument group supplies the line breaks. ItemKind::ElabTask(e) => concat(vec![self.expr(e), text(";")]), ItemKind::Import(paths) => text(format!("import {};", join_paths(paths))), ItemKind::Export(e) => Self::export(e), ItemKind::Timeunit(t) => text(format!("{t};")), ItemKind::Typedef(t) => self.typedef(t), ItemKind::ParamDecl(d) => concat(vec![self.param_decl(d, align), text(";")]), ItemKind::DataDecl(d) => concat(vec![self.data_decl(d), text(";")]), ItemKind::PortDecl(d) => concat(vec![self.port_decl(d), text(";")]), ItemKind::ContAssign(a) => self.cont_assign(a), ItemKind::Always { kw, stmt } => self.stmt_as_body(text(kw.clone()), stmt), ItemKind::Initial(s) => self.stmt_as_body(text("initial"), s), ItemKind::Final(s) => self.stmt_as_body(text("final"), s), ItemKind::Instantiation(inst) => self.instantiation(inst, depth), ItemKind::Bind(b) => self.bind(b, depth), ItemKind::GateInstantiation(g) => self.gate_instantiation(g), ItemKind::Genvar(names) => text(format!("genvar {};", join_names(names))), ItemKind::GenerateRegion { items, dangling } => { let mut body = Vec::new(); if !items.is_empty() { body.push(Doc::HardLine); body.extend(self.item_seq(items, depth + 1)); } body.extend(self.dangling(dangling)); concat(vec![text("generate"), indent(body), Doc::HardLine, text("endgenerate")]) } ItemKind::GenIf(g) => self.gen_if(g, depth), ItemKind::GenFor(g) => self.gen_for(g, depth), ItemKind::GenCase(g) => self.gen_case(g, depth), ItemKind::Function(f) => self.function(f), ItemKind::Task(t) => self.task(t), ItemKind::Let(l) => self.let_decl(l), ItemKind::Class(c) => self.class(c, depth), ItemKind::Modport(decls) => self.modport(decls), ItemKind::Clocking(c) => self.clocking(c), ItemKind::Verbatim(raw) => self.raw_text(raw), ItemKind::Defparam(pairs) => { let parts: Vec = pairs .iter() .map(|(l, r)| concat(vec![self.expr(l), text(" = "), self.expr(r)])) .collect(); let mut docs = vec![text("defparam ")]; docs.extend(join(parts, text(", "))); docs.push(text(";")); concat(docs) } } } // ------------------------------------------------------------------ // Module // ------------------------------------------------------------------ fn module(&self, m: &Module, depth: usize) -> Doc { let mut docs = vec![self.module_head(m, depth)]; let mut body = Vec::new(); if !m.items.is_empty() { body.push(Doc::HardLine); body.extend(self.item_seq(&m.items, depth + 1)); } body.extend(self.dangling(&m.dangling)); docs.push(indent(body)); docs.push(Doc::HardLine); docs.push(Self::closing(m.end_kw(), &m.end_label)); concat(docs) } /// A module header: everything through the `;` that closes it. /// /// Split out from the body so a range run can keep one and lay out the /// other (`range.rs`); a whole-file run always emits both. fn module_head(&self, m: &Module, depth: usize) -> Doc { let mut docs = vec![text(format!("{} {}", m.kw, m.name))]; let has_imports = !m.imports.is_empty(); if has_imports { // One line per `import` statement the header wrote: folding two of // them into one comma-separated statement would rewrite a `;`. let mut lines = Vec::new(); for imp in &m.imports { lines.push(Doc::HardLine); lines.extend(self.leading(&imp.meta)); lines.push(text(format!("import {};", join_paths(&imp.paths)))); lines.extend(self.trailing(&imp.meta)); } docs.push(indent(lines)); docs.push(Doc::HardLine); } // After an import block the header continues at column 0, so the // usual single space before `#(`/`(` is dropped. let mut on_fresh_line = has_imports; on_fresh_line = self.bracket_comments(&m.param_comments, &mut docs, on_fresh_line); // A written-but-empty `#()` is printed back; a missing one stays // missing. if let Some(params) = &m.param_ports { let items: Vec = params .iter() .map(|p| ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma)) .collect(); let items = self.list_entries(items, &m.param_directives); let broken = !m.param_directives.is_empty(); docs.push(text(if on_fresh_line { "#" } else { " #" })); docs.push(self.delimited_dangling("(", items, &m.param_dangling, ")", broken)); on_fresh_line = false; } let on_fresh_line = self.bracket_comments(&m.port_comments, &mut docs, on_fresh_line); // A port list whose every element sits in an `ifdef arm still holds // directives while being `PortList::Empty`, so the two are laid out by // the same code. let mut broken = !m.port_directives.is_empty(); match &m.ports { PortList::None => docs.push(text(";")), PortList::Empty | PortList::Ansi(_) | PortList::NonAnsi(_) => { let items: Vec = match &m.ports { PortList::Ansi(ports) => { // An aligned list is a broken list: alignment only // means anything one element per line. let aligns = self.ansi_port_aligns(ports, &m.port_directives, depth + 1); broken |= aligns.iter().any(Option::is_some); ports .iter() .zip(&aligns) .map(|(p, a)| { ListItem::from_meta(&p.meta, self.ansi_port(p, a.as_ref())) .with_comma(p.comma) }) .collect() } PortList::NonAnsi(ports) => ports .iter() .map(|p| { ListItem::from_meta(&p.meta, text(p.name.clone())).with_comma(p.comma) }) .collect(), _ => Vec::new(), }; let items = self.list_entries(items, &m.port_directives); if !on_fresh_line { docs.push(text(" ")); } docs.push(self.delimited_dangling("(", items, &m.port_dangling, ")", broken)); docs.push(text(";")); } } concat(docs) } fn param_port(&self, p: &ParamPort) -> Doc { let mut parts: Vec = Vec::new(); if let Some(kw) = &p.kw { parts.push(kw.clone()); } if p.is_type { parts.push("type".to_string()); } let mut docs = Vec::new(); let ty = self.data_type(&p.ty); let prefix = parts.join(" "); if !prefix.is_empty() { docs.push(text(prefix)); docs.push(text(" ")); } if let Some(t) = ty { docs.push(t); docs.push(text(" ")); } docs.push(text(p.name.clone())); docs.extend(self.unpacked_dims(&p.unpacked)); if let Some(d) = &p.default { docs.push(text(" = ")); docs.push(group(vec![self.expr(d)])); } concat(docs) } fn ansi_port(&self, p: &AnsiPort, align: Option<&Align>) -> Doc { align::render(&self.ansi_port_cells(p), ANSI_PORT_COLS, align) } /// An ANSI port split at its one alignment column, the name: the /// direction/net/type prefix, then the name and everything after it. A /// port with no prefix at all (a continuation port, `output a, b`) is one /// cell, which is what takes it out of every alignment group. fn ansi_port_cells(&self, p: &AnsiPort) -> Vec { let mut prefix = Vec::new(); if let Some(dir) = &p.dir { prefix.push(text(format!("{dir} "))); } if let Some(net) = &p.net { prefix.push(text(format!("{net} "))); } if let Some(t) = self.data_type(&p.ty) { prefix.push(t); prefix.push(text(" ")); } // The trailing space of the last prefix part is the column separator, // which `align::render` writes instead. if let Some(Doc::Text(last)) = prefix.last_mut() { if last.ends_with(' ') { last.pop(); } } let mut docs = vec![text(p.name.clone())]; docs.extend(self.unpacked_dims(&p.unpacked)); if let Some(d) = &p.default { docs.push(text(" = ")); docs.push(self.expr(d)); } if prefix.is_empty() { return vec![concat(docs)]; } vec![concat(prefix), concat(docs)] } // ------------------------------------------------------------------ // Types and declarations // ------------------------------------------------------------------ /// Format a data type; `None` if fully implicit. fn data_type(&self, ty: &DataType) -> Option { if ty.is_implicit() { return None; } let mut docs = Vec::new(); let mut need_space = false; // `virtual clk_rst_if`, `virtual interface bus_if`. if let Some(v) = ty.virt { docs.push(text(v.text())); need_space = true; } if !ty.name.is_empty() { if need_space { docs.push(text(" ")); } docs.push(text(ty.name.clone())); need_space = true; } // `uvm_analysis_port #(bit [31:0]) port;` — spaced before the `#(`, // like an instantiation's overrides and unlike the tight `#(` of a // parameterized name in expression position. if let Some(params) = ty.params() { if need_space { docs.push(text(" ")); } docs.push(self.raw_inline(params)); need_space = true; } if let Some(s) = &ty.signing { if need_space { docs.push(text(" ")); } docs.push(text(s.clone())); need_space = true; } if !ty.packed.is_empty() { if need_space { docs.push(text(" ")); } for d in &ty.packed { docs.push(self.dim(d)); } need_space = true; } // An anonymous aggregate is the type itself, so it never shares the // line with a name — but it can follow a `virtual` prefix, and the // `need_space` bookkeeping above is what puts the space in. match ty.inline() { Some(TypeExtra::Enum(e)) => { if need_space { docs.push(text(" ")); } docs.push(self.enum_type(e)); } Some(TypeExtra::Struct(s)) => { if need_space { docs.push(text(" ")); } docs.push(self.struct_type(s)); } _ => {} } Some(concat(docs)) } fn dim(&self, d: &Dim) -> Doc { match &d.kind { DimKind::Range { a, b } => { let mut docs = vec![text("["), self.expr_compact(a)]; if let Some(b) = b { docs.push(text(":")); docs.push(self.expr_compact(b)); } docs.push(text("]")); concat(docs) } DimKind::Dynamic => text("[]"), DimKind::Wildcard => text("[*]"), } } /// Compact rendering used inside `[...]` brackets: arithmetic and shift /// operators lose their surrounding spaces (`[WIDTH-1:0]`), and no line /// breaks are introduced. fn expr_compact(&self, e: &Expr) -> Doc { match &e.kind { ExprKind::Binary { lhs, op, rhs, comments } => { if comments.before.is_empty() && comments.after.is_empty() { let tight = Self::binary_prec(op) >= 8; let sep = if tight { op.clone() } else { format!(" {op} ") }; return concat(vec![self.expr_compact(lhs), text(sep), self.expr_compact(rhs)]); } // A comment written next to the operator has nowhere to go in // the tight spelling, so the operator gets its spaces back; // a line comment pushes what follows onto the next line. let mut docs = vec![self.expr_compact(lhs)]; self.inline_comments_spaced(&comments.before, &mut docs); docs.push(text(op.clone())); self.inline_comments_spaced(&comments.after, &mut docs); docs.push(self.expr_compact(rhs)); concat(docs) } ExprKind::Ternary { cond, then, els, .. } => concat(vec![ self.expr_compact(cond), text(" ? "), self.expr_compact(then), text(" : "), self.expr_compact(els), ]), ExprKind::Paren { inner, .. } => { concat(vec![text("("), self.expr_compact(inner), text(")")]) } ExprKind::Unary { op, expr } => concat(vec![text(op.clone()), self.expr_compact(expr)]), _ => self.expr(e), } } fn unpacked_dims(&self, dims: &[Dim]) -> Vec { 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 = decls .iter() .map(|d| { let mut docs = vec![text(d.name.clone())]; docs.extend(self.unpacked_dims(&d.unpacked)); if let Some(init) = &d.init { docs.push(text(" =")); docs.push(group(vec![self.assign_rhs(self.expr(init))])); } ListItem::from_meta(&d.meta, concat(docs)) }) .collect(); if items.len() == 1 { let item = items.into_iter().next().unwrap(); let mut docs = self.leading(&Meta { leading: item.leading, ..Meta::default() }); docs.push(item.doc); let mut ends_line = self.inline_comments(&item.before_sep, &mut docs); if let Some(tr) = item.trailing { docs.push(if ends_line { Doc::HardLine } else { text(" ") }); docs.push(self.comment(&tr)); ends_line = is_line_comment(&tr.text); } // The caller appends the `;`; a line comment runs to end of line, // so it has to go on the next one. if ends_line { docs.push(Doc::HardLine); } return concat(docs); } // Multiple declarators: allow one-per-line continuation. let mut inner = Vec::new(); let last = items.len() - 1; for (i, item) in items.into_iter().enumerate() { let meta = Meta { leading: item.leading, ..Meta::default() }; inner.extend(self.leading(&meta)); inner.push(item.doc); let ends_line = self.inline_comments(&item.before_sep, &mut inner); if i < last { if ends_line { inner.push(Doc::HardLine); } inner.push(text(",")); } else if ends_line { inner.push(Doc::HardLine); } if let Some(tr) = item.trailing { inner.push(text(" ")); inner.push(self.comment(&tr)); if i < last || is_line_comment(&tr.text) { inner.push(Doc::HardLine); } } else if i < last { inner.push(Doc::Line); } } group(vec![indent(inner)]) } /// A `parameter`/`localparam` declaration. With an alignment plan it is /// laid out as cells padded to the group's columns; without one it takes /// the flush path every other declaration takes. /// /// The two must agree byte-for-byte when the padding collapses, because /// that is exactly what the printer's line-limit fallback does — and the /// next pass, seeing no excess spaces, comes back through the flush path. fn param_decl(&self, d: &ParamDecl, align: Option<&Align>) -> Doc { if let (Some(a), [decl]) = (align, &d.declarators[..]) { if let Some(init) = &decl.init { return align::render( &self.param_decl_cells(d, decl, init), PARAM_DECL_COLS, Some(a), ); } } let mut docs = vec![text(d.kw.clone()), text(" ")]; if d.is_type { docs.push(text("type ")); } if let Some(t) = self.data_type(&d.ty) { docs.push(t); docs.push(text(" ")); } docs.push(self.declarators(&d.declarators)); concat(docs) } /// A `parameter`/`localparam` declaration split at its two alignment /// columns: the keyword and type, the name, and the `= value`. fn param_decl_cells(&self, d: &ParamDecl, decl: &Declarator, init: &Expr) -> Vec { let mut prefix = vec![text(d.kw.clone())]; if d.is_type { prefix.push(text(" type")); } if let Some(t) = self.data_type(&d.ty) { prefix.push(text(" ")); prefix.push(t); } let mut name = vec![text(decl.name.clone())]; name.extend(self.unpacked_dims(&decl.unpacked)); vec![ concat(prefix), concat(name), concat(vec![text("="), group(vec![self.assign_rhs(self.expr(init))])]), ] } fn data_decl(&self, d: &DataDecl) -> Doc { let mut docs = Vec::new(); if let Some(net) = &d.net { docs.push(text(format!("{net} "))); } if let Some(delay) = &d.delay { docs.push(text("#")); docs.push(self.expr(delay)); docs.push(text(" ")); } for q in &d.qualifiers { docs.push(text(format!("{q} "))); } if let Some(t) = self.data_type(&d.ty) { docs.push(t); docs.push(text(" ")); } docs.push(self.declarators(&d.declarators)); concat(docs) } fn port_decl(&self, d: &PortDecl) -> Doc { let mut docs = vec![text(format!("{} ", d.dir))]; if let Some(net) = &d.net { docs.push(text(format!("{net} "))); } if let Some(t) = self.data_type(&d.ty) { docs.push(t); docs.push(text(" ")); } docs.push(self.declarators(&d.declarators)); concat(docs) } fn typedef(&self, t: &Typedef) -> Doc { match &t.kind { TypedefKind::ForwardClass => text(format!("typedef class {};", t.name)), TypedefKind::Alias(ty) => { let mut docs = vec![text("typedef ")]; if let Some(d) = self.data_type(ty) { docs.push(d); docs.push(text(" ")); } docs.push(text(t.name.clone())); docs.extend(self.unpacked_dims(&t.unpacked)); docs.push(text(";")); concat(docs) } TypedefKind::Enum(e) => { concat(vec![text("typedef "), self.enum_type(e), text(format!(" {};", t.name))]) } TypedefKind::Struct(s) => { concat(vec![text("typedef "), self.struct_type(s), text(format!(" {};", t.name))]) } } } /// `enum [base] { A, B }` — one line if it fits, else one member per line. /// Shared by `typedef enum ...` and by an anonymous enum standing where a /// type name would (`enum logic [1:0] {IDLE, STOP} state;`). fn enum_type(&self, e: &EnumType) -> Doc { let mut docs = vec![text("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 = e .members .iter() .map(|m| { let mut d = vec![text(m.name.clone())]; if let Some(v) = &m.value { d.push(text(" = ")); d.push(self.expr(v)); } ListItem::from_meta(&m.meta, concat(d)).with_comma(m.comma) }) .collect(); let items = self.list_entries(items, &e.directives); // `e.dangling` — comments written before the closing `}` — is printed // inside the braces; the enum has no other place to put it, and // dropping it loses a comment. let broken = !e.directives.is_empty(); docs.push(self.delimited_dangling("{", items, &e.dangling, "}", broken)); concat(docs) } /// `struct|union [packed] [signing] { ... }`, always one member per line. /// Shared by `typedef struct ...`, an anonymous struct standing where a /// type name would, and a struct member whose own type is an inline /// struct — the recursion is what indents a nested body one more level. fn struct_type(&self, s: &StructType) -> Doc { let mut header = s.kw.clone(); 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("}")]) } // ------------------------------------------------------------------ // 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(s) = &a.strength { docs.push(text(format!("({}, {}) ", s.first, s.second))); } if let Some(delay) = &a.delay { docs.push(text("#")); docs.push(self.expr(delay)); docs.push(text(" ")); } let items: Vec = 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) } /// `bind [: u_a, u_b] `: the head is one flat run /// of names, and everything after it is laid out exactly as the same /// instantiation written on its own would be. fn bind(&self, b: &BindDirective, depth: usize) -> Doc { let head = if b.instances.is_empty() { b.target.clone() } else { format!("{} : {}", b.target, join_names(&b.instances)) }; // The comments around the head have no node of their own; each prints // back between the two tokens it was written between. let mut docs = vec![text("bind")]; self.inline_comments_spaced(&b.target_comments, &mut docs); docs.push(text(head)); self.inline_comments_spaced(&b.module_comments, &mut docs); docs.push(self.instantiation(&b.inst, depth)); concat(docs) } fn instantiation(&self, inst: &Instantiation, depth: usize) -> Doc { let mut docs = vec![text(inst.module.clone())]; let mut on_fresh_line = self.bracket_comments(&inst.param_comments, &mut docs, false); // An empty `#()` was written by hand and is reprinted as `#()`; a // missing one stays missing. if let Some(params) = &inst.params { let items: Vec = params .iter() .map(|c| ListItem::from_meta(&c.meta, self.connection(c)).with_comma(c.comma)) .collect(); let items = self.list_entries(items, &inst.param_directives); let broken = !inst.param_directives.is_empty(); docs.push(text(if on_fresh_line { "#" } else { " #" })); docs.push(self.delimited("(", items, ")", broken)); on_fresh_line = false; } if let [only] = &inst.instances[..] { // The common case: no extra indent level, so a connection list // that breaks lines up under the instance itself. The comments // before the instance name print here — the multi-instance branch // below has `leading` for them, and this one had nowhere at all. if !self.bracket_comments(&only.meta.leading, &mut docs, on_fresh_line) { docs.push(text(" ")); } docs.push(self.instance(only, depth)); } else { if !on_fresh_line { docs.push(text(" ")); } // Several instances share one declaration: keep them on one line // if they fit, otherwise one per line, indented under the head. let last = inst.instances.len() - 1; let mut inner = Vec::new(); for (i, instance) in inst.instances.iter().enumerate() { inner.extend(self.leading(&instance.meta)); inner.push(self.instance(instance, depth + 1)); if self.inline_comments(&instance.meta.before_sep, &mut inner) { inner.push(Doc::HardLine); } if i < last { inner.push(text(",")); } if let Some(tr) = &instance.meta.trailing { inner.push(text(" ")); inner.push(self.comment(tr)); if i < last { inner.push(Doc::HardLine); } } else if i < last { inner.push(Doc::Line); } } docs.push(group(vec![indent(inner)])); } docs.push(text(";")); concat(docs) } /// One instance of a module instantiation: `u0 [3:0] (.a(x))`. fn instance(&self, instance: &Instance, depth: usize) -> Doc { let mut docs = vec![text(instance.name.clone())]; if !instance.dims.is_empty() { docs.push(text(" ")); for d in &instance.dims { docs.push(self.dim(d)); } } if !self.bracket_comments(&instance.conn_comments, &mut docs, false) { docs.push(text(" ")); } docs.push(self.connections(&instance.conns, &instance.conn_directives, depth + 1)); concat(docs) } /// A connection list, with the `` `ifdef``-style directives written between /// its entries merged back into source order. A list holding one is laid /// out broken: a directive runs to end of line, so nothing may share it. fn connections(&self, conns: &Connections, directives: &[ListDirective], depth: usize) -> Doc { let mut broken = !directives.is_empty(); let items: Vec = match conns { Connections::Named(list) => { let aligns = self.connection_aligns(list, directives, depth); broken |= aligns.iter().any(Option::is_some); list.iter() .zip(&aligns) .map(|(c, a)| { ListItem::from_meta(&c.meta, self.connection_aligned(c, a.as_ref())) .with_comma(c.comma) }) .collect() } Connections::Ordered(list) => list .iter() .map(|c| { let d = match &c.expr { Some(e) => self.expr(e), None => text(""), }; ListItem::from_meta(&c.meta, d).with_comma(c.comma) }) .collect(), }; let items = self.list_entries(items, directives); self.delimited("(", items, ")", broken) } fn connection(&self, c: &Connection) -> Doc { self.connection_aligned(c, None) } fn connection_aligned(&self, c: &Connection, align: Option<&Align>) -> Doc { align::render(&self.connection_cells(c), CONNECTION_COLS, align) } /// A named connection split at its one alignment column, the `(` of the /// value: `.data_i` and `(bus[7:0])`. Everything else — `.*`, an implicit /// `.clk`, a positional value, a connection with comments inside its own /// parens — is one cell and never joins a group. fn connection_cells(&self, c: &Connection) -> Vec { let plain = || vec![self.connection_plain(c)]; // An attributed connection is one cell: the attribute widens the row // by an amount no other row shares, so it never joins a group — // `list_breaks` already ends the group at it, as it does at a // compiler directive. if c.name.is_empty() || c.name == "*" || !c.meta.attrs.is_empty() { return plain(); } let Some(e) = &c.expr else { return plain() }; if matches!(e.kind, ExprKind::Empty(_)) { return plain(); } let mut inner = vec![Doc::SoftLine, self.expr(e)]; let ends_line = self.inline_comments(&c.close_comments, &mut inner); let close = if ends_line { Doc::HardLine } else { Doc::SoftLine }; vec![ text(format!(".{}", c.name)), concat(vec![text("("), group(vec![indent(inner), close]), text(")")]), ] } fn connection_plain(&self, c: &Connection) -> Doc { // `(* async *) .async_data_o (x)`: the attributes stay in front of // the connection, on its line (corpus // `common_cells/src/cdc_fifo_gray.sv:140`). if !c.meta.attrs.is_empty() { let mut docs = Vec::new(); for attr in &c.meta.attrs { docs.push(self.raw_inline(attr)); docs.push(text(" ")); } docs.push(self.connection_bare(c)); return concat(docs); } self.connection_bare(c) } /// A connection without its attributes: `.name(expr)`, `.name()`, /// `.name`, `.*`, or a positional value. fn connection_bare(&self, c: &Connection) -> Doc { if c.name == "*" { return text(".*"); } if c.name.is_empty() { // Positional parameter value. return match &c.expr { Some(e) => self.expr(e), None => text(""), }; } match &c.expr { None => text(format!(".{}", c.name)), Some(Expr { kind: ExprKind::Empty(comments), .. }) => { let mut docs = vec![text(format!(".{}(", c.name))]; let mut ends_line = false; for cm in comments { if ends_line { docs.push(Doc::HardLine); } docs.push(self.comment(cm)); ends_line = is_line_comment(&cm.text); } if ends_line { docs.push(Doc::HardLine); } docs.push(text(")")); concat(docs) } Some(e) => { let mut inner = vec![Doc::SoftLine, self.expr(e)]; let ends_line = self.inline_comments(&c.close_comments, &mut inner); let close = if ends_line { Doc::HardLine } else { Doc::SoftLine }; concat(vec![ text(format!(".{}(", c.name)), group(vec![indent(inner), close]), text(")"), ]) } } } fn gate_instantiation(&self, g: &GateInstantiation) -> Doc { let mut docs = vec![text(g.gate.clone())]; if let Some(delay) = &g.delay { docs.push(text(" #")); docs.push(self.expr(delay)); } for (i, inst) in g.instances.iter().enumerate() { docs.push(if i > 0 { text(", ") } else { text(" ") }); if let Some(name) = &inst.name { docs.push(text(name.clone())); docs.push(text(" ")); } docs.push(self.expr_list("(", &inst.args, ")")); } docs.push(text(";")); concat(docs) } // ------------------------------------------------------------------ // Generate constructs // ------------------------------------------------------------------ fn gen_if(&self, g: &GenIf, depth: usize) -> Doc { let mut docs = vec![text("if "), self.parens(&g.cond)]; let mut cuddle = self.gen_block(&mut docs, &g.then, depth); let mut els = &g.els; while let Some(e) = els { match e.as_ref() { GenElse::If(_meta, gi) => { if cuddle { docs.push(text(" else if ")); } else { docs.push(Doc::HardLine); docs.push(text("else if ")); } docs.push(self.parens(&gi.cond)); cuddle = self.gen_block(&mut docs, &gi.then, depth); els = &gi.els; } GenElse::Block(b) => { if cuddle { docs.push(text(" else")); } else { docs.push(Doc::HardLine); docs.push(text("else")); } self.gen_block(&mut docs, b, depth); break; } } } concat(docs) } /// Append a generate block; returns true if it ended with `end` (so /// `else` can cuddle). fn gen_block(&self, docs: &mut Vec, b: &GenBlock, depth: usize) -> bool { if b.is_block { match &b.label { Some(l) => docs.push(text(format!(" begin : {l}"))), None => docs.push(text(" begin")), } let mut body = Vec::new(); if !b.items.is_empty() { body.push(Doc::HardLine); body.extend(self.item_seq(&b.items, depth + 1)); } body.extend(self.dangling(&b.dangling)); docs.push(indent(body)); docs.push(Doc::HardLine); docs.push(Self::closing("end", &b.end_label)); true } else { let item = &b.items[0]; docs.push(group(vec![indent(vec![Doc::Line, self.item(item, depth + 1)])])); false } } fn gen_for(&self, g: &GenFor, depth: usize) -> Doc { let mut header = vec![text("for (")]; if g.init_genvar { header.push(text("genvar ")); } header.push(self.expr(&g.init.lhs)); header.push(text(format!(" {} ", g.init.op))); header.push(self.expr(&g.init.rhs)); header.push(text("; ")); header.push(self.expr(&g.cond)); header.push(text("; ")); header.push(self.for_step(&g.step)); header.push(text(")")); let mut docs = vec![concat(header)]; self.gen_block(&mut docs, &g.body, depth); concat(docs) } fn gen_case(&self, g: &GenCase, depth: usize) -> Doc { let mut docs = vec![text("case "), self.parens(&g.expr)]; let mut body = Vec::new(); for item in &g.items { body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); body.extend(self.leading(&item.meta)); let mut item_docs = vec![self.case_labels(&item.labels, item.span)]; self.gen_block(&mut item_docs, &item.body, depth + 1); body.push(concat(item_docs)); body.extend(self.trailing(&item.meta)); } body.extend(self.dangling(&g.dangling)); docs.push(indent(body)); docs.push(Doc::HardLine); docs.push(text("endcase")); concat(docs) } fn for_step(&self, step: &ForStep) -> Doc { match step { ForStep::Assign(a) => { concat(vec![self.expr(&a.lhs), text(format!(" {} ", a.op)), self.expr(&a.rhs)]) } ForStep::Expr(e) => self.expr(e), } } // ------------------------------------------------------------------ // Functions and tasks // ------------------------------------------------------------------ fn tf_args(&self, args: &[TfArg]) -> Doc { let items: Vec = args .iter() .map(|a| { let mut docs = Vec::new(); if let Some(dir) = &a.dir { docs.push(text(format!("{dir} "))); } if let Some(t) = self.data_type(&a.ty) { docs.push(t); docs.push(text(" ")); } docs.push(text(a.name.clone())); docs.extend(self.unpacked_dims(&a.unpacked)); if let Some(d) = &a.default { docs.push(text(" = ")); docs.push(self.expr(d)); } ListItem::from_meta(&a.meta, concat(docs)) }) .collect(); self.delimited("(", items, ")", false) } /// A class: header on one line (its parameter and `extends` override /// lists break like any other list when they do not fit), body items at /// one more indent level, `endclass` with the label the source wrote. fn class(&self, c: &ClassDecl, depth: usize) -> Doc { let mut head = String::new(); for q in &c.prefix { head.push_str(q); head.push(' '); } head.push_str("class "); if let Some(lifetime) = &c.lifetime { head.push_str(lifetime); head.push(' '); } head.push_str(&c.name); let mut docs = vec![text(head)]; let on_fresh_line = self.bracket_comments(&c.param_comments, &mut docs, false); if let Some(params) = &c.param_ports { let items: Vec = params .iter() .map(|p| ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma)) .collect(); let items = self.list_entries(items, &c.param_directives); let broken = !c.param_directives.is_empty(); docs.push(text(if on_fresh_line { "#" } else { " #" })); docs.push(self.delimited_dangling("(", items, &c.param_dangling, ")", broken)); } if let Some(ext) = &c.extends { docs.push(text(format!(" extends {}", ext.name))); let fresh = self.bracket_comments(&ext.param_comments, &mut docs, false); if let Some(params) = &ext.params { let items: Vec = params .iter() .map(|p| ListItem::from_meta(&p.meta, self.connection(p)).with_comma(p.comma)) .collect(); let items = self.list_entries(items, &ext.param_directives); let broken = !ext.param_directives.is_empty(); docs.push(text(if fresh { "#" } else { " #" })); docs.push(self.delimited("(", items, ")", broken)); } } if !c.implements.is_empty() { docs.push(text(format!(" implements {}", join_names(&c.implements)))); } docs.push(text(";")); let mut body = Vec::new(); if !c.items.is_empty() { body.push(Doc::HardLine); body.extend(self.item_seq(&c.items, depth + 1)); } body.extend(self.dangling(&c.dangling)); docs.push(indent(body)); docs.push(Doc::HardLine); docs.push(Self::closing("endclass", &c.end_label)); concat(docs) } /// `modport a (input x, output y), b (...);` (IEEE 1800 §25.5). /// /// Each modport's port list is a breakable group of its own, laid out /// exactly like a header port list: one line when it fits, one entry per /// line when it does not. A direction keyword and the names it governs are /// one entry, so the source's grouping (`input valid, data`) survives. fn modport(&self, decls: &[ModportDecl]) -> Doc { let mut docs = vec![text("modport")]; let last = decls.len().saturating_sub(1); let mut on_fresh_line = false; for (i, d) in decls.iter().enumerate() { if !on_fresh_line { docs.push(text(" ")); } docs.extend(self.leading(&d.meta)); docs.push(text(format!("{} ", d.name))); let items: Vec = d .ports .iter() .map(|p| ListItem::from_meta(&p.meta, self.modport_port(p)).with_comma(p.comma)) .collect(); docs.push(self.delimited_dangling("(", items, &d.dangling, ")", false)); let ends_line = self.inline_comments(&d.meta.before_sep, &mut docs); if i < last { if ends_line { docs.push(Doc::HardLine); } docs.push(text(",")); } on_fresh_line = false; if let Some(tr) = &d.meta.trailing { docs.push(text(" ")); docs.push(self.comment(tr)); if i < last { docs.push(Doc::HardLine); on_fresh_line = true; } } } docs.push(text(";")); concat(docs) } /// One direction group of a modport port list: `input valid, data`. fn modport_port(&self, p: &ModportPort) -> Doc { text(format!("{} {}", p.kw, join_names(&p.names))) } /// `clocking cb @(posedge clk); ... endclocking` (IEEE 1800 §14.3), one /// item per line — the body is a declaration list, not an expression, so /// there is nothing here worth collapsing onto the header's line. fn clocking(&self, c: &ClockingDecl) -> Doc { let mut head = String::from(if c.is_default { "default clocking" } else { "clocking" }); if let Some(n) = &c.name { head.push(' '); head.push_str(&n.text); } let mut docs = vec![text(head)]; // `default clocking cb;` selects an existing block: no event, no body. let Some(event) = &c.event else { docs.push(text(";")); return concat(docs); }; docs.push(text(" ")); docs.push(self.sens_list(event)); docs.push(text(";")); let mut body = Vec::new(); for item in &c.items { body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); body.extend(self.leading_comments(&item.meta)); body.push(concat(vec![self.clocking_item(&item.kind), text(";")])); body.extend(self.trailing(&item.meta)); } body.extend(self.dangling(&c.dangling)); docs.push(indent(body)); if c.has_end { docs.push(Doc::HardLine); docs.push(Self::closing("endclocking", &c.end_label)); } concat(docs) } fn clocking_item(&self, kind: &ClockingItemKind) -> Doc { match kind { ClockingItemKind::Default { input, output } => { let mut s = String::from("default"); if let Some(skew) = input { s.push_str(" input "); s.push_str(skew); } if let Some(skew) = output { s.push_str(" output "); s.push_str(skew); } text(s) } ClockingItemKind::Signals { dir, skew, names } => { let mut s = dir.clone(); if let Some(skew) = skew { s.push(' '); s.push_str(skew); } s.push(' '); s.push_str(&join_names(names)); text(s) } } } /// `export "DPI-C" function f;` / `export pkg::*;` — one line either way; /// no list here is long enough to be worth a breakable group. fn export(e: &ExportDecl) -> Doc { match e { ExportDecl::Dpi(d) => { let mut head = format!("export {} ", d.spec); if let Some(c) = &d.c_identifier { head.push_str(&c.text); head.push_str(" = "); } text(format!("{head}{} {};", d.kw, d.name.text)) } ExportDecl::Package(paths) => text(format!("export {};", join_paths(paths))), } } /// `let max(a, b) = (a > b) ? a : b;` (IEEE 1800 §11.12) — a name, an /// optional port list laid out like a function's, and one expression. fn let_decl(&self, l: &LetDecl) -> Doc { let mut docs = vec![text(format!("let {}", l.name))]; if l.has_parens { docs.push(self.tf_args(&l.ports)); } docs.push(text(" =")); docs.push(self.assign_rhs(self.expr(&l.value))); concat(vec![group(docs), text(";")]) } fn function(&self, f: &FunctionDecl) -> Doc { let mut header = Vec::new(); if let Some(d) = &f.dpi { header.push(text(dpi_import_prefix(d))); } for q in &f.prefix { header.push(text(format!("{q} "))); } header.push(text("function ")); for q in &f.qualifiers { header.push(text(format!("{q} "))); } if let Some(ret) = &f.ret { if let Some(t) = self.data_type(ret) { header.push(t); header.push(text(" ")); } } if let Some(scope) = &f.scope { header.push(text(format!("{scope}::"))); } header.push(text(f.name.clone())); if f.has_parens { header.push(self.tf_args(&f.args)); } header.push(text(";")); // A prototype (`extern`/`pure virtual`) is the header and nothing // else: no body, no `endfunction`. if f.is_prototype { return concat(header); } let mut body = Vec::new(); if !f.stmts.is_empty() { body.push(Doc::HardLine); body.extend(self.stmt_seq(&f.stmts)); } body.extend(self.dangling(&f.dangling)); concat(vec![ concat(header), indent(body), Doc::HardLine, Self::closing("endfunction", &f.end_label), text(if f.end_semi { ";" } else { "" }), ]) } fn task(&self, t: &TaskDecl) -> Doc { let mut header = Vec::new(); if let Some(d) = &t.dpi { header.push(text(dpi_import_prefix(d))); } for q in &t.prefix { header.push(text(format!("{q} "))); } header.push(text("task ")); for q in &t.qualifiers { header.push(text(format!("{q} "))); } if let Some(scope) = &t.scope { header.push(text(format!("{scope}::"))); } header.push(text(t.name.clone())); if t.has_parens { header.push(self.tf_args(&t.args)); } header.push(text(";")); if t.is_prototype { return concat(header); } let mut body = Vec::new(); if !t.stmts.is_empty() { body.push(Doc::HardLine); body.extend(self.stmt_seq(&t.stmts)); } body.extend(self.dangling(&t.dangling)); concat(vec![ concat(header), indent(body), Doc::HardLine, Self::closing("endtask", &t.end_label), text(if t.end_semi { ";" } else { "" }), ]) } // ------------------------------------------------------------------ // 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 { self.stmt_as_body_from(prefix, s, 0) } /// The same, skipping the body's first `skip` leading comments because /// `prefix` already printed them inside its parentheses. See /// [`Fmt::header_parens`]. fn stmt_as_body_from(&self, prefix: Doc, s: &Stmt, skip: usize) -> Doc { match &s.kind { StmtKind::Block { label, stmts, dangling, end_label, .. } => { let mut docs = vec![prefix, text(" ")]; docs.extend(self.leading_from(&s.meta, skip)); 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_from(&s.meta, skip)); let control_doc = self.timing_control(control); docs.push(self.stmt_as_body(control_doc, inner)); docs.extend(self.trailing(&s.meta)); concat(docs) } // The same three parts `stmt` prints, with the skip applied. _ => { let mut body = self.leading_from(&s.meta, skip); body.push(self.stmt_kind(&s.kind)); body.extend(self.trailing(&s.meta)); group(vec![prefix, indent(vec![Doc::Line, concat(body)])]) } } } fn block_doc( &self, label: &Option, stmts: &[Stmt], dangling: &[Comment], end_label: &Option, ) -> Doc { let mut docs = vec![match label { Some(l) => text(format!("begin : {l}")), None => text("begin"), }]; let mut body = Vec::new(); if !stmts.is_empty() { body.push(Doc::HardLine); body.extend(self.stmt_seq(stmts)); } body.extend(self.dangling(dangling)); docs.push(indent(body)); docs.push(Doc::HardLine); docs.push(Self::closing("end", end_label)); concat(docs) } fn timing_control(&self, tc: &TimingControl) -> Doc { match tc { TimingControl::Delay(e) => concat(vec![text("#"), self.expr(e)]), TimingControl::Event(sens) => self.sens_list(sens), } } fn sens_list(&self, sens: &SensList) -> Doc { match sens { // Written without parens, printed without parens: `@ev`, // `@a.b` — inventing a `( ... )` changes the token stream. SensList::Bare(e) => concat(vec![text("@"), self.expr(e)]), SensList::Star { before, after } => { if before.is_empty() && after.is_empty() { return text("@(*)"); } // Comments written inside the parens stay inside them, on the // side of the `*` they were written on. let mut inner = Vec::new(); if before.is_empty() { // `(*` directly followed by anything but `)` lexes as an // attribute instance, so keep the `*` off the paren. inner.push(text(" ")); } for c in before { inner.push(self.comment(c)); inner.push(if is_line_comment(&c.text) { Doc::HardLine } else { text(" ") }); } inner.push(text("*")); for c in after { inner.push(text(" ")); inner.push(self.comment(c)); if is_line_comment(&c.text) { inner.push(Doc::HardLine); } } concat(vec![text("@("), indent(inner), text(")")]) } SensList::List(items) => { // Each separator is printed as it was written: `,` and `or` // mean the same thing but are different tokens, and rewriting // one as the other is a token change the safety net rejects. let mut parts: Vec = 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, else_comments, els } => { self.if_stmt(qualifier, cond, then, else_comments, els) } StmtKind::Case { qualifier, kw, expr, inside, items, dangling } => { let mut head = String::new(); if let Some(q) = qualifier { head.push_str(q); head.push(' '); } head.push_str(kw); head.push(' '); let (parens, taken) = match items.first() { Some(first) => self.header_parens(expr, &first.meta), None => (self.parens(expr), 0), }; let mut docs = vec![text(head), parens]; if *inside { docs.push(text(" inside")); } docs.push(self.case_body(items, dangling, taken)); concat(docs) } // `randcase` is a `case` body with weights for labels and no // selector, so it shares the body layout. StmtKind::RandCase { items, dangling } => { concat(vec![text("randcase"), self.case_body(items, dangling, 0)]) } StmtKind::For { init, cond, step, body } => { let mut header = vec![text("for (")]; let init_parts: Vec = 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 = 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 } => { let (parens, taken) = self.header_parens(cond, &body.meta); self.stmt_as_body_from(concat(vec![text("while "), parens]), body, taken) } 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 } => { let (parens, taken) = self.header_parens(count, &body.meta); self.stmt_as_body_from(concat(vec![text("repeat "), parens]), body, taken) } StmtKind::Forever { body } => self.stmt_as_body(text("forever"), body), StmtKind::Foreach { target, vars, body } => { let head = concat(vec![ text("foreach ("), self.expr(target), text(format!("[{}])", join_names(vars))), ]); self.stmt_as_body(head, body) } StmtKind::Assign { lhs, op, op_comments, rhs_comments, timing, rhs } => { let mut docs = vec![self.expr(lhs)]; // Comments written before the operator print before it, each // kept on its own side (`x[6:0] /* opcode */ = v;`). if self.inline_comments(op_comments, &mut docs) { docs.push(Doc::HardLine); docs.push(text(op.clone())); } else { docs.push(text(format!(" {op}"))); } let mut rhs_docs = Vec::new(); if let Some(tc) = timing { rhs_docs.push(self.timing_control(tc)); rhs_docs.push(text(" ")); } rhs_docs.push(self.expr(rhs)); if rhs_comments.is_empty() { docs.push(self.assign_rhs(concat(rhs_docs))); } else { // As in a continuous assignment: the comments stay on the // operator's line, and a line comment pushes the value // onto the next one. let mut inner = Vec::new(); let ends_line = self.inline_comments(rhs_comments, &mut inner); inner.push(if ends_line { Doc::HardLine } else { text(" ") }); inner.push(concat(rhs_docs)); docs.push(indent(inner)); } concat(vec![group(docs), text(";")]) } StmtKind::ForceRelease { kw, lhs, rhs } => { let mut docs = vec![text(format!("{kw} ")), self.expr(lhs)]; if let Some(r) = rhs { docs.push(text(" = ")); docs.push(self.expr(r)); } docs.push(text(";")); concat(docs) } StmtKind::Timing { control, stmt } => { let control_doc = self.timing_control(control); match stmt { Some(s) => self.stmt_as_body(control_doc, s), None => concat(vec![control_doc, text(";")]), } } StmtKind::Wait { cond, stmt } => match stmt { Some(s) => { let (parens, taken) = self.header_parens(cond, &s.meta); self.stmt_as_body_from(concat(vec![text("wait "), parens]), s, taken) } None => concat(vec![text("wait "), self.parens(cond), text(";")]), }, StmtKind::ExprStmt(e) => concat(vec![self.expr(e), text(";")]), StmtKind::EventTrigger(e) => concat(vec![text("-> "), self.expr(e), text(";")]), StmtKind::VarDecl(d) => concat(vec![self.data_decl(d), text(";")]), StmtKind::ParamDecl(d) => concat(vec![self.param_decl(d, None), text(";")]), StmtKind::PortDecl(d) => concat(vec![self.port_decl(d), text(";")]), StmtKind::Return(e) => match e { Some(e) => concat(vec![text("return "), self.expr(e), text(";")]), None => text("return;"), }, StmtKind::Break => text("break;"), StmtKind::Continue => text("continue;"), StmtKind::Disable(name) => text(format!("disable {name};")), StmtKind::WaitFork => text("wait fork;"), StmtKind::Import(paths) => text(format!("import {};", join_paths(paths))), // A statement label prints tight against its `:`, the way a case // label does: `check_decode: assert (...)`. StmtKind::Labeled { name, stmt, .. } => { concat(vec![text(format!("{name}: ")), self.stmt(stmt)]) } 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), // A concurrent assertion: verbatim source, like its item twin. StmtKind::Verbatim(raw) => self.raw_text(raw), 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, cond: &Expr, then: &Stmt, else_comments: &[Comment], els: &Option>, ) -> Doc { let mut head = String::new(); if let Some(q) = qualifier { head.push_str(q); head.push(' '); } head.push_str("if "); let (parens, taken) = self.header_parens(cond, &then.meta); let prefix = concat(vec![text(head), parens]); // A line comment trailing the then-branch runs to end of line, so a // cuddled `else` would be swallowed into its text. let then_is_block = matches!(then.kind, StmtKind::Block { .. }) && !trailing_ends_line(&then.meta); let mut docs = vec![self.stmt_as_body_from(prefix, then, taken)]; if let Some(els) = els { // A comment written before `else` prints before it, each on its // own line: it is where the source put it, and after the keyword // it would have crossed a token. if !else_comments.is_empty() { docs.push(Doc::HardLine); for c in else_comments { docs.push(self.comment(c)); docs.push(Doc::HardLine); } docs.push(text("else")); } else 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, else_comments: ecm, 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, ecm, 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], item: TextRange) -> Doc { if labels.is_empty() { return text(if self.default_has_colon(item) { "default:" } else { "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 = 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 { // `default;` — the colon IEEE 1800 §12.5 makes optional, with a null // body. The `;` closes the keyword rather than standing as a body of // its own, so it hugs instead of going through `stmt_as_body`. if item.labels.is_empty() && matches!(item.stmt.kind, StmtKind::Null) && is_bare(&item.stmt.meta) && !self.default_has_colon(item.span) { return text("default;"); } self.stmt_as_body(self.case_labels(&item.labels, item.span), &item.stmt) } /// The items of a `case`/`randcase` body. `skip` is the number of leading /// comments of the *first* item the `case (...)` header already printed /// inside its parentheses (see [`Fmt::header_parens`]). fn case_body(&self, items: &[CaseItem], dangling: &[Comment], skip: usize) -> Doc { let mut body = Vec::new(); for (i, item) in items.iter().enumerate() { body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); body.extend(self.leading_from(&item.meta, if i == 0 { skip } else { 0 })); body.push(self.case_item(item)); body.extend(self.trailing(&item.meta)); } body.extend(self.dangling(dangling)); concat(vec![indent(body), Doc::HardLine, text("endcase")]) } // ------------------------------------------------------------------ // Expressions // ------------------------------------------------------------------ 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, } } 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, comments } => { if comments.is_empty() { return concat(vec![self.expr(callee), self.expr_list("(", args, ")")]); } // 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); } 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 } => { concat(vec![self.expr(base), text("["), self.expr_compact(index), text("]")]) } ExprKind::Range { base, op, msb, lsb } => concat(vec![ self.expr(base), text("["), self.expr_compact(msb), text(op.clone()), self.expr_compact(lsb), text("]"), ]), ExprKind::Member { base, name } => { concat(vec![self.expr(base), text(format!(".{name}"))]) } ExprKind::Scope { base, name } => { concat(vec![self.expr(base), text(format!("::{name}"))]) } // Written tight, like the `::` it almost always precedes. ExprKind::Parameterized { base, params } => { concat(vec![self.expr(base), self.raw_inline(params)]) } ExprKind::Concat(items) => self.expr_list("{", items, "}"), ExprKind::Repl { count, inner } => concat(vec![ text("{"), self.expr(count), self.expr_list("{", inner, "}"), text("}"), ]), // `{<<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) } ExprKind::Cast { ty, expr } => { concat(vec![self.expr(ty), text("'("), self.expr(expr), text(")")]) } 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 } => concat(vec![self.expr(expr), text(op.clone())]), ExprKind::With { base, arg, comments } => { concat(vec![self.with_head(base, comments), self.expr(arg)]) } ExprKind::WithConstraint { base, block, comments } => { concat(vec![self.with_head(base, comments), self.with_block(block)]) } ExprKind::Inside { lhs, ranges } => { concat(vec![self.expr(lhs), text(" inside "), self.expr_list("{", ranges, "}")]) } ExprKind::InsideMacro { lhs, set } => { concat(vec![self.expr(lhs), text(" inside "), 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, close_comments, .. } => match &value.kind { ExprKind::Empty(comments) => { let mut docs = vec![text(format!(".{name}("))]; let mut ends_line = false; for cm in comments { if ends_line { docs.push(Doc::HardLine); } docs.push(self.comment(cm)); ends_line = is_line_comment(&cm.text); } if ends_line { docs.push(Doc::HardLine); } docs.push(text(")")); concat(docs) } _ => { let mut inner = vec![Doc::SoftLine, self.expr(value)]; let ends_line = self.inline_comments(close_comments, &mut inner); let close = if ends_line { Doc::HardLine } else { Doc::SoftLine }; concat(vec![ text(format!(".{name}(")), group(vec![indent(inner), close]), text(")"), ]) } }, ExprKind::ValueRange { lo, hi } => { concat(vec![text("["), self.expr(lo), text(":"), self.expr(hi), text("]")]) } ExprKind::Type(ty) => self.data_type(ty).unwrap_or_else(|| text("")), ExprKind::MinTypMax { min, typ, max } => { concat(vec![self.expr(min), text(":"), self.expr(typ), text(":"), self.expr(max)]) } } } /// A `? :` with comments written inside it. Each comment stays between the /// two tokens it was written between, and a line comment forces the break /// that follows it, so the layout can never fold a comment over the `?`, /// the `:` or an operand. fn ternary_with_comments( &self, cond: &Expr, then: &Expr, els: &Expr, comments: &TernaryComments, ) -> Doc { let mut head = vec![self.expr(cond)]; let hard = self.inline_comments(&comments.before_question, &mut head); let mut inner = vec![if hard { Doc::HardLine } else { Doc::Line }]; inner.push(text("?")); let hard = self.inline_comments(&comments.after_question, &mut inner); inner.push(if hard { Doc::HardLine } else { text(" ") }); inner.push(self.expr(then)); let hard = self.inline_comments(&comments.before_colon, &mut inner); inner.push(if hard { Doc::HardLine } else { Doc::Line }); inner.push(text(":")); let hard = self.inline_comments(&comments.after_colon, &mut inner); inner.push(if hard { Doc::HardLine } else { text(" ") }); inner.push(self.expr(els)); head.push(indent(inner)); group(head) } /// Flatten a left-nested chain of same-precedence binary operators so /// `a + b + c` breaks as one unit instead of stair-stepping. An operator /// carrying comments (written after the operand before it) starts its own /// line, so the comment stays last on the line it was written on. fn binary_chain(&self, e: &Expr) -> Doc { let ExprKind::Binary { op, .. } = &e.kind else { unreachable!() }; let prec = Self::binary_prec(op); let mut operands: Vec<&Expr> = Vec::new(); let mut ops: Vec> = 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 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::>().join(", ") } /// The same for a list of `pkg::item` import paths. fn join_paths(paths: &[ImportPath]) -> String { paths.iter().map(ImportPath::text).collect::>().join(", ") } /// `import "DPI-C" [context|pure ][c_name = ]` — the linkage prefix a DPI /// import writes in front of the function or task prototype it declares. fn dpi_import_prefix(d: &DpiImport) -> String { let mut s = format!("import {} ", d.spec); if let Some(p) = &d.property { s.push_str(p); s.push(' '); } if let Some(c) = &d.c_identifier { s.push_str(&c.text); s.push_str(" = "); } s } /// 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("//") } /// True when a node carries no trivia at all, so printing it cannot move a /// comment anywhere. fn is_bare(meta: &Meta) -> bool { meta.leading.is_empty() && meta.trailing.is_none() && meta.before_sep.is_empty() && meta.attrs.is_empty() } /// True when a node's trailing comments end in a line comment, so anything /// printed after them on the same line would be swallowed into the comment's /// text. `trailing` prints `before_sep` first and `trailing` last. fn trailing_ends_line(meta: &Meta) -> bool { match &meta.trailing { Some(tr) => is_line_comment(&tr.text), None => meta.before_sep.last().is_some_and(|c| is_line_comment(&c.text)), } } /// Offset of the first byte at or after `from` that is neither whitespace nor /// part of a comment, or `None` if the text ends first. /// /// Used to ask what a node is followed by in the source — a `)` that closes /// the header it sits in, the optional `:` of a `default` case label — when /// the AST does not record it. fn skip_trivia(src: &str, from: usize) -> Option { let bytes = src.as_bytes(); let mut i = from; while i < bytes.len() { match bytes[i] { b'/' if bytes.get(i + 1) == Some(&b'/') => { i += 2; while i < bytes.len() && bytes[i] != b'\n' { i += 1; } } b'/' if bytes.get(i + 1) == Some(&b'*') => { i += 2; while i < bytes.len() && !(bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/')) { i += 1; } i = (i + 2).min(bytes.len()); } c if c.is_ascii_whitespace() => i += 1, _ => return Some(i), } } None }