diff --git a/TODO.md b/TODO.md index 71d350f..96939df 100644 --- a/TODO.md +++ b/TODO.md @@ -3004,7 +3004,7 @@ module names, `README.md`'s architecture section updated. Runs AFTER §27 (every lane touches its files). - [ ] Lane A `vlog_parser` — parser/ and ast/ module maps; tests moved; counts pinned; byte-identity proven -- [ ] Lane B `vlog_formatter` — format/ module map; counts; byte-identity +- [x] Lane B `vlog_formatter` — format/ module map; counts; byte-identity - [ ] Lane C `lucisv_server` — server/ and completion/ module maps; tests out of server.rs first; counts; e2e unchanged; vsix smoke - [ ] Lane D `vlog_semantic` + `vlog_refactor` diff --git a/crates/vlog_formatter/src/format.rs b/crates/vlog_formatter/src/format.rs deleted file mode 100644 index 570c5db..0000000 --- a/crates/vlog_formatter/src/format.rs +++ /dev/null @@ -1,5443 +0,0 @@ -//! 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. -/// The pieces of a `begin … end` block a printer needs, gathered so the -/// two spellings (a statement, and a body cuddled onto a header) pass one -/// argument instead of six. -struct BlockDoc<'a> { - label_comments: &'a LabelComments, - label: &'a Option, - stmts: &'a [Stmt], - dangling: &'a [Comment], - end_label_comments: &'a LabelComments, - end_label: &'a Option, -} - -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} : {}", named(l))), - None => text(kw), - } - } - - /// The same, with the comments the source wrote in the label's two gaps - /// (`endgroup /*a*/ : /*b*/ cg`). The common case — no comment — is - /// [`Fmt::closing`] verbatim. - fn closing_labeled(&self, kw: &str, label: &Option, c: &LabelComments) -> Doc { - if c.is_empty() { - return Self::closing(kw, label); - } - let mut docs = vec![text(kw.to_string())]; - self.label_tail(label, c, &mut docs); - concat(docs) - } - - /// ` : name`, with the comments written in its two gaps. A no-op when no - /// label was written. - fn label_tail(&self, label: &Option, c: &LabelComments, docs: &mut Vec) { - let Some(l) = label else { - // A comment before a `:` that was never written belongs to - // whatever follows, and `gap_before` never took it. - debug_assert!(c.is_empty()); - return; - }; - self.slot_comments(&c.before_colon, docs); - docs.push(text(if c.before_colon.is_empty() { " :" } else { ":" })); - if c.after_colon.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&c.after_colon, docs); - } - docs.push(text(named(l))); - } - - // ------------------------------------------------------------------ - // 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(" ")); - } - } - - /// The `pkg::cls::` written in front of an out-of-body definition's name, - /// one segment at a time so a comment beside a `::` prints where it was - /// written — and so an escaped segment keeps the space that terminates - /// it, which `named` supplies. - fn scope_prefix(&self, scope: &[ScopeSeg], docs: &mut Vec) { - for seg in scope { - docs.push(text(named(&seg.name.text))); - self.slot_comments(&seg.before_sep, docs); - docs.push(text("::")); - self.slot_comments(&seg.after_sep, docs); - } - } - - /// The `; ` between two sections of a `for` header, carrying whatever the - /// source wrote in the two gaps around it. - fn for_semi(&self, before: &[Comment], after: &[Comment], docs: &mut Vec) { - self.slot_comments(before, docs); - docs.push(text(";")); - if after.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(after, docs); - } - } - - /// `for` plus its `(`, with the gap between them. - fn for_open(&self, comments: &ForComments, docs: &mut Vec) { - docs.push(text("for")); - if comments.after_kw.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&comments.after_kw, docs); - } - docs.push(text("(")); - self.slot_comments(&comments.after_open, docs); - } - - /// The `lhs op rhs` of a `for` header's initialiser or step. - fn simple_assign(&self, a: &SimpleAssign, docs: &mut Vec) { - docs.push(self.expr(&a.lhs)); - self.slot_comments(&a.op_comments.before, docs); - docs.push(text(if a.op_comments.before.is_empty() { - format!(" {}", a.op) - } else { - a.op.clone() - })); - if a.op_comments.after.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&a.op_comments.after, docs); - } - docs.push(self.expr(&a.rhs)); - } - - /// `= value`, with the comments written on either side of the `=`. - fn eq_default(&self, comments: &BinaryComments, value: Doc, docs: &mut Vec) { - self.slot_comments(&comments.before, docs); - docs.push(text(if comments.before.is_empty() { " =" } else { "=" })); - if comments.after.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&comments.after, docs); - } - docs.push(value); - } - - /// A keyword and whatever the source wrote between it and what follows — - /// a space when that is nothing. - fn word_then(&self, word: &str, comments: &[Comment], docs: &mut Vec) { - docs.push(text(word.to_string())); - if comments.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(comments, docs); - } - } - - /// A run of qualifier keywords, each followed by the space or the comment - /// the source wrote after it (`local /*c*/ static `). Always ends in a - /// separator, so the caller writes what follows without one of its own. - fn qualifier_run(&self, run: &[Qualifier], docs: &mut Vec) { - for q in run { - docs.push(text(q.text.clone())); - if q.after.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&q.after, docs); - } - } - } - - /// One named comment slot between two tokens the caller emits either side - /// of it, spaced off both — and a no-op when the slot is empty, so a - /// construct with no comment in it is laid out exactly as it was before - /// the slot existed. - /// - /// This is what every slot of [`SegmentComments`] is printed with, and it - /// is why the empty case of a `.`, a `::` or a `[` costs nothing. - fn slot_comments(&self, comments: &[Comment], docs: &mut Vec) { - if comments.is_empty() { - return; - } - self.inline_comments_spaced(comments, docs); - } - - /// `[ … ]` with the comments written in a segment's or a dimension's own - /// slots printed back between the same two tokens the source wrote them - /// between. `rest` is the `: lsb` half of a range, absent for an index. - /// - /// The opener's own slot (`base /*c*/ [`) belongs to whoever emitted the - /// base, so it is not printed here. - fn bracket_slots( - &self, - comments: &SegmentComments, - first: Doc, - rest: Option<(&str, Doc)>, - ) -> Doc { - let mut docs = vec![text("[")]; - self.slot_comments(&comments.after_open, &mut docs); - docs.push(first); - if let Some((op, second)) = rest { - self.slot_comments(&comments.before_op, &mut docs); - docs.push(text(op.to_string())); - self.slot_comments(&comments.after_op, &mut docs); - docs.push(second); - } - self.slot_comments(&comments.before_close, &mut docs); - docs.push(text("]")); - concat(docs) - } - - 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 close_needs_hardline = self.list_rows(items, dangling, &mut inner) || force_break; - // 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) - } - - /// The elements of a list, their separators and the comments written - /// around each one, appended to `inner`. Returns whether what follows the - /// last element must start on a new line — a trailing comment, or a - /// comment written where the separator would have been, cannot share it. - /// - /// Split out of [`Fmt::delimited_dangling`] so a fragment's enum members - /// go through the very layout their enum body would have given them, at - /// indent 0 and with no braces around them. - fn list_rows(&self, items: Vec, dangling: &[Comment], inner: &mut Vec) -> bool { - let last = items.len().saturating_sub(1); - let mut close_needs_hardline = false; - 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, 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; - } - close_needs_hardline - } - - /// 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() - // A comment after the keyword makes this row a width no other row - // shares, so it never joins an alignment group. - || !d.after_kw.is_empty() - { - 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(")")]) - } - - /// `( cond )` with the comments a header kept in its own slots. The - /// `after_kw` half is written by the caller, which owns the keyword. - fn header_slots(&self, cond: &Expr, comments: &HeaderComments) -> Doc { - if comments.after_open.is_empty() && comments.before_close.is_empty() { - return self.parens(cond); - } - let before: Vec<&Comment> = comments.after_open.iter().collect(); - let after: Vec<&Comment> = comments.before_close.iter().collect(); - self.paren_comments(cond, &before, &after) - } - - /// `( 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(); - // The last item that actually emitted something, which is what a - // glued null item glues to. - let mut prev: Option<&Item> = None; - 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() && !prev.is_some_and(|p| self.glued_null_item(p, item)) { - docs.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); - } - docs.extend(item_docs); - prev = Some(item); - } - docs - } - - /// True when `item` is a null item (`;`) the source wrote on the line the - /// item before it ended on, which is how it is printed back: - /// `endgenerate;`, `end;`, `endmodule;`, `;;`. - /// - /// The question is asked of the source rather than of the AST because it - /// is a layout fact about the gap between two siblings, and this is the - /// one place that gap is laid out — the same reason `eq_offset` and - /// `default_has_colon` read `src` here. A null item that begins a body has - /// no sibling to glue to and prints on its own line. - /// - /// Anything that gives the `;` docs of its own — a leading comment, an - /// attribute, a blank line, a format-off fence opening on it — takes the - /// own-line path instead, so the glue only ever appends a bare `;`. Note - /// that a `//` comment cannot stand in a newline-free gap: it would - /// swallow the `;` that follows it. The only comment that fits is a - /// one-line block comment, which prints inline before the `;`, in the - /// order it was written. - fn glued_null_item(&self, prev: &Item, item: &Item) -> bool { - if !matches!(item.kind, ItemKind::Empty) { - return false; - } - if item.meta.blank_before || !item.meta.leading.is_empty() || !item.meta.attrs.is_empty() { - return false; - } - if self.is_verbatim(item.span) || self.opens_at(item.span.start as usize).is_some() { - return false; - } - self.src - .get(prev.span.end as usize..item.span.start as usize) - .is_some_and(|gap| !gap.contains('\n')) - } - - 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 = match &f.fragment { - Some(fragment) => self.fragment(fragment), - None => 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) - } - - /// A whole file that is the middle of some body, printed at indent 0 - /// through the very printers that body uses — a statement sequence, an - /// enum's member list, a covergroup's items. Nothing here is a layout of - /// its own: the fragment is the piece of code it was written as, minus the - /// construct around it, and it must come back the way that construct would - /// have printed it. See `docs/features/fragment-mode/README.md`. - fn fragment(&self, fragment: &Fragment) -> Vec { - match fragment { - Fragment::Statements(stmts) => self.stmt_seq(stmts), - Fragment::EnumMembers { members, directives } => { - let items = self.list_entries(self.enum_member_items(members), directives); - let mut docs = Vec::new(); - // The file's own dangling comments are `SourceFile::dangling` - // and `Fmt::file` prints them, so the list has none of its own. - self.list_rows(items, &[], &mut docs); - docs - } - Fragment::CoverItems(items) => self.cover_items(items), - } - } - - 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, before_name, name, before_semi, .. } => { - Some(self.package_head(kw, before_name, name, before_semi)) - } - _ => None, - } - } - - /// A split item's closing keyword, laid out. - fn tail_doc(&self, kind: &ItemKind) -> Option { - match kind { - ItemKind::Module(m) => { - Some(self.closing_labeled(m.end_kw(), &m.end_label, &m.end_label_comments)) - } - ItemKind::Package { end_label, end_label_comments, .. } => { - Some(self.closing_labeled("endpackage", end_label, end_label_comments)) - } - _ => 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, - before_name, - name, - before_semi, - items, - dangling, - end_label, - end_label_comments, - .. - } => { - let mut docs = vec![self.package_head(kw, before_name, name, before_semi)]; - 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_labeled("endpackage", end_label, end_label_comments)); - 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::Constraint(c) => self.constraint(c), - ItemKind::Covergroup(c) => self.covergroup(c), - ItemKind::PropSeqDecl(d) => self.prop_seq_decl(d), - ItemKind::Assertion(a) => self.assertion(a), - ItemKind::DefaultDisable(d) => self.default_disable(d), - ItemKind::Verbatim(raw) => self.raw_text(raw), - // A null item is its `;`. Whether it keeps the previous item's - // line or takes one of its own is `item_seq`'s call. - ItemKind::Empty => text(";"), - 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) - } - // `alias a = b = c;` — one line, one space around every `=`, the - // spacing every other assignment-shaped item already uses. - ItemKind::Alias(nets) => { - let mut docs = vec![text("alias ")]; - docs.extend(join(nets.iter().map(|n| self.expr(n)).collect(), text(" = "))); - docs.push(text(";")); - concat(docs) - } - } - } - - // ------------------------------------------------------------------ - // Module - // ------------------------------------------------------------------ - - /// `package p;` — the two comment slots a package header owns. - fn package_head( - &self, - kw: &str, - before_name: &[Comment], - name: &str, - before_semi: &[Comment], - ) -> Doc { - let mut docs = vec![text(kw.to_string())]; - if before_name.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(before_name, &mut docs); - } - docs.push(text(named(name))); - docs.push(self.semi(before_semi)); - concat(docs) - } - - 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_labeled(m.end_kw(), &m.end_label, &m.end_label_comments)); - 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(m.kw.clone())]; - if m.before_name.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&m.before_name, &mut docs); - } - docs.push(text(named(&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 { " #" })); - self.slot_comments(&m.param_after_hash, &mut docs); - 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(self.semi(&m.before_semi)), - 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, name_doc(&p.name)).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(self.semi(&m.before_semi)); - } - } - concat(docs) - } - - fn param_port(&self, p: &ParamPort) -> Doc { - let mut docs = Vec::new(); - if let Some(kw) = &p.kw { - self.word_then(kw, &p.after_kw, &mut docs); - } else { - self.slot_comments(&p.after_kw, &mut docs); - } - if p.is_type { - docs.push(text("type ")); - } - match self.data_type(&p.ty) { - Some(t) => { - docs.push(t); - if p.before_name.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&p.before_name, &mut docs); - } - } - None => self.slot_comments(&p.before_name, &mut docs), - } - docs.push(name_doc(&p.name)); - docs.extend(self.unpacked_dims(&p.unpacked)); - if let Some(d) = &p.default { - self.eq_default(&p.eq_comments, group(vec![self.expr(d)]), &mut docs); - } - 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 { - // A comment in one of the port's own gaps makes the row a width no - // other row shares, so it is one cell and joins no alignment group — - // the rule an attributed connection already follows. - if !p.after_dir.is_empty() || !p.before_name.is_empty() { - return vec![self.ansi_port_plain(p)]; - } - 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![name_doc(&p.name)]; - docs.extend(self.unpacked_dims(&p.unpacked)); - if let Some(d) = &p.default { - self.eq_default(&p.eq_comments, self.expr(d), &mut docs); - } - if prefix.is_empty() { - return vec![concat(docs)]; - } - vec![concat(prefix), concat(docs)] - } - - /// An ANSI port written out in one piece, for the rows that carry a - /// comment in one of their own gaps and so cannot be aligned. - fn ansi_port_plain(&self, p: &AnsiPort) -> Doc { - let mut docs = Vec::new(); - if let Some(dir) = &p.dir { - self.word_then(dir, &p.after_dir, &mut docs); - } - if let Some(net) = &p.net { - docs.push(text(format!("{net} "))); - } - match self.data_type(&p.ty) { - Some(t) => { - docs.push(t); - if p.before_name.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&p.before_name, &mut docs); - } - } - None => self.slot_comments(&p.before_name, &mut docs), - } - docs.push(name_doc(&p.name)); - docs.extend(self.unpacked_dims(&p.unpacked)); - if let Some(d) = &p.default { - self.eq_default(&p.eq_comments, self.expr(d), &mut docs); - } - 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(name_doc(&ty.name)); - 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() { - // A dimension that opens with a comment writes its own space. - if need_space && ty.packed[0].comments.opens_clean() { - 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 { - let c = &d.comments; - let brackets = match &d.kind { - DimKind::Range { a, b } => { - let rest = b.as_ref().map(|b| (":", self.expr_compact(b))); - self.bracket_slots(c, self.expr_compact(a), rest) - } - // `[]` and `[*]` have no operand, so the one inner slot they own - // is the gap before the `]`, which is where `parse_dims` puts - // anything written between the brackets. - DimKind::Dynamic => self.bracket_slots(c, text(""), None), - DimKind::Wildcard => self.bracket_slots(c, text("*"), None), - }; - if c.opens_clean() { - return brackets; - } - // `logic /*c*/ [3:0]` — the gap before the `[` belongs to the - // dimension, since nothing to its left has a slot for it. The space - // in front is the dimension's own: a caller that would have written - // one asks [`SegmentComments::opens_clean`] and leaves it out. - let mut docs = Vec::new(); - self.inline_comments_spaced(&c.before_open, &mut docs); - docs.push(brackets); - concat(docs) - } - - /// Compact rendering used inside `[...]` brackets: arithmetic and shift - /// operators lose their surrounding spaces (`[WIDTH-1:0]`), and no line - /// breaks are introduced. - fn expr_compact(&self, e: &Expr) -> Doc { - match &e.kind { - ExprKind::Binary { lhs, op, rhs, comments } => { - if comments.before.is_empty() && comments.after.is_empty() { - let tight = Self::binary_prec(op) >= 8; - let sep = if tight { op.clone() } else { format!(" {op} ") }; - return concat(vec![self.expr_compact(lhs), text(sep), self.expr_compact(rhs)]); - } - // A comment written next to the operator has nowhere to go in - // the tight spelling, so the operator gets its spaces back; - // a line comment pushes what follows onto the next line. - let mut docs = vec![self.expr_compact(lhs)]; - self.inline_comments_spaced(&comments.before, &mut docs); - docs.push(text(op.clone())); - self.inline_comments_spaced(&comments.after, &mut docs); - docs.push(self.expr_compact(rhs)); - concat(docs) - } - // The compact spelling has nowhere to put a comment written - // inside the `? :` or just inside the parentheses, so a shape - // that carries one falls back to the ordinary layout, which does. - ExprKind::Ternary { cond, then, els, comments } if comments.is_empty() => concat(vec![ - self.expr_compact(cond), - text(" ? "), - self.expr_compact(then), - text(" : "), - self.expr_compact(els), - ]), - ExprKind::Paren { inner, before, after } if before.is_empty() && after.is_empty() => { - concat(vec![text("("), self.expr_compact(inner), text(")")]) - } - ExprKind::Unary { op, comments, expr } if comments.is_empty() => { - concat(vec![text(op.clone()), self.expr_compact(expr)]) - } - _ => self.expr(e), - } - } - - fn unpacked_dims(&self, dims: &[Dim]) -> Vec { - let mut docs = Vec::new(); - if !dims.is_empty() { - if dims[0].comments.opens_clean() { - 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![name_doc(&d.name)]; - docs.extend(self.unpacked_dims(&d.unpacked)); - if let Some(init) = &d.init { - self.slot_comments(&d.eq_comments.before, &mut docs); - docs.push(text(if d.eq_comments.before.is_empty() { " =" } else { "=" })); - if d.eq_comments.after.is_empty() { - docs.push(group(vec![self.assign_rhs(self.expr(init))])); - } else { - self.inline_comments_spaced(&d.eq_comments.after, &mut docs); - docs.push(group(vec![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::new(); - self.word_then(&d.kw, &d.after_kw, &mut docs); - 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![name_doc(&decl.name)]; - 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(" ")); - } - self.qualifier_run(&d.qualifiers, &mut docs); - 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 { - let mut docs = Vec::new(); - self.word_then("typedef", &t.after_kw, &mut docs); - let base = match &t.kind { - TypedefKind::ForwardClass => Some(text("class")), - TypedefKind::Alias(ty) => self.data_type(ty), - TypedefKind::Enum(e) => Some(self.enum_type(e)), - TypedefKind::Struct(s) => Some(self.struct_type(s)), - }; - match base { - Some(d) => { - docs.push(d); - if t.before_name.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&t.before_name, &mut docs); - } - } - None => self.slot_comments(&t.before_name, &mut docs), - } - docs.push(name_doc(&t.name)); - docs.extend(self.unpacked_dims(&t.unpacked)); - docs.push(self.semi(&t.before_semi)); - concat(docs) - } - - /// `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")]; - let mut spaced = false; - if !e.after_kw.is_empty() { - self.inline_comments_spaced(&e.after_kw, &mut docs); - spaced = true; - } - if let Some(base) = &e.base { - if let Some(d) = self.data_type(base) { - if !spaced { - docs.push(text(" ")); - } - docs.push(d); - spaced = false; - } - } - if e.before_open.is_empty() { - if !spaced { - docs.push(text(" ")); - } - } else { - self.inline_comments_spaced(&e.before_open, &mut docs); - } - let items = self.list_entries(self.enum_member_items(&e.members), &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) - } - - /// One list entry per enum member. Shared by the `enum { ... }` body and - /// by an enum-member fragment, so the two lay a member out identically. - fn enum_member_items(&self, members: &[EnumMember]) -> Vec { - members - .iter() - .map(|m| { - let mut d = vec![name_doc(&m.name)]; - // Tight against the name: `OtbnDmem[16]` is one enum name - // range, not a name with a dimension beside it. - d.extend(m.range.iter().map(|r| self.dim(r))); - if let Some(v) = &m.value { - self.slot_comments(&m.eq_comments.before, &mut d); - d.push(text(if m.eq_comments.before.is_empty() { " =" } else { "=" })); - if m.eq_comments.after.is_empty() { - d.push(text(" ")); - } else { - self.inline_comments_spaced(&m.eq_comments.after, &mut d); - } - d.push(self.expr(v)); - } - ListItem::from_meta(&m.meta, concat(d)).with_comma(m.comma) - }) - .collect() - } - - /// `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 c = &s.header_comments; - // `union tagged packed`, in the LRM's order, each word followed by - // whatever the source wrote after it. - let mut head = Vec::new(); - self.word_then(&s.kw, &c.after_kw, &mut head); - if s.tagged { - self.word_then("tagged", &c.after_tagged, &mut head); - } - if s.packed { - self.word_then("packed", &c.after_packed, &mut head); - } - if let Some(sig) = &s.signing { - self.word_then(sig, &c.after_signing, &mut head); - } - head.push(text("{")); - 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(); - self.qualifier_run(&m.qualifiers, &mut d); - 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![concat(head), 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 { - // `y /*c*/ =` — the comments stay on the operator's left. - let mut head = vec![self.expr(&p.lhs)]; - self.slot_comments(&p.op_comments, &mut head); - head.push(text(if p.op_comments.is_empty() { " =" } else { "=" })); - if p.rhs_comments.is_empty() { - head.push(self.assign_rhs(self.expr(&p.rhs))); - return group(head); - } - 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)); - head.push(indent(inner)); - group(head) - } - - fn cont_assign(&self, a: &ContAssign) -> Doc { - // `assign /*c*/ y = x;` — the first pair's own leading comments were - // written after the keyword, and print there. - let lead = a.assigns.first().map(|p| p.meta.leading.as_slice()).unwrap_or(&[]); - let mut docs = vec![text("assign")]; - if lead.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(lead, &mut docs); - } - if let Some(s) = &a.strength { - docs.push(text(format!("{} ", drive_strength(s)))); - } - if let Some(delay) = &a.delay { - docs.push(text("#")); - docs.push(self.expr(delay)); - docs.push(text(" ")); - } - let items: Vec = a - .assigns - .iter() - .enumerate() - .map(|(i, p)| { - // The first pair's leading comments are printed above, after - // the keyword; printing them twice would duplicate them. - let skip = usize::from(i == 0) * lead.len(); - let mut item = ListItem::from_meta(&p.meta, self.assign_pair(p)); - item.leading.drain(..skip.min(item.leading.len())); - item - }) - .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 { - // 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); - // One segment at a time, for the reason `scope_prefix` prints a `::` - // chain that way: `named` supplies the space an escaped segment needs - // to terminate, and a joined string could not carry it. - for (i, seg) in b.target.iter().enumerate() { - if i > 0 { - docs.push(text(".")); - } - docs.push(text(named(&seg.name))); - if let Some(index) = &seg.index { - docs.push(text("[")); - docs.push(self.expr_compact(index)); - docs.push(text("]")); - } - } - if !b.instances.is_empty() { - docs.push(text(format!(" : {}", join_names(&b.instances)))); - } - 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![name_doc(&inst.module)]; - 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() || holds_verbatim_value(params); - docs.push(text(if on_fresh_line { "#" } else { " #" })); - self.slot_comments(&inst.after_hash, &mut docs); - 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(self.semi(&inst.before_semi)); - 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![name_doc(&instance.name)]; - if !instance.dims.is_empty() { - if instance.dims[0].comments.opens_clean() { - 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) || holds_verbatim_value(list); - 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(); - } - // A comment written in one of the connection's own gaps makes the row - // a width no other row shares, so it never joins an alignment group. - if !c.after_dot.is_empty() || !c.before_open.is_empty() || !c.after_open.is_empty() { - return plain(); - } - let Some(e) = &c.expr else { return plain() }; - // A verbatim conditional region is many lines of bytes; a row that - // wide shares its width with nothing, and the `)` after it has a line - // break of its own to keep (`Fmt::verbatim_value_breaks`). - if matches!(e.kind, ExprKind::Empty(_) | ExprKind::Verbatim(_)) { - 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!(".{}", named(&c.name))), - concat(vec![text("("), group(vec![indent(inner), close]), text(")")]), - ] - } - - /// True when a connection's value is a **verbatim conditional region** - /// the source ended a line after — which it always does when the region - /// ends on a `` `endif ``. - /// - /// A line-oriented directive runs to the end of its line (`lexer.rs`'s - /// `is_line_directive`), so a `)` printed after one on the same line is - /// swallowed into the directive's own token — a rewrite the safety net - /// refuses. The break is read back from `src` rather than stored, for the - /// reason [`Fmt::glued_null_item`] gives, and is a fixed point by - /// construction: the break printed here reads back as the same break. - fn verbatim_value_breaks(&self, c: &Connection) -> bool { - let Some(Expr { kind: ExprKind::Verbatim(raw), .. }) = &c.expr else { return false }; - self.src - .get(raw.span.end as usize..c.span.end as usize) - .is_some_and(|gap| gap.contains('\n')) - } - - 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 == "*" { - if c.after_dot.is_empty() { - return text(".*"); - } - let mut docs = vec![text(".")]; - self.slot_comments(&c.after_dot, &mut docs); - docs.push(text("*")); - return concat(docs); - } - if c.name.is_empty() { - // Positional parameter value. - return match &c.expr { - Some(e) => self.expr(e), - None => text(""), - }; - } - // `.` then the name, with whatever the source wrote between them. - let head = |f: &Self| { - let mut docs = vec![text(".")]; - f.slot_comments(&c.after_dot, &mut docs); - docs.push(text(named(&c.name))); - docs - }; - // …and the `(` that follows the name, with its two gaps. - let open = |f: &Self, docs: &mut Vec| { - f.slot_comments(&c.before_open, docs); - docs.push(text("(")); - f.slot_comments(&c.after_open, docs); - }; - match &c.expr { - None => concat(head(self)), - Some(Expr { kind: ExprKind::Empty(comments), .. }) => { - let mut docs = head(self); - open(self, &mut docs); - 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 broke = ends_line || self.verbatim_value_breaks(c); - let close = if broke { Doc::HardLine } else { Doc::SoftLine }; - let mut docs = head(self); - open(self, &mut docs); - docs.push(group(vec![indent(inner), close])); - docs.push(text(")")); - concat(docs) - } - } - } - - fn gate_instantiation(&self, g: &GateInstantiation) -> Doc { - let mut docs = vec![text(g.gate.clone())]; - if let Some(s) = &g.strength { - docs.push(text(format!(" {}", drive_strength(s)))); - } - if let [delay] = g.delay.as_slice() { - // One value prints itself, brackets and all (`#5`, `#(5)`). - docs.push(text(" #")); - docs.push(self.expr(delay)); - } else if !g.delay.is_empty() { - // `#(rise, fall[, turn-off])` — the parens are the list's own. - docs.push(text(" #(")); - for (i, d) in g.delay.iter().enumerate() { - if i > 0 { - docs.push(text(", ")); - } - docs.push(self.expr(d)); - } - docs.push(text(")")); - } - for (i, inst) in g.instances.iter().enumerate() { - docs.push(if i > 0 { text(", ") } else { text(" ") }); - if let Some(name) = &inst.name { - docs.push(name_doc(name)); - 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 { - if b.before_kw.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&b.before_kw, docs); - } - docs.push(text("begin")); - if let Some(l) = &b.label { - self.slot_comments(&b.before_colon, docs); - docs.push(text(if b.before_colon.is_empty() { " :" } else { ":" })); - if b.after_colon.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&b.after_colon, docs); - } - docs.push(text(named(l))); - } - 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_labeled("end", &b.end_label, &b.end_label_comments)); - 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::new(); - self.for_open(&g.comments, &mut header); - if g.init_genvar { - header.push(text("genvar")); - if g.after_genvar.is_empty() { - header.push(text(" ")); - } else { - self.inline_comments_spaced(&g.after_genvar, &mut header); - } - } - self.simple_assign(&g.init, &mut header); - self.for_semi(&g.comments.before_first_semi, &g.comments.after_first_semi, &mut header); - header.push(self.expr(&g.cond)); - self.for_semi(&g.comments.before_second_semi, &g.comments.after_second_semi, &mut header); - header.push(self.for_step(&g.step)); - self.slot_comments(&g.comments.before_close, &mut header); - 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.before_colon, 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) => { - let mut docs = Vec::new(); - self.simple_assign(a, &mut docs); - concat(docs) - } - ForStep::Expr(e) => self.expr(e), - } - } - - // ------------------------------------------------------------------ - // Functions and tasks - // ------------------------------------------------------------------ - - fn tf_args(&self, args: &[TfArg], dangling: &[Comment]) -> Doc { - let items: Vec = args - .iter() - .map(|a| { - let mut docs = Vec::new(); - if let Some(dir) = &a.dir { - docs.push(text(dir.clone())); - if a.after_dir.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&a.after_dir, &mut docs); - } - } - if let Some(t) = self.data_type(&a.ty) { - docs.push(t); - if a.before_name.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&a.before_name, &mut docs); - } - } else { - self.slot_comments(&a.before_name, &mut docs); - } - docs.push(name_doc(&a.name)); - docs.extend(self.unpacked_dims(&a.unpacked)); - if let Some(d) = &a.default { - self.slot_comments(&a.eq_comments.before, &mut docs); - docs.push(text(if a.eq_comments.before.is_empty() { " =" } else { "=" })); - if a.eq_comments.after.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&a.eq_comments.after, &mut docs); - } - docs.push(self.expr(d)); - } - ListItem::from_meta(&a.meta, concat(docs)) - }) - .collect(); - self.delimited_dangling("(", items, dangling, ")", 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 docs = Vec::new(); - self.qualifier_run(&c.prefix, &mut docs); - docs.push(text("class")); - // `class /*c*/ c` — and, when a lifetime was written, whatever stood - // on either side of it; both gaps land in the one slot, which prints - // between the keyword run and the name. - if c.before_name.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&c.before_name, &mut docs); - } - if let Some(lifetime) = &c.lifetime { - docs.push(text(format!("{lifetime} "))); - } - docs.push(text(named(&c.name))); - let on_fresh_line = self.bracket_comments(&c.param_comments, &mut docs, false); - if let Some(params) = &c.param_ports { - let items: Vec = params - .iter() - .map(|p| ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma)) - .collect(); - let items = self.list_entries(items, &c.param_directives); - let broken = !c.param_directives.is_empty(); - docs.push(text(if on_fresh_line { "#" } else { " #" })); - self.slot_comments(&c.param_after_hash, &mut docs); - docs.push(self.delimited_dangling("(", items, &c.param_dangling, ")", broken)); - } - if let Some(ext) = &c.extends { - docs.push(text(format!(" extends {}", named(&ext.name)))); - let fresh = self.bracket_comments(&ext.param_comments, &mut docs, false); - if let Some(params) = &ext.params { - let items: Vec = params - .iter() - .map(|p| ListItem::from_meta(&p.meta, self.connection(p)).with_comma(p.comma)) - .collect(); - let items = self.list_entries(items, &ext.param_directives); - let broken = !ext.param_directives.is_empty(); - docs.push(text(if fresh { "#" } else { " #" })); - self.slot_comments(&ext.after_hash, &mut docs); - docs.push(self.delimited("(", items, ")", broken)); - } - } - if !c.implements.is_empty() { - docs.push(text(format!(" implements {}", join_names(&c.implements)))); - } - docs.push(self.semi(&c.before_semi)); - let mut body = Vec::new(); - if !c.items.is_empty() { - body.push(Doc::HardLine); - body.extend(self.item_seq(&c.items, depth + 1)); - } - body.extend(self.dangling(&c.dangling)); - docs.push(indent(body)); - docs.push(Doc::HardLine); - docs.push(self.closing_labeled("endclass", &c.end_label, &c.end_label_comments)); - concat(docs) - } - - /// `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!("{} ", named(&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(&named(&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_labeled("endclocking", &c.end_label, &c.end_label_comments)); - } - concat(docs) - } - - /// One clocking-block item. A `= expression` binding - /// (`output tms = _tms_internal;`) prints on the item's own line: the - /// bound expression is a signal name, never long enough to be worth a - /// breakable group. - 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, signals } => { - let mut head = dir.clone(); - if let Some(skew) = skew { - head.push(' '); - head.push_str(skew); - } - head.push(' '); - let mut docs = vec![text(head)]; - for (i, sig) in signals.iter().enumerate() { - if i > 0 { - docs.push(text(", ")); - } - docs.push(name_doc(&sig.name.text)); - if let Some(value) = &sig.value { - docs.push(text(" = ")); - docs.push(self.expr(value)); - } - } - concat(docs) - } - } - } - - /// `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(&named(&c.text)); - head.push_str(" = "); - } - text(format!("{head}{} {};", d.kw, named(&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 {}", named(&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))); - } - self.qualifier_run(&f.prefix, &mut header); - header.push(text("function")); - if f.after_kw.is_empty() { - header.push(text(" ")); - } else { - self.inline_comments_spaced(&f.after_kw, &mut header); - } - self.qualifier_run(&f.qualifiers, &mut header); - let mut named_ret = false; - if let Some(ret) = &f.ret { - if let Some(t) = self.data_type(ret) { - header.push(t); - named_ret = true; - } - } - if named_ret { - if f.before_name.is_empty() { - header.push(text(" ")); - } else { - self.inline_comments_spaced(&f.before_name, &mut header); - } - } else { - self.slot_comments(&f.before_name, &mut header); - } - self.scope_prefix(&f.scope, &mut header); - header.push(name_doc(&f.name)); - if f.has_parens { - self.slot_comments(&f.before_args, &mut header); - header.push(self.tf_args(&f.args, &f.args_dangling)); - } - header.push(self.semi(&f.before_semi)); - // 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_labeled("endfunction", &f.end_label, &f.end_label_comments), - 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))); - } - self.qualifier_run(&t.prefix, &mut header); - header.push(text("task")); - if t.after_kw.is_empty() { - header.push(text(" ")); - } else { - self.inline_comments_spaced(&t.after_kw, &mut header); - } - self.qualifier_run(&t.qualifiers, &mut header); - self.slot_comments(&t.before_name, &mut header); - self.scope_prefix(&t.scope, &mut header); - header.push(name_doc(&t.name)); - if t.has_parens { - self.slot_comments(&t.before_args, &mut header); - header.push(self.tf_args(&t.args, &t.args_dangling)); - } - header.push(self.semi(&t.before_semi)); - 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_labeled("endtask", &t.end_label, &t.end_label_comments), - text(if t.end_semi { ";" } else { "" }), - ]) - } - - // ------------------------------------------------------------------ - // Constraints - // ------------------------------------------------------------------ - - /// `[qualifiers ]constraint [cls::]name { ... }`, or the `constraint c;` - /// prototype. - /// - /// A named constraint is a *block*, so it is laid out like one: the - /// header keeps the `{`, every constraint item takes a line of its own at - /// one further indent, and the `}` closes back at the header's column. - /// That supersedes the `classes` README's "no layout convention worth - /// inventing" — there was none while the body was opaque bytes; now that - /// it is navigable, one canonical shape is worth exactly what canonical - /// shapes are always worth. - fn constraint(&self, c: &ConstraintDecl) -> Doc { - let mut docs = Vec::new(); - self.qualifier_run(&c.qualifiers, &mut docs); - docs.push(text("constraint")); - self.inline_comments_spaced(&c.before_name, &mut docs); - self.scope_prefix(&c.scope, &mut docs); - let name = named(&c.name.text); - // `named` already wrote the space an escaped identifier needs; a - // second one would be a gratuitous re-spacing of the header. - let escaped = name.ends_with(' '); - docs.push(text(name)); - let ends_line = self.inline_comments(&c.after_name, &mut docs); - let Some(set) = &c.body else { - if ends_line { - docs.push(Doc::HardLine); - } - docs.push(text(";")); - return concat(docs); - }; - if ends_line { - docs.push(Doc::HardLine); - } else if !escaped || !c.after_name.is_empty() { - docs.push(text(" ")); - } - docs.push(self.constraint_block(set, false)); - if c.semi { - if self.inline_comments(&c.before_semi, &mut docs) { - docs.push(Doc::HardLine); - } - docs.push(text(";")); - } - concat(docs) - } - - /// The `{ ... }` of a constraint body or a nested constraint set. - /// - /// `flat_ok` allows the whole block onto one line when nothing inside it - /// forces a break — the shape a `randomize() with { addr == 0; }` is - /// written in. A `constraint` declaration never passes it: a declaration - /// is a block and reads as one. - fn constraint_block(&self, set: &ConstraintSet, flat_ok: bool) -> Doc { - let brk = if flat_ok { Doc::SoftLine } else { Doc::HardLine }; - let mut body = Vec::new(); - if !set.items.is_empty() { - body.push(brk.clone()); - body.extend(self.constraint_items(&set.items)); - } - body.extend(self.dangling(&set.dangling)); - if body.is_empty() { - return text("{}"); - } - group(vec![text("{"), indent(body), brk, text("}")]) - } - - /// The block of a `randomize() with { ... }`: the same layout, but kept on - /// the statement's line when the **source** wrote it on one line. - /// - /// A `with` block is written inside a statement, not standing as a - /// declaration, and `if (!req.randomize() with { addr == 0; })` is the - /// idiom every DV testbench writes. The question is asked of the source - /// rather than measured, for two reasons. It is a fact about the gap - /// between two tokens, which is the one thing this file already reads - /// `src` for (`glued_null_item`, `default_has_colon`). And it is a fixed - /// point by construction: a flattened block is one line, so the next pass - /// flattens it again; a broken one holds newlines, so the next pass - /// breaks it again. - /// - /// Reading the source also settles the `//` question for free: a line - /// comment needs a newline to end, so a one-line block cannot hold one, - /// and a flattened `}` can never land inside a comment. The - /// `contains_hard_line` check is the belt to that braces — anything else - /// that forces a break takes the block layout. - fn with_constraint_block(&self, set: &ConstraintSet) -> Doc { - if self.src.get(set.span.as_range()).is_some_and(|s| !s.contains('\n')) { - let flat = self.constraint_block(set, true); - if !contains_hard_line(std::slice::from_ref(&flat)) { - return flat; - } - } - self.constraint_block(set, false) - } - - fn constraint_items(&self, items: &[ConstraintItem]) -> Vec { - let mut docs = Vec::new(); - for (i, item) in items.iter().enumerate() { - if i > 0 { - docs.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); - } - docs.push(self.with_meta(&item.meta, self.constraint_item(item))); - } - docs - } - - /// One constraint item, and the `;` that ends it when its kind takes one. - /// - /// The `;` is written here rather than in each arm so that the comments - /// the source wrote in front of it have exactly one place to be printed: - /// on the item's side of the separator, which is where they were - /// written. [`ConstraintItemKind::takes_semi`] is the one answer both - /// this and the parser read. - fn constraint_item(&self, item: &ConstraintItem) -> Doc { - let mut docs = vec![self.constraint_item_kind(&item.kind)]; - if item.kind.takes_semi() { - if self.inline_comments(&item.before_semi, &mut docs) { - docs.push(Doc::HardLine); - } - docs.push(text(";")); - } - concat(docs) - } - - fn constraint_item_kind(&self, kind: &ConstraintItemKind) -> Doc { - match kind { - ConstraintItemKind::Expr { soft, after_soft, expr } => { - if !*soft { - return self.expr(expr); - } - let mut docs = vec![text("soft")]; - self.inline_comments_spaced(after_soft, &mut docs); - docs.push(self.expr(expr)); - concat(docs) - } - ConstraintItemKind::Implication { cond, comments, set } => { - let mut head = vec![self.expr(cond)]; - self.inline_comments_spaced(&comments.before, &mut head); - head.push(text("->")); - let ends_line = self.inline_comments(&comments.after, &mut head); - if ends_line { - head.push(Doc::HardLine); - } - self.constraint_set_as_body(concat(head), set, &[], !ends_line) - } - ConstraintItemKind::If { cond, comments, then, else_comments, after_else, els } => { - let mut head = vec![text("if")]; - self.inline_comments_spaced(&comments.after_kw, &mut head); - head.push(self.constraint_parens(cond, comments)); - let mut docs = vec![self.constraint_set_as_body( - concat(head), - then, - &comments.before_body, - true, - )]; - let Some(els) = els else { return concat(docs) }; - // A braced `then` cuddles the `else` onto the `}` line, the - // way a statement `if` cuddles it onto `end`. - docs.push(if then.braced { text(" ") } else { Doc::HardLine }); - for c in else_comments { - docs.push(self.comment(c)); - docs.push(Doc::HardLine); - } - // `else if` chains on one line, the way a statement `if` does: - // an unbraced else holding exactly one `if` is the chain, and - // indenting it once per link would stair-step the whole thing - // off the right of the page. - match Self::chained_if(els) { - Some(item) => { - let mut chain = vec![text("else")]; - self.inline_comments_spaced(after_else, &mut chain); - chain.push(self.with_meta(&item.meta, self.constraint_item(item))); - docs.push(concat(chain)); - } - None => { - docs.push(self.constraint_set_as_body(text("else"), els, after_else, true)) - } - } - concat(docs) - } - ConstraintItemKind::Foreach { array, vars, var_comments, comments, set } => { - let mut head = vec![text("foreach")]; - self.inline_comments_spaced(&comments.after_kw, &mut head); - head.push(text("(")); - self.inline_comments(&comments.after_open, &mut head); - if !comments.after_open.is_empty() { - head.push(text(" ")); - } - head.push(self.expr(array)); - head.push(self.foreach_vars(vars, var_comments)); - if self.inline_comments(&comments.before_close, &mut head) { - head.push(Doc::HardLine); - } else if !comments.before_close.is_empty() { - head.push(text(" ")); - } - head.push(text(")")); - self.constraint_set_as_body(concat(head), set, &comments.before_body, true) - } - ConstraintItemKind::SolveBefore { solve, before_comments, before } => { - let mut docs = vec![text("solve "), self.plain_expr_list(solve)]; - self.inline_comments_spaced(before_comments, &mut docs); - docs.push(text("before ")); - docs.push(self.plain_expr_list(before)); - concat(docs) - } - ConstraintItemKind::Unique { items, comments } => { - let mut docs = vec![text("unique")]; - self.inline_comments_spaced(comments, &mut docs); - docs.push(self.expr_list("{", items, "}")); - concat(docs) - } - ConstraintItemKind::DisableSoft { expr, comments } => { - let mut docs = vec![text("disable")]; - self.inline_comments_spaced(&comments.before, &mut docs); - docs.push(text("soft")); - self.inline_comments_spaced(&comments.after, &mut docs); - docs.push(self.expr(expr)); - concat(docs) - } - ConstraintItemKind::Directive(raw) => self.raw_text(raw), - ConstraintItemKind::Empty => text(";"), - } - } - - /// The `( cond )` of a constraint `if`, with the comments written just - /// inside either parenthesis printed back where they were written. - fn constraint_parens(&self, cond: &Expr, comments: &HeaderComments) -> Doc { - self.guard_parens(cond, &comments.after_open, &comments.before_close) - } - - /// `( expr )` with whatever was written just inside either parenthesis: - /// a constraint `if`'s condition, a covergroup `iff` guard, a bin's - /// `with ( ... )` filter. One place, so the three cannot drift apart. - fn guard_parens(&self, e: &Expr, after_open: &[Comment], before_close: &[Comment]) -> Doc { - if after_open.is_empty() && before_close.is_empty() { - return self.parens(e); - } - let before: Vec<&Comment> = after_open.iter().collect(); - let after: Vec<&Comment> = before_close.iter().collect(); - self.paren_comments(e, &before, &after) - } - - /// The `if` an `else` chains straight onto: the single item of an - /// unbraced `else` set, when that item is itself an `if`. - fn chained_if(set: &ConstraintSet) -> Option<&ConstraintItem> { - if set.braced || set.items.len() != 1 { - return None; - } - let item = set.items.first()?; - matches!(item.kind, ConstraintItemKind::If { .. }).then_some(item) - } - - /// A header followed by a constraint set: a braced set cuddles onto the - /// header line, an unbraced one goes on the same line if it fits and on - /// an indented next line if it does not — exactly what - /// [`Fmt::stmt_as_body`] does for statements. - fn constraint_set_as_body( - &self, - head: Doc, - set: &ConstraintSet, - before: &[Comment], - space: bool, - ) -> Doc { - if set.braced { - let mut docs = vec![head]; - if self.inline_comments(before, &mut docs) { - docs.push(Doc::HardLine); - } else if space || !before.is_empty() { - docs.push(text(" ")); - } - docs.push(self.constraint_block(set, false)); - return concat(docs); - } - let body = match set.items.first() { - Some(item) => self.with_meta(&item.meta, self.constraint_item(item)), - None => text(""), - }; - group(vec![head, indent(vec![Doc::Line, body])]) - } - - /// A comma-separated expression list with no brackets around it: the two - /// halves of a `solve a, b before c, d;`. - /// - /// Not [`Fmt::delimited`], which is written for a *bracketed* list: its - /// closing break would land the `before` keyword — or the item's `;` — - /// on a line of its own the moment any comment forced the group open. - /// A list with no brackets has nothing to open, so every comment prints - /// where it was written and only a `//` costs a line break. - fn plain_expr_list(&self, items: &[ExprItem]) -> Doc { - self.plain_list(items.iter().map(|i| (&i.meta, self.expr(&i.expr))).collect()) - } - - /// The same, over elements the caller has already rendered: a transition - /// bin's `(a => b), (c => d)` sets are laid out by exactly this rule. - fn plain_list(&self, items: Vec<(&Meta, Doc)>) -> Doc { - let mut docs = Vec::new(); - let last = items.len().saturating_sub(1); - for (i, (meta, doc)) in items.into_iter().enumerate() { - let leading: Vec<&Comment> = meta.leading.iter().collect(); - let mut ends_line = false; - for c in leading { - docs.push(self.comment(c)); - docs.push(if is_line_comment(&c.text) { Doc::HardLine } else { text(" ") }); - ends_line = is_line_comment(&c.text); - } - docs.push(doc); - ends_line = self.inline_comments(&meta.before_sep, &mut docs) || ends_line; - if i < last { - if ends_line { - docs.push(Doc::HardLine); - } - docs.push(text(",")); - } - if let Some(tr) = &meta.trailing { - docs.push(text(" ")); - docs.push(self.comment(tr)); - if is_line_comment(&tr.text) { - docs.push(Doc::HardLine); - continue; - } - } - if i < last { - docs.push(text(" ")); - } - } - concat(docs) - } - - /// `expr dist { 0 := 5, [1:20] :/ 20 }` — the weight list laid out like - /// every other braced list: one per line when it does not fit. `:=` and - /// `:/` are printed back exactly as written; they mean different things. - fn dist(&self, expr: &Expr, comments: &BinaryComments, weights: &[DistItem]) -> Doc { - let items: Vec = weights - .iter() - .map(|w| { - let mut docs = vec![self.expr(&w.value)]; - if let (Some(op), Some(weight)) = (&w.op, &w.weight) { - self.inline_comments_spaced(&w.op_comments.before, &mut docs); - docs.push(text(op.clone())); - self.inline_comments_spaced(&w.op_comments.after, &mut docs); - docs.push(self.expr(weight)); - } - ListItem::from_meta(&w.meta, concat(docs)) - }) - .collect(); - let mut docs = vec![self.expr(expr)]; - self.inline_comments_spaced(&comments.before, &mut docs); - docs.push(text("dist")); - self.inline_comments_spaced(&comments.after, &mut docs); - docs.push(self.delimited("{", items, "}", false)); - concat(docs) - } - - // ------------------------------------------------------------------ - // Covergroups - // ------------------------------------------------------------------ - - /// `covergroup g (args) with function sample (args); ... endgroup : g`. - /// - /// A covergroup is a block, so it is laid out like one: the whole header - /// on the header line, every cover item on a line of its own at one - /// further indent, and `endgroup` back at the header's column with - /// whatever label the source wrote. - fn covergroup(&self, c: &CovergroupDecl) -> Doc { - let mut docs = Vec::new(); - self.qualifier_run(&c.qualifiers, &mut docs); - docs.push(text("covergroup")); - self.inline_comments_spaced(&c.before_name, &mut docs); - docs.push(name_doc(&c.name.text)); - if let Some(args) = &c.args { - if !c.before_args.is_empty() { - self.inline_comments_spaced(&c.before_args, &mut docs); - } - docs.push(self.tf_args(args, &[])); - } - match &c.event { - Some(CoverageEvent::Sample(s)) => { - self.inline_comments_spaced(&s.before_with, &mut docs); - docs.push(text("with")); - self.inline_comments_spaced(&s.after_with, &mut docs); - docs.push(text("function")); - self.inline_comments_spaced(&s.after_function, &mut docs); - docs.push(name_doc(&s.name.text)); - if s.has_parens { - if !s.before_args.is_empty() { - self.inline_comments_spaced(&s.before_args, &mut docs); - } - docs.push(self.tf_args(&s.args, &[])); - } - } - Some(CoverageEvent::Clocking { before, sens }) => { - self.inline_comments_spaced(before, &mut docs); - docs.push(self.sens_list(sens)); - } - None => {} - } - if self.inline_comments(&c.before_semi, &mut docs) { - docs.push(Doc::HardLine); - } - docs.push(text(";")); - let mut body = Vec::new(); - if !c.items.is_empty() { - body.push(Doc::HardLine); - body.extend(self.cover_items(&c.items)); - } - body.extend(self.dangling(&c.dangling)); - docs.push(indent(body)); - docs.push(Doc::HardLine); - let end_label = c.end_label.as_ref().map(|l| l.text.clone()); - docs.push(self.closing_labeled("endgroup", &end_label, &c.end_label_comments)); - if c.end_semi { - if self.inline_comments(&c.before_end_semi, &mut docs) { - docs.push(Doc::HardLine); - } - docs.push(text(";")); - } - concat(docs) - } - - fn cover_items(&self, items: &[CoverItem]) -> Vec { - let mut docs = Vec::new(); - for (i, item) in items.iter().enumerate() { - if i > 0 { - docs.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); - } - docs.push(self.with_meta(&item.meta, self.cover_item(item))); - } - docs - } - - /// One cover item, and the `;` that ends it when its kind takes one — the - /// rule [`CoverItemKind::takes_semi`] is the single answer to, read here - /// and by the parser that consumed it. - fn cover_item(&self, item: &CoverItem) -> Doc { - let mut docs = vec![self.cover_item_kind(&item.kind)]; - if item.kind.takes_semi() { - if self.inline_comments(&item.before_semi, &mut docs) { - docs.push(Doc::HardLine); - } - docs.push(text(";")); - } - concat(docs) - } - - fn cover_item_kind(&self, kind: &CoverItemKind) -> Doc { - match kind { - CoverItemKind::Coverpoint(cp) => { - let mut head = Vec::new(); - self.cover_label(&cp.label, &mut head); - head.push(text("coverpoint")); - self.inline_comments_spaced(&cp.after_kw, &mut head); - head.push(self.expr(&cp.expr)); - self.cover_iff(&cp.iff, &mut head); - self.cover_body_as_body(concat(head), &cp.before_body, &cp.body) - } - CoverItemKind::Cross(cr) => { - let mut head = Vec::new(); - self.cover_label(&cr.label, &mut head); - head.push(text("cross")); - self.inline_comments_spaced(&cr.after_kw, &mut head); - head.push(self.plain_expr_list(&cr.items)); - self.cover_iff(&cr.iff, &mut head); - self.cover_body_as_body(concat(head), &cr.before_body, &cr.body) - } - CoverItemKind::Option(o) => self.option_assign(o), - CoverItemKind::Directive(raw) => self.raw_text(raw), - CoverItemKind::Empty => text(";"), - } - } - - /// The `name :` a coverpoint or a cross may be labelled with. - fn cover_label(&self, label: &Option, docs: &mut Vec) { - let Some(l) = label else { return }; - docs.push(name_doc(&l.name.text)); - if self.inline_comments(&l.comments.before, docs) { - docs.push(Doc::HardLine); - } - docs.push(text(":")); - self.inline_comments_spaced(&l.comments.after, docs); - } - - /// The ` iff ( expr )` guard of a coverpoint, a cross or a bin. - fn cover_iff(&self, iff: &Option>, docs: &mut Vec) { - let Some(i) = iff else { return }; - self.inline_comments_spaced(&i.before_kw, docs); - docs.push(text("iff")); - self.inline_comments_spaced(&i.after_kw, docs); - docs.push(self.guard_parens(&i.expr, &i.after_open, &i.before_close)); - } - - /// A coverpoint or cross header followed by its `{ bins }` body, or by - /// nothing at all — a body-less one ends in the `;` [`Fmt::cover_item`] - /// writes. - fn cover_body_as_body(&self, head: Doc, before: &[Comment], body: &Option) -> Doc { - let Some(body) = body else { return head }; - let mut docs = vec![head]; - if self.inline_comments(before, &mut docs) { - docs.push(Doc::HardLine); - } else { - docs.push(text(" ")); - } - docs.push(self.cover_block(body)); - concat(docs) - } - - /// The `{ ... }` of a coverpoint or cross body: one bin per line at one - /// further indent, the `}` back at the header's column — a constraint - /// set's layout, for a construct that reads the same way. - fn cover_block(&self, body: &CoverBody) -> Doc { - let mut inner = Vec::new(); - if !body.items.is_empty() { - inner.push(Doc::HardLine); - inner.extend(self.bin_items(&body.items)); - } - inner.extend(self.dangling(&body.dangling)); - if inner.is_empty() { - return text("{}"); - } - group(vec![text("{"), indent(inner), Doc::HardLine, text("}")]) - } - - fn bin_items(&self, items: &[BinItem]) -> Vec { - let mut docs = Vec::new(); - for (i, item) in items.iter().enumerate() { - if i > 0 { - docs.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); - } - docs.push(self.with_meta(&item.meta, self.bin_item(item))); - } - docs - } - - fn bin_item(&self, item: &BinItem) -> Doc { - let mut docs = vec![match &item.kind { - BinItemKind::Bin(b) => self.bin_decl(b), - BinItemKind::Option(o) => self.option_assign(o), - BinItemKind::Directive(raw) => self.raw_text(raw), - BinItemKind::Empty => text(";"), - }]; - if item.kind.takes_semi() { - if self.inline_comments(&item.before_semi, &mut docs) { - docs.push(Doc::HardLine); - } - docs.push(text(";")); - } - concat(docs) - } - - /// `option.per_instance = 1` / `type_option.weight = 5`. - fn option_assign(&self, o: &OptionAssign) -> Doc { - let mut docs = vec![self.expr(&o.target)]; - if self.inline_comments(&o.comments.before, &mut docs) { - docs.push(Doc::HardLine); - } else { - docs.push(text(" ")); - } - docs.push(text("=")); - self.inline_comments_spaced(&o.comments.after, &mut docs); - docs.push(self.expr(&o.value)); - concat(docs) - } - - /// `[wildcard ]bins name[4] = spec [with (expr)] [iff (expr)]`. - fn bin_decl(&self, b: &BinDecl) -> Doc { - let mut docs = Vec::new(); - if b.wildcard { - docs.push(text("wildcard")); - self.inline_comments_spaced(&b.after_wildcard, &mut docs); - } - docs.push(text(b.kind.as_str())); - self.inline_comments_spaced(&b.before_name, &mut docs); - docs.push(name_doc(&b.name.text)); - if let Some(a) = &b.array { - if !a.before.is_empty() { - self.inline_comments_spaced(&a.before, &mut docs); - } - docs.push(text("[")); - self.inline_comments(&a.comments.before, &mut docs); - if !a.comments.before.is_empty() { - docs.push(text(" ")); - } - if let Some(size) = &a.size { - docs.push(self.expr(size)); - } - if self.inline_comments(&a.comments.after, &mut docs) { - docs.push(Doc::HardLine); - } else if !a.comments.after.is_empty() { - docs.push(text(" ")); - } - docs.push(text("]")); - } - if self.inline_comments(&b.eq_comments.before, &mut docs) { - docs.push(Doc::HardLine); - } else { - docs.push(text(" ")); - } - docs.push(text("=")); - self.inline_comments_spaced(&b.eq_comments.after, &mut docs); - docs.push(self.bin_spec(&b.spec)); - if let Some(w) = &b.with_expr { - self.inline_comments_spaced(&w.before_kw, &mut docs); - docs.push(text("with")); - self.inline_comments_spaced(&w.after_kw, &mut docs); - docs.push(self.guard_parens(&w.expr, &w.after_open, &w.before_close)); - } - self.cover_iff(&b.iff, &mut docs); - concat(docs) - } - - fn bin_spec(&self, spec: &BinSpec) -> Doc { - match spec { - BinSpec::Values(items) => self.expr_list("{", items, "}"), - BinSpec::Transitions(sets) => self.trans_list(sets), - BinSpec::Default => text("default"), - BinSpec::DefaultSequence { comments } => { - let mut docs = vec![text("default")]; - self.inline_comments_spaced(comments, &mut docs); - docs.push(text("sequence")); - concat(docs) - } - BinSpec::Select(s) => self.select_expr(s), - } - } - - /// `(a => b), (c => d)` — the transition sets of a transition bin, joined - /// by the commas the source wrote. - fn trans_list(&self, sets: &[TransSet]) -> Doc { - self.plain_list(sets.iter().map(|s| (&s.meta, self.trans_set(s))).collect()) - } - - fn trans_set(&self, set: &TransSet) -> Doc { - let mut docs = vec![text("(")]; - for (i, r) in set.ranges.iter().enumerate() { - if i > 0 { - if self.inline_comments(&r.arrow_comments.before, &mut docs) { - docs.push(Doc::HardLine); - } else { - docs.push(text(" ")); - } - docs.push(text("=>")); - self.inline_comments_spaced(&r.arrow_comments.after, &mut docs); - } - docs.push(self.trans_range(r)); - } - if self.inline_comments(&set.dangling, &mut docs) { - docs.push(Doc::HardLine); - } else if !set.dangling.is_empty() { - docs.push(text(" ")); - } - docs.push(text(")")); - concat(docs) - } - - fn trans_range(&self, r: &TransRange) -> Doc { - let mut docs = vec![self.plain_expr_list(&r.items)]; - let Some(rep) = &r.repeat else { return concat(docs) }; - if !rep.before.is_empty() { - self.inline_comments_spaced(&rep.before, &mut docs); - } - docs.push(text("[")); - self.inline_comments(&rep.after_open, &mut docs); - if !rep.after_open.is_empty() { - docs.push(text(" ")); - } - docs.push(text(rep.op.clone())); - self.inline_comments(&rep.comments.before, &mut docs); - if !rep.comments.before.is_empty() { - docs.push(text(" ")); - } - docs.push(self.expr(&rep.lo)); - if let Some(hi) = &rep.hi { - self.inline_comments(&rep.colon_comments.before, &mut docs); - if !rep.colon_comments.before.is_empty() { - docs.push(text(" ")); - } - docs.push(text(":")); - self.inline_comments(&rep.colon_comments.after, &mut docs); - if !rep.colon_comments.after.is_empty() { - docs.push(text(" ")); - } - docs.push(self.expr(hi)); - } - if self.inline_comments(&rep.comments.after, &mut docs) { - docs.push(Doc::HardLine); - } else if !rep.comments.after.is_empty() { - docs.push(text(" ")); - } - docs.push(text("]")); - concat(docs) - } - - /// `binsof(a) intersect {0} && !binsof(b)` — a cross bin's select - /// expression, and the bare coverpoint name a coverpoint bin may name. - fn select_expr(&self, s: &SelectExpr) -> Doc { - match s { - SelectExpr::Binsof(b) => { - let mut docs = vec![text("binsof")]; - if !b.after_kw.is_empty() { - self.inline_comments_spaced(&b.after_kw, &mut docs); - } - docs.push(text("(")); - self.inline_comments(&b.after_open, &mut docs); - if !b.after_open.is_empty() { - docs.push(text(" ")); - } - docs.push(self.expr(&b.name)); - if self.inline_comments(&b.before_close, &mut docs) { - docs.push(Doc::HardLine); - } else if !b.before_close.is_empty() { - docs.push(text(" ")); - } - docs.push(text(")")); - if let Some(items) = &b.intersect { - self.inline_comments_spaced(&b.before_intersect, &mut docs); - docs.push(text("intersect")); - self.inline_comments_spaced(&b.after_intersect, &mut docs); - docs.push(self.expr_list("{", items, "}")); - } - concat(docs) - } - SelectExpr::Not { comments, expr } => { - let mut docs = vec![text("!")]; - if !comments.is_empty() { - self.inline_comments(comments, &mut docs); - docs.push(text(" ")); - } - docs.push(self.select_expr(expr)); - concat(docs) - } - SelectExpr::Binary { lhs, op, comments, rhs } => { - let mut docs = vec![self.select_expr(lhs)]; - if self.inline_comments(&comments.before, &mut docs) { - docs.push(Doc::HardLine); - } else { - docs.push(text(" ")); - } - docs.push(text(op.clone())); - self.inline_comments_spaced(&comments.after, &mut docs); - docs.push(self.select_expr(rhs)); - concat(docs) - } - SelectExpr::Paren { comments, expr } => { - let mut docs = vec![text("(")]; - self.inline_comments(&comments.before, &mut docs); - if !comments.before.is_empty() { - docs.push(text(" ")); - } - docs.push(self.select_expr(expr)); - if self.inline_comments(&comments.after, &mut docs) { - docs.push(Doc::HardLine); - } else if !comments.after.is_empty() { - docs.push(text(" ")); - } - docs.push(text(")")); - concat(docs) - } - SelectExpr::Expr(e) => self.expr(e), - } - } - - // ------------------------------------------------------------------ - // Assertions (IEEE 1800-2017 §16) - // - // One layout rule, stated in `docs/features/sva-bodies/README.md`: the - // spec's top-level operators — `|->`, `|=>`, `##`, `and`, `or` — break - // one per line at the parent's indent when the spec does not fit on one - // line; everything else is inline. Each operand is then laid out by the - // same rule, so a wide operand of a broken operator breaks in turn and a - // narrow one does not. - // ------------------------------------------------------------------ - - /// `property p (args); … endproperty : p` and its `sequence` twin. - fn prop_seq_decl(&self, d: &PropSeqDecl) -> Doc { - let end_kw = if d.kw == "sequence" { "endsequence" } else { "endproperty" }; - let mut docs = vec![text(d.kw.clone())]; - self.inline_comments_spaced(&d.before_name, &mut docs); - docs.push(name_doc(&d.name.text)); - if let Some(args) = &d.args { - // The parens hug the name, as a function's do; only a comment - // written in that gap puts anything between the two. - if !d.before_args.is_empty() { - self.inline_comments_spaced(&d.before_args, &mut docs); - } - docs.push(self.tf_args(&args.args, &args.dangling)); - } - if self.inline_comments(&d.before_semi, &mut docs) { - docs.push(Doc::HardLine); - } - docs.push(text(";")); - let mut body = Vec::new(); - for local in &d.locals { - body.push(if local.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); - body.push(self.with_meta(&local.meta, self.item_kind(&local.kind, None, 0))); - } - body.push(Doc::HardLine); - body.push(self.prop_spec(&d.spec)); - if d.spec_semi { - if self.inline_comments(&d.before_spec_semi, &mut body) { - body.push(Doc::HardLine); - } - body.push(text(";")); - } - body.extend(self.dangling(&d.dangling)); - docs.push(indent(body)); - docs.push(Doc::HardLine); - let end_label = d.end_label.as_ref().map(|l| l.text.clone()); - docs.push(self.closing_labeled(end_kw, &end_label, &d.end_label_comments)); - concat(docs) - } - - /// `[lbl :] assert property ( spec ) action_block`. - fn assertion(&self, a: &AssertionDecl) -> Doc { - let mut docs = Vec::new(); - if let Some(label) = &a.label { - docs.push(name_doc(&label.text)); - self.slot_comments(&a.label_comments.before_colon, &mut docs); - docs.push(text(":")); - if a.label_comments.after_colon.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&a.label_comments.after_colon, &mut docs); - } - } - docs.push(text(a.kw.clone())); - if !a.kw2.is_empty() { - self.inline_comments_spaced(&a.after_kw, &mut docs); - docs.push(text(a.kw2.clone())); - } - if a.before_open.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&a.before_open, &mut docs); - } - docs.push(self.prop_parens(&a.after_open, &a.spec, &a.before_close)); - self.action_block(concat(docs), &a.action) - } - - /// `( spec )`. The parentheses hug the spec's first and last lines — a - /// spec that breaks does so *inside* them, one indent in, which is what - /// every multi-line assertion in the corpus is already written as. - fn prop_parens( - &self, - after_open: &[Comment], - spec: &PropSpec, - before_close: &[Comment], - ) -> Doc { - let mut inner = Vec::new(); - if self.inline_comments(after_open, &mut inner) { - inner.push(Doc::HardLine); - } else if !after_open.is_empty() { - inner.push(text(" ")); - } - inner.push(self.prop_spec(spec)); - let mut docs = vec![text("("), indent(inner)]; - if self.inline_comments(before_close, &mut docs) { - docs.push(Doc::HardLine); - } else if !before_close.is_empty() { - docs.push(text(" ")); - } - docs.push(text(")")); - concat(docs) - } - - /// `head` — the assertion through its closing `)` — followed by the - /// action block's pass and fail statements, laid out exactly as an `if` - /// statement's branches are: a block cuddles onto the line before it, a - /// single statement goes there if it fits and on an indented next line if - /// it does not, and `else` follows a block on its closing line. - fn action_block(&self, head: Doc, a: &ActionBlock) -> Doc { - if a.pass.is_none() && a.fail.is_none() { - let mut docs = vec![head]; - if self.inline_comments(&a.before, &mut docs) { - docs.push(Doc::HardLine); - } - docs.push(text(";")); - return concat(docs); - } - let Some(pass) = &a.pass else { - // `assert property (p) else $error(…);` — the `else` follows the - // spec's `)` directly, and takes the next line when it does not - // fit beside it. - let Some(fail) = &a.fail else { return head }; - let mut head = vec![head]; - self.inline_comments(&a.before_else, &mut head); - let head = concat(head); - let mut els = vec![text("else")]; - self.inline_comments(&a.after_else, &mut els); - // A `begin ... end` fail statement cuddles onto the assertion's - // own line, the way an `if`'s block branch does; measuring it - // would only ever say "does not fit", because a block holds a - // hard line break. - if matches!(fail.kind, StmtKind::Block { .. } | StmtKind::ForkJoin { .. }) { - return concat(vec![head, text(" "), self.stmt_as_body(concat(els), fail)]); - } - return group(vec![ - head, - indent(vec![Doc::Line, self.stmt_as_body(concat(els), fail)]), - ]); - }; - // A line comment trailing the pass statement runs to end of line, so - // a cuddled `else` would be swallowed into its text — `if_stmt`'s - // rule, for the same reason. - let pass_is_block = matches!(pass.kind, StmtKind::Block { .. } | StmtKind::ForkJoin { .. }) - && !trailing_ends_line(&pass.meta); - let mut docs = vec![self.stmt_as_body(head, pass)]; - let Some(fail) = &a.fail else { return concat(docs) }; - if !a.before_else.is_empty() { - docs.push(Doc::HardLine); - for c in &a.before_else { - docs.push(self.comment(c)); - docs.push(Doc::HardLine); - } - docs.push(text("else")); - } else if pass_is_block { - docs.push(text(" else")); - } else { - docs.push(Doc::HardLine); - docs.push(text("else")); - } - self.inline_comments(&a.after_else, &mut docs); - // The fail statement is measured on its own, not against the pass - // statement that already broke across lines: `if_stmt` passes an - // empty prefix here for the same reason, and the `else` above - // supplies the separator's left half. - docs.push(self.stmt_as_body(text(""), fail)); - concat(docs) - } - - /// `default disable iff ( expr );`. - fn default_disable(&self, d: &DisableIff) -> Doc { - let mut docs = vec![text("default")]; - if d.before_kw.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&d.before_kw, &mut docs); - } - docs.push(self.disable_iff(d)); - if self.inline_comments(&d.before_semi, &mut docs) { - docs.push(Doc::HardLine); - } - docs.push(text(";")); - concat(docs) - } - - /// `disable iff ( expr )`, without the `default` spelling's `;`. - fn disable_iff(&self, d: &DisableIff) -> Doc { - let mut docs = vec![text("disable")]; - if d.after_disable.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&d.after_disable, &mut docs); - } - docs.push(text("iff")); - if d.after_iff.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&d.after_iff, &mut docs); - } - if d.parens { - docs.push(self.guard_parens(&d.expr, &d.after_open, &d.before_close)); - } else { - docs.push(self.expr(&d.expr)); - } - concat(docs) - } - - /// A `property_spec`: the clocking event, the `disable iff` and the - /// property expression, each on its own line when the three do not fit - /// on one. - fn prop_spec(&self, spec: &PropSpec) -> Doc { - let mut docs = Vec::new(); - for c in &spec.leading { - docs.push(self.comment(c)); - docs.push(if is_line_comment(&c.text) { Doc::HardLine } else { Doc::Line }); - } - if let Some(sens) = &spec.clocking { - docs.push(self.sens_list(sens)); - docs.push(Doc::Line); - } - if let Some(dis) = &spec.disable { - self.slot_comments(&dis.before_kw, &mut docs); - docs.push(self.disable_iff(dis)); - docs.push(Doc::Line); - } - // A comment written in front of the property expression prints where - // it was written — after whatever `Doc::Line` the header already - // pushed, so it starts the line rather than trailing a space onto it. - for c in &spec.before_expr { - docs.push(self.comment(c)); - docs.push(if is_line_comment(&c.text) { Doc::HardLine } else { Doc::Line }); - } - docs.push(self.prop_expr(&spec.expr)); - group(docs) - } - - /// True when a top-level operator of a spec breaks onto its own line. - /// The five the round's one layout rule names. - fn breaks_line(op: &PropOp) -> bool { - match op { - PropOp::Delay(_) => true, - PropOp::Word(w) => matches!(w.as_str(), "|->" | "|=>" | "and" | "or"), - } - } - - fn prop_expr(&self, e: &PropExpr) -> Doc { - match &e.kind { - PropKind::Expr(inner) => self.expr(inner), - PropKind::Paren(p) => { - let mut docs = vec![text("(")]; - if self.inline_comments(&p.after_open, &mut docs) { - docs.push(Doc::HardLine); - } else if !p.after_open.is_empty() { - docs.push(text(" ")); - } - docs.push(self.prop_expr(&p.expr)); - docs.extend(self.match_items(&p.items)); - if self.inline_comments(&p.before_close, &mut docs) { - docs.push(Doc::HardLine); - } else if !p.before_close.is_empty() { - docs.push(text(" ")); - } - docs.push(text(")")); - concat(docs) - } - PropKind::Binary(b) => { - let mut op = Vec::new(); - self.slot_comments(&b.comments.before, &mut op); - match &b.op { - PropOp::Word(w) => op.push(text(w.clone())), - PropOp::Delay(d) => op.push(self.cycle_delay(d)), - } - if b.comments.after.is_empty() { - op.push(text(" ")); - } else { - self.inline_comments_spaced(&b.comments.after, &mut op); - } - let lhs = self.prop_expr(&b.lhs); - let rhs = self.prop_expr(&b.rhs); - if Self::breaks_line(&b.op) { - return group(vec![lhs, Doc::Line, concat(op), rhs]); - } - concat(vec![lhs, text(" "), concat(op), rhs]) - } - PropKind::Unary(u) => { - let mut docs = vec![text(u.op.clone())]; - if u.comments.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&u.comments, &mut docs); - } - if let Some(count) = &u.count { - docs.push(self.sva_range("", &[], count)); - if u.after_count.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&u.after_count, &mut docs); - } - } - docs.push(self.prop_expr(&u.expr)); - concat(docs) - } - PropKind::Call(c) => { - let mut docs = vec![text(c.name.clone())]; - self.slot_comments(&c.before_open, &mut docs); - docs.push(text("(")); - if self.inline_comments(&c.after_open, &mut docs) { - docs.push(Doc::HardLine); - } else if !c.after_open.is_empty() { - docs.push(text(" ")); - } - docs.push(self.prop_expr(&c.expr)); - docs.extend(self.match_items(&c.items)); - if self.inline_comments(&c.before_close, &mut docs) { - docs.push(Doc::HardLine); - } else if !c.before_close.is_empty() { - docs.push(text(" ")); - } - docs.push(text(")")); - concat(docs) - } - PropKind::Abort(a) => { - let mut docs = vec![text(a.kw.clone())]; - if a.comments.after_kw.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&a.comments.after_kw, &mut docs); - } - docs.push(self.guard_parens( - &a.cond, - &a.comments.after_open, - &a.comments.before_close, - )); - if a.comments.before_body.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&a.comments.before_body, &mut docs); - } - docs.push(self.prop_expr(&a.expr)); - concat(docs) - } - PropKind::Delay(d) => { - let mut docs = vec![self.cycle_delay(&d.delay)]; - if d.after_delay.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&d.after_delay, &mut docs); - } - docs.push(self.prop_expr(&d.expr)); - concat(docs) - } - PropKind::Repeat(r) => { - let mut docs = vec![self.prop_expr(&r.expr)]; - self.slot_comments(&r.before_open, &mut docs); - docs.push(self.sva_range(&r.op, &r.after_op, &r.range)); - concat(docs) - } - PropKind::If(i) => { - let mut docs = vec![text("if")]; - if i.comments.after_kw.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&i.comments.after_kw, &mut docs); - } - docs.push(self.guard_parens( - &i.cond, - &i.comments.after_open, - &i.comments.before_close, - )); - if i.comments.before_body.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&i.comments.before_body, &mut docs); - } - docs.push(self.prop_expr(&i.then)); - if let Some(els) = &i.els { - self.slot_comments(&i.before_else, &mut docs); - docs.push(text(" else")); - if i.after_else.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&i.after_else, &mut docs); - } - docs.push(self.prop_expr(els)); - } - concat(docs) - } - PropKind::Case(c) => { - let mut docs = vec![text("case")]; - if c.comments.after_kw.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&c.comments.after_kw, &mut docs); - } - docs.push(self.guard_parens( - &c.cond, - &c.comments.after_open, - &c.comments.before_close, - )); - let mut body = Vec::new(); - for item in &c.items { - body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); - body.push(self.with_meta(&item.meta, self.prop_case_item(item))); - } - body.extend(self.dangling(&c.dangling)); - docs.push(indent(body)); - docs.push(Doc::HardLine); - docs.push(text("endcase")); - concat(docs) - } - PropKind::Spec(spec) => self.prop_spec(spec), - } - } - - fn prop_case_item(&self, item: &PropCaseItem) -> Doc { - let mut docs = Vec::new(); - if item.is_default { - docs.push(text("default")); - } else { - docs.push(self.plain_expr_list(&item.labels)); - } - self.slot_comments(&item.before_colon, &mut docs); - docs.push(text(":")); - if item.after_colon.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&item.after_colon, &mut docs); - } - docs.push(self.prop_expr(&item.expr)); - if self.inline_comments(&item.before_semi, &mut docs) { - docs.push(Doc::HardLine); - } - docs.push(text(";")); - concat(docs) - } - - /// `, x = e, y++` — the match items of a parenthesised sequence. - fn match_items(&self, items: &[MatchItem]) -> Vec { - let mut docs = Vec::new(); - for item in items { - self.slot_comments(&item.before_comma, &mut docs); - docs.push(text(", ")); - docs.extend(self.leading(&item.meta)); - docs.push(self.expr(&item.lhs)); - if let Some(op) = &item.op { - self.slot_comments(&item.comments.before, &mut docs); - docs.push(text(format!(" {op}"))); - if item.comments.after.is_empty() { - docs.push(text(" ")); - } else { - self.inline_comments_spaced(&item.comments.after, &mut docs); - } - } - if let Some(rhs) = &item.rhs { - docs.push(self.expr(rhs)); - } - } - docs - } - - /// `##3`, `##[1:$]`, `##[+]`. - fn cycle_delay(&self, d: &CycleDelay) -> Doc { - let mut docs = vec![text("##")]; - self.slot_comments(&d.after_hash, &mut docs); - if let Some(e) = &d.expr { - docs.push(self.expr(e)); - } - if let Some(range) = &d.range { - docs.push(self.sva_range("", &[], range)); - } - concat(docs) - } - - /// `[*3]`, `[=1:2]`, `[->1]`, `[+]`, and the bare `[2]` count of a - /// `nexttime`. `op` is empty for the two that write none. - fn sva_range(&self, op: &str, after_op: &[Comment], r: &SvaRange) -> Doc { - let mut docs = vec![text("[")]; - self.slot_comments_tight(&r.after_open, &mut docs); - if !op.is_empty() { - docs.push(text(op.to_string())); - self.slot_comments_tight(after_op, &mut docs); - } - if !r.shorthand.is_empty() { - docs.push(text(r.shorthand.clone())); - } - if let Some(lo) = &r.lo { - docs.push(self.expr(lo)); - } - if let Some(hi) = &r.hi { - self.slot_comments_tight(&r.before_colon, &mut docs); - docs.push(text(":")); - self.slot_comments_tight(&r.after_colon, &mut docs); - docs.push(self.expr(hi)); - } - self.slot_comments_tight(&r.before_close, &mut docs); - docs.push(text("]")); - concat(docs) - } - - /// [`Fmt::slot_comments`] for a slot that writes no space of its own: the - /// inside of a `[ ... ]` bound, where `[*3]` must stay tight. - fn slot_comments_tight(&self, comments: &[Comment], docs: &mut Vec) { - if comments.is_empty() { - return; - } - self.inline_comments(comments, docs); - docs.push(text(" ")); - } - - // ------------------------------------------------------------------ - // Statements - // ------------------------------------------------------------------ - - fn stmt(&self, s: &Stmt) -> Doc { - self.with_meta(&s.meta, self.stmt_kind(&s.kind, &s.before_semi)) - } - - /// The `;` that ends a statement, with whatever the source wrote in front - /// of it (`x = 1 /* inclusive */ ;`). [`StmtKind::takes_semi`] is what - /// says which kinds reach this; every other one prints its own `;` as - /// part of a body it does not own the end of. - fn semi(&self, before_semi: &[Comment]) -> Doc { - if before_semi.is_empty() { - return text(";"); - } - let mut docs = Vec::new(); - if self.inline_comments(before_semi, &mut docs) { - docs.push(Doc::HardLine); - } else { - docs.push(text(" ")); - } - docs.push(text(";")); - concat(docs) - } - - /// 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_comments, - label, - stmts, - dangling, - end_label_comments, - end_label, - .. - } => { - let mut docs = vec![prefix, text(" ")]; - docs.extend(self.leading_from(&s.meta, skip)); - docs.push(self.block_doc(BlockDoc { - label_comments, - label, - stmts, - dangling, - end_label_comments, - 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, &s.before_semi)); - body.extend(self.trailing(&s.meta)); - group(vec![prefix, indent(vec![Doc::Line, concat(body)])]) - } - } - } - - fn block_doc(&self, b: BlockDoc<'_>) -> Doc { - let mut docs = vec![text("begin")]; - self.label_tail(b.label, b.label_comments, &mut docs); - let mut body = Vec::new(); - if !b.stmts.is_empty() { - body.push(Doc::HardLine); - body.extend(self.stmt_seq(b.stmts)); - } - body.extend(self.dangling(b.dangling)); - docs.push(indent(body)); - docs.push(Doc::HardLine); - docs.push(self.closing_labeled("end", b.end_label, b.end_label_comments)); - concat(docs) - } - - fn timing_control(&self, tc: &TimingControl) -> Doc { - match tc { - TimingControl::Delay { after_hash, expr } => { - let mut docs = vec![text("#")]; - self.slot_comments(after_hash, &mut docs); - docs.push(self.expr(expr)); - concat(docs) - } - 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 { expr, after_at } => { - let mut docs = vec![text("@")]; - self.slot_comments(after_at, &mut docs); - docs.push(self.expr(expr)); - concat(docs) - } - 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, after_at } => { - // 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(e.clone())); - if i.after_edge.is_empty() { - parts.push(text(" ")); - } else { - self.inline_comments_spaced(&i.after_edge, &mut parts); - } - } - parts.push(self.expr(&i.expr)); - // `posedge clk iff enable` — the gate belongs to this - // term, so it prints before the separator, not after it. - if let Some(iff) = &i.iff { - parts.push(text(" iff ")); - parts.push(self.expr(iff)); - } - if self.inline_comments(&i.meta.before_sep, &mut parts) { - parts.push(Doc::HardLine); - } - } - let mut docs = vec![text("@")]; - self.slot_comments(after_at, &mut docs); - docs.push(text("(")); - docs.push(group(vec![indent(vec![Doc::SoftLine, concat(parts)]), Doc::SoftLine])); - docs.push(text(")")); - concat(docs) - } - } - } - - fn stmt_kind(&self, kind: &StmtKind, before_semi: &[Comment]) -> Doc { - match kind { - StmtKind::Block { - label_comments, - label, - stmts, - dangling, - end_label_comments, - end_label, - .. - } => self.block_doc(BlockDoc { - label_comments, - label, - stmts, - dangling, - end_label_comments, - end_label, - }), - StmtKind::ForkJoin { - label_comments, - label, - join_kw, - stmts, - dangling, - end_label_comments, - end_label, - .. - } => { - let mut docs = vec![text("fork")]; - self.label_tail(label, label_comments, &mut docs); - 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_labeled(join_kw, end_label, end_label_comments)); - concat(docs) - } - StmtKind::If { qualifier, after_kw, cond, then, else_comments, els } => { - self.if_stmt(qualifier, after_kw, cond, then, else_comments, els) - } - StmtKind::Case { qualifier, kw, after_kw, expr, inside, items, dangling } => { - let mut docs = Vec::new(); - if let Some(q) = qualifier { - docs.push(text(format!("{q} "))); - } - self.word_then(kw, after_kw, &mut docs); - let (parens, taken) = match items.first() { - Some(first) => self.header_parens(expr, &first.meta), - None => (self.parens(expr), 0), - }; - docs.push(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, comments, body } => { - let mut header = Vec::new(); - self.for_open(comments, &mut header); - 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); - if fi.before_name.is_empty() { - d.push(text(" ")); - } else { - self.inline_comments_spaced(&fi.before_name, &mut d); - } - } - } else { - self.slot_comments(&fi.before_name, &mut d); - } - self.simple_assign(&fi.assign, &mut d); - concat(d) - }) - .collect(); - header.extend(join(init_parts, text(", "))); - self.for_semi(&comments.before_first_semi, &comments.after_first_semi, &mut header); - if let Some(c) = cond { - header.push(self.expr(c)); - } - self.for_semi( - &comments.before_second_semi, - &comments.after_second_semi, - &mut header, - ); - let step_parts: Vec = step.iter().map(|s| self.for_step(s)).collect(); - header.extend(join(step_parts, text(", "))); - self.slot_comments(&comments.before_close, &mut header); - 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, comments } => { - let mut docs = vec![text("do")]; - match &body.kind { - StmtKind::Block { - label_comments, - label, - stmts, - dangling, - end_label_comments, - end_label, - .. - } => { - docs.push(text(" ")); - docs.push(self.block_doc(BlockDoc { - label_comments, - label, - stmts, - dangling, - end_label_comments, - end_label, - })); - docs.push(text(" ")); - self.word_then("while", &comments.after_kw, &mut docs); - } - _ => { - docs.push(group(vec![indent(vec![Doc::Line, self.stmt(body)])])); - docs.push(Doc::HardLine); - self.word_then("while", &comments.after_kw, &mut docs); - } - } - docs.push(self.header_slots(cond, comments)); - docs.push(self.semi(before_semi)); - 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, var_comments, comments, body } => { - let mut head = vec![text("foreach")]; - self.slot_comments(&comments.after_kw, &mut head); - if comments.after_kw.is_empty() { - head.push(text(" ")); - } - head.push(text("(")); - self.slot_comments(&comments.after_open, &mut head); - head.push(self.expr(target)); - head.push(self.foreach_vars(vars, var_comments)); - self.slot_comments(&comments.before_close, &mut head); - head.push(text(")")); - self.stmt_as_body(concat(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), self.semi(before_semi)]) - } - 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(self.semi(before_semi)); - 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, self.semi(before_semi)]), - } - } - 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), self.semi(before_semi)]), - }, - StmtKind::ExprStmt(e) => concat(vec![self.expr(e), self.semi(before_semi)]), - StmtKind::EventTrigger(e) => { - concat(vec![text("-> "), self.expr(e), self.semi(before_semi)]) - } - StmtKind::VarDecl(d) => concat(vec![self.data_decl(d), self.semi(before_semi)]), - // The item form prints its own `;`. - StmtKind::Typedef(t) => self.typedef(t), - StmtKind::ParamDecl(d) => { - concat(vec![self.param_decl(d, None), self.semi(before_semi)]) - } - StmtKind::PortDecl(d) => concat(vec![self.port_decl(d), self.semi(before_semi)]), - StmtKind::Return { after_kw, expr } => match expr { - Some(e) => { - let mut docs = Vec::new(); - self.word_then("return", after_kw, &mut docs); - docs.push(self.expr(e)); - docs.push(self.semi(before_semi)); - concat(docs) - } - None => concat(vec![text("return"), self.semi(before_semi)]), - }, - StmtKind::Break => concat(vec![text("break"), self.semi(before_semi)]), - StmtKind::Continue => concat(vec![text("continue"), self.semi(before_semi)]), - StmtKind::Disable(name) => { - concat(vec![text(format!("disable {}", named(name))), self.semi(before_semi)]) - } - StmtKind::WaitFork => concat(vec![text("wait fork"), self.semi(before_semi)]), - 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!("{}: ", named(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::Assertion(a) => self.assertion(a), - StmtKind::Assert { kw, cond, then, els } => { - let mut docs = vec![text(format!("{kw} ")), self.parens(cond)]; - match (then, els) { - (None, None) => docs.push(self.semi(before_semi)), - (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, - after_kw: &[Comment], - cond: &Expr, - then: &Stmt, - else_comments: &[Comment], - els: &Option>, - ) -> Doc { - let mut head = Vec::new(); - if let Some(q) = qualifier { - head.push(text(format!("{q} "))); - } - self.word_then("if", after_kw, &mut head); - let (parens, taken) = self.header_parens(cond, &then.meta); - head.push(parens); - let prefix = concat(head); - // 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, - after_kw: ea, - 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, ea, 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], before_colon: &[Comment], item: TextRange) -> Doc { - if labels.is_empty() { - if !self.default_has_colon(item) { - return text("default"); - } - let mut docs = vec![text("default")]; - self.slot_comments(before_colon, &mut docs); - docs.push(text(":")); - return concat(docs); - } - 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.before_colon, 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, - } - } - - /// True when a call's callee is a **macro name the source separated from - /// its `(`** — `` `WIDTH (a + b) ``, the expression-position spelling of - /// the `` `uvm_field_int (x, y) `` an item already keeps - /// (`Parser::at_spaced_macro_call`). - /// - /// The gap is data, not layout: `` `A (b) `` and `` `A(b) `` are one token - /// each, of *different text*, so closing it is a token rewrite the safety - /// net refuses — pinned in both directions by - /// `verification::{tightening,loosening}_a_*_macro_call_is_rejected`. And - /// lucisv cannot know which spelling was meant, because that depends on - /// whether the macro was defined with formals (IEEE 1800 §22.5.1), which - /// lives in a file this formatter does not read. - /// - /// The question is asked of `src` rather than of the AST for the reason - /// [`Fmt::glued_null_item`] gives: it is a fact about the gap between two - /// tokens, and this is the one place that gap is laid out. It is a fixed - /// point by construction — the printed gap is one space, which reads back - /// as a gap on the next pass. - fn spaced_macro_callee(&self, callee: &Expr) -> bool { - let ExprKind::Ident(name) = &callee.kind else { return false }; - name.starts_with('`') - && self - .src - .get(callee.span.end as usize..) - .and_then(|rest| rest.chars().next()) - .is_some_and(char::is_whitespace) - } - - fn expr(&self, e: &Expr) -> Doc { - match &e.kind { - ExprKind::Ident(s) => name_doc(s), - ExprKind::Number(s) => text(s.clone()), - ExprKind::Str(s) => text(s.clone()), - // Only reachable through `connection`, which handles the comments. - ExprKind::Empty(_) => text(""), - ExprKind::Unary { op, comments, expr } => { - let mut docs = vec![text(op.clone())]; - self.slot_comments(comments, &mut docs); - docs.push(self.expr(expr)); - concat(docs) - } - ExprKind::Binary { .. } => self.binary_chain(e), - ExprKind::Ternary { cond, then, els, comments } => { - if comments.is_empty() { - return group(vec![ - self.expr(cond), - indent(vec![ - Doc::Line, - text("? "), - self.expr(then), - Doc::Line, - text(": "), - self.expr(els), - ]), - ]); - } - self.ternary_with_comments(cond, then, els, comments) - } - ExprKind::Call { callee, args, comments } => { - let spaced = self.spaced_macro_callee(callee); - if comments.is_empty() { - let mut docs = vec![self.expr(callee)]; - if spaced { - docs.push(text(" ")); - } - docs.push(self.expr_list("(", args, ")")); - return concat(docs); - } - // A comment written around the brackets prints back between - // the same two tokens it was written between: after the - // callee, and inside the empty `()` that had nowhere else to - // put it. - let mut docs = vec![self.expr(callee)]; - if !comments.before_open.is_empty() { - self.inline_comments_spaced(&comments.before_open, &mut docs); - } else if spaced { - docs.push(text(" ")); - } - let items: Vec = - args.iter().map(|i| ListItem::from_meta(&i.meta, self.expr(&i.expr))).collect(); - docs.push(self.delimited_dangling("(", items, &comments.dangling, ")", false)); - concat(docs) - } - // `new src` — one space, never a break: the source handle is a - // postfix expression that breaks internally if it must. - ExprKind::New(src) => concat(vec![text("new "), self.expr(src)]), - ExprKind::Index { base, index, comments } => { - let mut docs = vec![self.expr(base)]; - self.slot_comments(&comments.before_open, &mut docs); - docs.push(self.bracket_slots(comments, self.expr_compact(index), None)); - concat(docs) - } - ExprKind::Range { base, op, msb, lsb, comments } => { - let mut docs = vec![self.expr(base)]; - self.slot_comments(&comments.before_open, &mut docs); - docs.push(self.bracket_slots( - comments, - self.expr_compact(msb), - Some((op, self.expr_compact(lsb))), - )); - concat(docs) - } - ExprKind::Member { base, name, comments } => { - self.chain_segment(base, ".", name, comments) - } - ExprKind::Scope { base, name, comments } => { - self.chain_segment(base, "::", name, comments) - } - // Written tight, like the `::` it almost always precedes. - ExprKind::Parameterized { base, params } => { - concat(vec![self.expr(base), self.raw_inline(params)]) - } - ExprKind::Concat(items) => self.expr_list("{", items, "}"), - ExprKind::Repl { count, inner } => concat(vec![ - text("{"), - self.expr(count), - self.expr_list("{", inner, "}"), - text("}"), - ]), - // `{<<8{v}}` — written tight, like a replication. - ExprKind::Stream { dir, slice, inner } => { - let mut docs = vec![text("{"), text(dir.clone())]; - if let Some(s) = slice { - docs.push(self.expr(s)); - } - docs.push(self.expr_list("{", inner, "}")); - docs.push(text("}")); - concat(docs) - } - ExprKind::Paren { inner, before, after } => { - if before.is_empty() && after.is_empty() { - return self.parens(inner); - } - let before: Vec<&Comment> = before.iter().collect(); - let after: Vec<&Comment> = after.iter().collect(); - self.paren_comments(inner, &before, &after) - } - // `ty'{...}` prints no brackets of its own: the assignment - // pattern already carries the `'{` and the `}`. - ExprKind::Cast { ty, comments, expr, pattern: true } => { - let mut docs = vec![self.expr(ty)]; - self.slot_comments(&comments.before_tick, &mut docs); - self.slot_comments(&comments.after_tick, &mut docs); - docs.push(self.expr(expr)); - concat(docs) - } - ExprKind::Cast { ty, comments, expr, .. } => { - if comments.is_empty() { - return concat(vec![self.expr(ty), text("'("), self.expr(expr), text(")")]); - } - let mut docs = vec![self.expr(ty)]; - self.slot_comments(&comments.before_tick, &mut docs); - docs.push(text("'")); - self.slot_comments(&comments.after_tick, &mut docs); - docs.push(text("(")); - self.slot_comments(&comments.after_open, &mut docs); - docs.push(self.expr(expr)); - self.slot_comments(&comments.before_close, &mut docs); - docs.push(text(")")); - concat(docs) - } - ExprKind::AssignPattern(items) => { - let items: Vec = items - .iter() - .map(|pi| { - let mut d = Vec::new(); - if let Some(k) = &pi.key { - d.push(self.expr(k)); - d.push(text(": ")); - } - d.push(self.expr(&pi.value)); - ListItem::from_meta(&pi.meta, concat(d)) - }) - .collect(); - self.delimited("'{", items, "}", false) - } - // `'{N{0}}` — written tight, like the `{N{0}}` it replicates. - ExprKind::AssignPatternRepl { count, inner } => concat(vec![ - text("'{"), - self.expr(count), - self.expr_list("{", inner, "}"), - text("}"), - ]), - ExprKind::Postfix { expr, op, comments } => { - let mut docs = vec![self.expr(expr)]; - self.slot_comments(comments, &mut docs); - docs.push(text(op.clone())); - concat(docs) - } - ExprKind::With { base, arg, comments } => { - concat(vec![self.with_head(base, comments), self.expr(arg)]) - } - ExprKind::WithConstraint { base, block, comments } => { - let body = match &**block { - ConstraintBody::Items(set) => self.with_constraint_block(set), - ConstraintBody::Verbatim(raw) => self.with_block(raw), - }; - concat(vec![self.with_head(base, comments), body]) - } - ExprKind::Dist { expr, comments, weights } => self.dist(expr, comments, weights), - ExprKind::Inside { lhs, ranges, comments } => { - self.inside_head(lhs, comments, self.expr_list("{", ranges, "}")) - } - ExprKind::InsideMacro { lhs, set, comments } => { - self.inside_head(lhs, comments, text(set.clone())) - } - // A named call argument, printed the way a named connection is: - // `.name(value)`, tight, with a break opportunity inside. - ExprKind::NamedArg { name, value, comments, .. } => match &value.kind { - ExprKind::Empty(inner) => { - let comments_inner = inner; - let mut docs = vec![text(".")]; - self.slot_comments(&comments.after_dot, &mut docs); - docs.push(text(named(name))); - self.slot_comments(&comments.before_open, &mut docs); - docs.push(text("(")); - self.slot_comments(&comments.after_open, &mut docs); - let comments = comments_inner; - let mut ends_line = false; - for cm in comments { - if ends_line { - docs.push(Doc::HardLine); - } - docs.push(self.comment(cm)); - ends_line = is_line_comment(&cm.text); - } - if ends_line { - docs.push(Doc::HardLine); - } - docs.push(text(")")); - concat(docs) - } - _ => { - let mut inner = vec![Doc::SoftLine, self.expr(value)]; - let ends_line = self.inline_comments(&comments.close, &mut inner); - let close = if ends_line { Doc::HardLine } else { Doc::SoftLine }; - let mut docs = vec![text(".")]; - self.slot_comments(&comments.after_dot, &mut docs); - docs.push(text(named(name))); - self.slot_comments(&comments.before_open, &mut docs); - docs.push(text("(")); - self.slot_comments(&comments.after_open, &mut docs); - docs.push(group(vec![indent(inner), close])); - docs.push(text(")")); - concat(docs) - } - }, - ExprKind::ValueRange { lo, hi, comments } => { - self.bracket_slots(comments, self.expr(lo), Some((":", self.expr(hi)))) - } - ExprKind::Type(ty) => self.data_type(ty).unwrap_or_else(|| text("")), - // Byte for byte, like every other verbatim leaf, and `Inline` - // rather than re-indented for the reason `raw_inline` gives: the - // region never begins its own line, so a dedent-by-column would - // drift instead of reaching a fixed point. - ExprKind::Verbatim(raw) => self.raw_inline(raw), - ExprKind::MinTypMax { min, typ, max } => { - concat(vec![self.expr(min), text(":"), self.expr(typ), text(":"), self.expr(max)]) - } - } - } - - /// The `[i, j]` of a `foreach` header — the one bracket group that - /// declares loop variables — with every comment written in it printed - /// back between the two tokens it was written between. - /// - /// Shared by the statement `foreach` and the constraint one, which write - /// the same grammar. - fn foreach_vars(&self, vars: &[ForeachVar], comments: &SegmentComments) -> Doc { - if comments.is_empty() && vars.iter().all(|v| v.before.is_empty() && v.after.is_empty()) { - let names: Vec = vars.iter().map(|v| v.name.clone()).collect(); - return text(format!("[{}]", join_names(&names))); - } - let mut docs = Vec::new(); - self.slot_comments(&comments.before_open, &mut docs); - docs.push(text("[")); - self.slot_comments(&comments.after_open, &mut docs); - for (i, v) in vars.iter().enumerate() { - if i > 0 { - docs.push(text(",")); - } - self.slot_comments(&v.before, &mut docs); - if i > 0 && v.before.is_empty() { - docs.push(text(" ")); - } - docs.push(text(named(&v.name.text))); - self.slot_comments(&v.after, &mut docs); - } - self.slot_comments(&comments.before_close, &mut docs); - docs.push(text("]")); - concat(docs) - } - - /// `base.name` / `base::name`, with the comments the source wrote on - /// either side of the joining token. - fn chain_segment( - &self, - base: &Expr, - joiner: &str, - name: &str, - comments: &SegmentComments, - ) -> Doc { - if comments.is_empty() { - return concat(vec![self.expr(base), text(format!("{joiner}{}", named(name)))]); - } - let mut docs = vec![self.expr(base)]; - self.slot_comments(&comments.before_open, &mut docs); - docs.push(text(joiner.to_string())); - self.slot_comments(&comments.after_open, &mut docs); - docs.push(text(named(name))); - concat(docs) - } - - /// `lhs inside set`, with the comments written on either side of the word - /// kept on their own side of it, as every binary operator's are. - fn inside_head(&self, lhs: &Expr, comments: &BinaryComments, set: Doc) -> Doc { - if comments.before.is_empty() && comments.after.is_empty() { - return concat(vec![self.expr(lhs), text(" inside "), set]); - } - let mut docs = vec![self.expr(lhs)]; - self.inline_comments_spaced(&comments.before, &mut docs); - docs.push(text("inside")); - self.inline_comments_spaced(&comments.after, &mut docs); - docs.push(set); - concat(docs) - } - - /// 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) - } -} - -/// `(weak0, pull1)`, or the single-strength `(weak1)` a pull gate may write. -fn drive_strength(s: &DriveStrength) -> String { - match &s.second { - Some(second) => format!("({}, {})", s.first, second), - None => format!("({})", s.first), - } -} - -/// A name, plus the space that terminates it when it is an escaped identifier. -/// -/// An escaped identifier runs from its `\` to the next **whitespace** -/// character and to nothing else (IEEE 1800-2017 §5.6.1), so `\my-signal;` -/// lexes as one identifier that swallows the `;`, and `.\my-port(x)` as one -/// that swallows the rest of the line. Every name this file writes goes -/// through here (or through [`name_doc`], its `Doc` twin): declarators, -/// ANSI and non-ANSI ports, parameters and their aligned cells, type names, -/// typedef/enum/genvar/`let` names, module, package, class, function, task, -/// modport and clocking names, instance and module-instance names, port -/// connections and named call arguments, `extends`, scopes, hierarchical -/// members, tf arguments, block/fork/statement labels, every `end : label`, -/// `disable`, and the `join_names`/`join_paths` lists. The audit that built -/// that list is a grep of `text(` and `format!(` over this file; a site that -/// grows a name later belongs on it. -/// -/// The space is unconditional. Where the layout already writes a separator -/// the output carries two (`logic \a = 1;`) — legal, a fixed point under -/// re-formatting, and cheaper than a second rule about what comes next. -/// True when any entry of a connection or override list carries a -/// **multi-line verbatim value** — a conditional region -/// ([`ExprKind::Verbatim`]). -/// -/// Such a value brings its own line breaks, which `Doc::Inline` copies -/// through without telling the enclosing group; without this the list would -/// be measured as one short line and flattened around a value that is -/// twenty lines tall. It is exactly the reason a list holding a -/// [`ListDirective`] is broken, for exactly the same construct. -fn holds_verbatim_value(list: &[Connection]) -> bool { - list.iter().any(|c| match &c.expr { - Some(Expr { kind: ExprKind::Verbatim(raw), .. }) => raw.text.contains('\n'), - _ => false, - }) -} - -fn named(s: &str) -> String { - if ends_escaped(s) { - format!("{s} ") - } else { - s.to_string() - } -} - -/// [`named`] as a `Doc`. -fn name_doc(s: &str) -> Doc { - text(named(s)) -} - -/// Whether `s` ends *inside* an escaped identifier, and so cannot be followed -/// directly by punctuation. -/// -/// Whitespace is the only terminator, so the question is exactly whether a -/// `\` survives in the run of characters after the last whitespace — which -/// also answers it for the composites the AST hands over already joined -/// (`a.\b`, `pkg::\x`). Conservative by construction: a false positive -/// writes one harmless extra space. `vlog_refactor::instantiate` carries the -/// same two-line rule for the skeletons it splices. -fn ends_escaped(s: &str) -> bool { - s.rsplit(char::is_whitespace).next().unwrap_or(s).contains('\\') -} - -/// 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| named(&n.text)).collect::>().join(", ") -} - -/// The same for a list of `pkg::item` import paths. -fn join_paths(paths: &[ImportPath]) -> String { - paths - .iter() - .map(|p| format!("{}::{}", named(&p.pkg.text), named(&p.item.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(&named(&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 -} diff --git a/crates/vlog_formatter/src/format/class.rs b/crates/vlog_formatter/src/format/class.rs new file mode 100644 index 0000000..eab69ff --- /dev/null +++ b/crates/vlog_formatter/src/format/class.rs @@ -0,0 +1,369 @@ +//! Classes and constraints: the `class` header and body, and every +//! constraint form — the `constraint c { ... }` declaration, a +//! `randomize() with { ... }` block, the `->`/`if`/`foreach`/`solve`/ +//! `unique` items, and the `dist` weight list an expression may end in. +//! +//! Covergroups, the other DV construct a class holds, are large enough +//! to be a sibling module (`cover.rs`). + +use crate::doc::*; +use crate::printer::contains_hard_line; +use vlog_parser::ast::*; +use vlog_parser::token::Comment; + +use super::list::ListItem; +use super::{join_names, named, Fmt}; + +impl<'a> Fmt<'a> { + /// A class: header on one line (its parameter and `extends` override + /// lists break like any other list when they do not fit), body items at + /// one more indent level, `endclass` with the label the source wrote. + pub(super) fn class(&self, c: &ClassDecl, depth: usize) -> Doc { + let mut docs = Vec::new(); + self.qualifier_run(&c.prefix, &mut docs); + docs.push(text("class")); + // `class /*c*/ c` — and, when a lifetime was written, whatever stood + // on either side of it; both gaps land in the one slot, which prints + // between the keyword run and the name. + if c.before_name.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&c.before_name, &mut docs); + } + if let Some(lifetime) = &c.lifetime { + docs.push(text(format!("{lifetime} "))); + } + docs.push(text(named(&c.name))); + let on_fresh_line = self.bracket_comments(&c.param_comments, &mut docs, false); + if let Some(params) = &c.param_ports { + let items: Vec = params + .iter() + .map(|p| ListItem::from_meta(&p.meta, self.param_port(p)).with_comma(p.comma)) + .collect(); + let items = self.list_entries(items, &c.param_directives); + let broken = !c.param_directives.is_empty(); + docs.push(text(if on_fresh_line { "#" } else { " #" })); + self.slot_comments(&c.param_after_hash, &mut docs); + docs.push(self.delimited_dangling("(", items, &c.param_dangling, ")", broken)); + } + if let Some(ext) = &c.extends { + docs.push(text(format!(" extends {}", named(&ext.name)))); + let fresh = self.bracket_comments(&ext.param_comments, &mut docs, false); + if let Some(params) = &ext.params { + let items: Vec = params + .iter() + .map(|p| ListItem::from_meta(&p.meta, self.connection(p)).with_comma(p.comma)) + .collect(); + let items = self.list_entries(items, &ext.param_directives); + let broken = !ext.param_directives.is_empty(); + docs.push(text(if fresh { "#" } else { " #" })); + self.slot_comments(&ext.after_hash, &mut docs); + docs.push(self.delimited("(", items, ")", broken)); + } + } + if !c.implements.is_empty() { + docs.push(text(format!(" implements {}", join_names(&c.implements)))); + } + docs.push(self.semi(&c.before_semi)); + let mut body = Vec::new(); + if !c.items.is_empty() { + body.push(Doc::HardLine); + body.extend(self.item_seq(&c.items, depth + 1)); + } + body.extend(self.dangling(&c.dangling)); + docs.push(indent(body)); + docs.push(Doc::HardLine); + docs.push(self.closing_labeled("endclass", &c.end_label, &c.end_label_comments)); + concat(docs) + } + + /// `[qualifiers ]constraint [cls::]name { ... }`, or the `constraint c;` + /// prototype. + /// + /// A named constraint is a *block*, so it is laid out like one: the + /// header keeps the `{`, every constraint item takes a line of its own at + /// one further indent, and the `}` closes back at the header's column. + /// That supersedes the `classes` README's "no layout convention worth + /// inventing" — there was none while the body was opaque bytes; now that + /// it is navigable, one canonical shape is worth exactly what canonical + /// shapes are always worth. + pub(super) fn constraint(&self, c: &ConstraintDecl) -> Doc { + let mut docs = Vec::new(); + self.qualifier_run(&c.qualifiers, &mut docs); + docs.push(text("constraint")); + self.inline_comments_spaced(&c.before_name, &mut docs); + self.scope_prefix(&c.scope, &mut docs); + let name = named(&c.name.text); + // `named` already wrote the space an escaped identifier needs; a + // second one would be a gratuitous re-spacing of the header. + let escaped = name.ends_with(' '); + docs.push(text(name)); + let ends_line = self.inline_comments(&c.after_name, &mut docs); + let Some(set) = &c.body else { + if ends_line { + docs.push(Doc::HardLine); + } + docs.push(text(";")); + return concat(docs); + }; + if ends_line { + docs.push(Doc::HardLine); + } else if !escaped || !c.after_name.is_empty() { + docs.push(text(" ")); + } + docs.push(self.constraint_block(set, false)); + if c.semi { + if self.inline_comments(&c.before_semi, &mut docs) { + docs.push(Doc::HardLine); + } + docs.push(text(";")); + } + concat(docs) + } + + /// The `{ ... }` of a constraint body or a nested constraint set. + /// + /// `flat_ok` allows the whole block onto one line when nothing inside it + /// forces a break — the shape a `randomize() with { addr == 0; }` is + /// written in. A `constraint` declaration never passes it: a declaration + /// is a block and reads as one. + fn constraint_block(&self, set: &ConstraintSet, flat_ok: bool) -> Doc { + let brk = if flat_ok { Doc::SoftLine } else { Doc::HardLine }; + let mut body = Vec::new(); + if !set.items.is_empty() { + body.push(brk.clone()); + body.extend(self.constraint_items(&set.items)); + } + body.extend(self.dangling(&set.dangling)); + if body.is_empty() { + return text("{}"); + } + group(vec![text("{"), indent(body), brk, text("}")]) + } + + /// The block of a `randomize() with { ... }`: the same layout, but kept on + /// the statement's line when the **source** wrote it on one line. + /// + /// A `with` block is written inside a statement, not standing as a + /// declaration, and `if (!req.randomize() with { addr == 0; })` is the + /// idiom every DV testbench writes. The question is asked of the source + /// rather than measured, for two reasons. It is a fact about the gap + /// between two tokens, which is the one thing the formatter already reads + /// `src` for (`glued_null_item`, `default_has_colon`). And it is a fixed + /// point by construction: a flattened block is one line, so the next pass + /// flattens it again; a broken one holds newlines, so the next pass + /// breaks it again. + /// + /// Reading the source also settles the `//` question for free: a line + /// comment needs a newline to end, so a one-line block cannot hold one, + /// and a flattened `}` can never land inside a comment. The + /// `contains_hard_line` check is the belt to that braces — anything else + /// that forces a break takes the block layout. + pub(super) fn with_constraint_block(&self, set: &ConstraintSet) -> Doc { + if self.src.get(set.span.as_range()).is_some_and(|s| !s.contains('\n')) { + let flat = self.constraint_block(set, true); + if !contains_hard_line(std::slice::from_ref(&flat)) { + return flat; + } + } + self.constraint_block(set, false) + } + + fn constraint_items(&self, items: &[ConstraintItem]) -> Vec { + let mut docs = Vec::new(); + for (i, item) in items.iter().enumerate() { + if i > 0 { + docs.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); + } + docs.push(self.with_meta(&item.meta, self.constraint_item(item))); + } + docs + } + + /// One constraint item, and the `;` that ends it when its kind takes one. + /// + /// The `;` is written here rather than in each arm so that the comments + /// the source wrote in front of it have exactly one place to be printed: + /// on the item's side of the separator, which is where they were + /// written. [`ConstraintItemKind::takes_semi`] is the one answer both + /// this and the parser read. + fn constraint_item(&self, item: &ConstraintItem) -> Doc { + let mut docs = vec![self.constraint_item_kind(&item.kind)]; + if item.kind.takes_semi() { + if self.inline_comments(&item.before_semi, &mut docs) { + docs.push(Doc::HardLine); + } + docs.push(text(";")); + } + concat(docs) + } + + fn constraint_item_kind(&self, kind: &ConstraintItemKind) -> Doc { + match kind { + ConstraintItemKind::Expr { soft, after_soft, expr } => { + if !*soft { + return self.expr(expr); + } + let mut docs = vec![text("soft")]; + self.inline_comments_spaced(after_soft, &mut docs); + docs.push(self.expr(expr)); + concat(docs) + } + ConstraintItemKind::Implication { cond, comments, set } => { + let mut head = vec![self.expr(cond)]; + self.inline_comments_spaced(&comments.before, &mut head); + head.push(text("->")); + let ends_line = self.inline_comments(&comments.after, &mut head); + if ends_line { + head.push(Doc::HardLine); + } + self.constraint_set_as_body(concat(head), set, &[], !ends_line) + } + ConstraintItemKind::If { cond, comments, then, else_comments, after_else, els } => { + let mut head = vec![text("if")]; + self.inline_comments_spaced(&comments.after_kw, &mut head); + head.push(self.constraint_parens(cond, comments)); + let mut docs = vec![self.constraint_set_as_body( + concat(head), + then, + &comments.before_body, + true, + )]; + let Some(els) = els else { return concat(docs) }; + // A braced `then` cuddles the `else` onto the `}` line, the + // way a statement `if` cuddles it onto `end`. + docs.push(if then.braced { text(" ") } else { Doc::HardLine }); + for c in else_comments { + docs.push(self.comment(c)); + docs.push(Doc::HardLine); + } + // `else if` chains on one line, the way a statement `if` does: + // an unbraced else holding exactly one `if` is the chain, and + // indenting it once per link would stair-step the whole thing + // off the right of the page. + match Self::chained_if(els) { + Some(item) => { + let mut chain = vec![text("else")]; + self.inline_comments_spaced(after_else, &mut chain); + chain.push(self.with_meta(&item.meta, self.constraint_item(item))); + docs.push(concat(chain)); + } + None => { + docs.push(self.constraint_set_as_body(text("else"), els, after_else, true)) + } + } + concat(docs) + } + ConstraintItemKind::Foreach { array, vars, var_comments, comments, set } => { + let mut head = vec![text("foreach")]; + self.inline_comments_spaced(&comments.after_kw, &mut head); + head.push(text("(")); + self.inline_comments(&comments.after_open, &mut head); + if !comments.after_open.is_empty() { + head.push(text(" ")); + } + head.push(self.expr(array)); + head.push(self.foreach_vars(vars, var_comments)); + if self.inline_comments(&comments.before_close, &mut head) { + head.push(Doc::HardLine); + } else if !comments.before_close.is_empty() { + head.push(text(" ")); + } + head.push(text(")")); + self.constraint_set_as_body(concat(head), set, &comments.before_body, true) + } + ConstraintItemKind::SolveBefore { solve, before_comments, before } => { + let mut docs = vec![text("solve "), self.plain_expr_list(solve)]; + self.inline_comments_spaced(before_comments, &mut docs); + docs.push(text("before ")); + docs.push(self.plain_expr_list(before)); + concat(docs) + } + ConstraintItemKind::Unique { items, comments } => { + let mut docs = vec![text("unique")]; + self.inline_comments_spaced(comments, &mut docs); + docs.push(self.expr_list("{", items, "}")); + concat(docs) + } + ConstraintItemKind::DisableSoft { expr, comments } => { + let mut docs = vec![text("disable")]; + self.inline_comments_spaced(&comments.before, &mut docs); + docs.push(text("soft")); + self.inline_comments_spaced(&comments.after, &mut docs); + docs.push(self.expr(expr)); + concat(docs) + } + ConstraintItemKind::Directive(raw) => self.raw_text(raw), + ConstraintItemKind::Empty => text(";"), + } + } + + /// The `( cond )` of a constraint `if`, with the comments written just + /// inside either parenthesis printed back where they were written. + fn constraint_parens(&self, cond: &Expr, comments: &HeaderComments) -> Doc { + self.guard_parens(cond, &comments.after_open, &comments.before_close) + } + + /// The `if` an `else` chains straight onto: the single item of an + /// unbraced `else` set, when that item is itself an `if`. + fn chained_if(set: &ConstraintSet) -> Option<&ConstraintItem> { + if set.braced || set.items.len() != 1 { + return None; + } + let item = set.items.first()?; + matches!(item.kind, ConstraintItemKind::If { .. }).then_some(item) + } + + /// A header followed by a constraint set: a braced set cuddles onto the + /// header line, an unbraced one goes on the same line if it fits and on + /// an indented next line if it does not — exactly what + /// [`Fmt::stmt_as_body`] does for statements. + fn constraint_set_as_body( + &self, + head: Doc, + set: &ConstraintSet, + before: &[Comment], + space: bool, + ) -> Doc { + if set.braced { + let mut docs = vec![head]; + if self.inline_comments(before, &mut docs) { + docs.push(Doc::HardLine); + } else if space || !before.is_empty() { + docs.push(text(" ")); + } + docs.push(self.constraint_block(set, false)); + return concat(docs); + } + let body = match set.items.first() { + Some(item) => self.with_meta(&item.meta, self.constraint_item(item)), + None => text(""), + }; + group(vec![head, indent(vec![Doc::Line, body])]) + } + + /// `expr dist { 0 := 5, [1:20] :/ 20 }` — the weight list laid out like + /// every other braced list: one per line when it does not fit. `:=` and + /// `:/` are printed back exactly as written; they mean different things. + pub(super) fn dist(&self, expr: &Expr, comments: &BinaryComments, weights: &[DistItem]) -> Doc { + let items: Vec = weights + .iter() + .map(|w| { + let mut docs = vec![self.expr(&w.value)]; + if let (Some(op), Some(weight)) = (&w.op, &w.weight) { + self.inline_comments_spaced(&w.op_comments.before, &mut docs); + docs.push(text(op.clone())); + self.inline_comments_spaced(&w.op_comments.after, &mut docs); + docs.push(self.expr(weight)); + } + ListItem::from_meta(&w.meta, concat(docs)) + }) + .collect(); + let mut docs = vec![self.expr(expr)]; + self.inline_comments_spaced(&comments.before, &mut docs); + docs.push(text("dist")); + self.inline_comments_spaced(&comments.after, &mut docs); + docs.push(self.delimited("{", items, "}", false)); + concat(docs) + } +} diff --git a/crates/vlog_formatter/src/format/comment.rs b/crates/vlog_formatter/src/format/comment.rs new file mode 100644 index 0000000..0ebe699 --- /dev/null +++ b/crates/vlog_formatter/src/format/comment.rs @@ -0,0 +1,301 @@ +//! Where a comment prints relative to the tokens around it: the leading +//! and trailing comments a node owns (`Meta`), the comments written in a +//! construct's own gaps (`slot_comments`, `inline_comments`), the ones +//! just inside a pair of parentheses, and the dangling comments a body +//! ends with. +//! +//! Every construct in the sibling modules spells its comment slots through +//! these few functions, which is what makes "comments are never dropped +//! and never cross a token" a property of one file rather than of every +//! arm of every match. + +use crate::doc::*; +use vlog_parser::ast::*; +use vlog_parser::token::Comment; + +use super::skip_trivia; +use super::verbatim::Slot; +use super::Fmt; + +impl<'a> Fmt<'a> { + /// A comment, ready to be re-indented at the printer's current level. + pub(super) fn comment(&self, c: &Comment) -> Doc { + self.raw_lines(&c.text, c.col) + } + + /// 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. + pub(super) 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. + pub(super) 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`]. + pub(super) 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); + } + + pub(super) 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. + pub(super) 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. + pub(super) fn inline_comments_spaced(&self, comments: &[Comment], docs: &mut Vec) { + if self.inline_comments(comments, docs) { + docs.push(Doc::HardLine); + } else { + docs.push(text(" ")); + } + } + + /// One named comment slot between two tokens the caller emits either side + /// of it, spaced off both — and a no-op when the slot is empty, so a + /// construct with no comment in it is laid out exactly as it was before + /// the slot existed. + /// + /// This is what every slot of [`SegmentComments`] is printed with, and it + /// is why the empty case of a `.`, a `::` or a `[` costs nothing. + pub(super) fn slot_comments(&self, comments: &[Comment], docs: &mut Vec) { + if comments.is_empty() { + return; + } + self.inline_comments_spaced(comments, docs); + } + + /// 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. + pub(super) 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 + } + + pub(super) 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) + } + + pub(super) 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 + } + + /// `( expr )` with break opportunity inside. + pub(super) 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. + pub(super) 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) + } + + /// `( cond )` with the comments a header kept in its own slots. The + /// `after_kw` half is written by the caller, which owns the keyword. + pub(super) fn header_slots(&self, cond: &Expr, comments: &HeaderComments) -> Doc { + if comments.after_open.is_empty() && comments.before_close.is_empty() { + return self.parens(cond); + } + let before: Vec<&Comment> = comments.after_open.iter().collect(); + let after: Vec<&Comment> = comments.before_close.iter().collect(); + self.paren_comments(cond, &before, &after) + } + + /// `( expr )` with whatever was written just inside either parenthesis: + /// a constraint `if`'s condition, a covergroup `iff` guard, a bin's + /// `with ( ... )` filter. One place, so the three cannot drift apart. + pub(super) fn guard_parens( + &self, + e: &Expr, + after_open: &[Comment], + before_close: &[Comment], + ) -> Doc { + if after_open.is_empty() && before_close.is_empty() { + return self.parens(e); + } + let before: Vec<&Comment> = after_open.iter().collect(); + let after: Vec<&Comment> = before_close.iter().collect(); + self.paren_comments(e, &before, &after) + } + + /// 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. + pub(super) 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 for `// ...` comments, which must end their line. +pub(super) fn is_line_comment(text: &str) -> bool { + text.starts_with("//") +} + +/// 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. +pub(super) 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)), + } +} diff --git a/crates/vlog_formatter/src/format/cover.rs b/crates/vlog_formatter/src/format/cover.rs new file mode 100644 index 0000000..65210d7 --- /dev/null +++ b/crates/vlog_formatter/src/format/cover.rs @@ -0,0 +1,418 @@ +//! Covergroups: the `covergroup` header with its sampling event, the +//! coverpoint and cross items, bins with their value, transition and +//! `binsof` specs, and `option`/`type_option` assignments. +//! +//! Its own file rather than a tail of `class.rs` because a covergroup is +//! the one DV construct with a grammar of its own — bins, transitions, +//! crosses, options — and the two together would be over 800 lines. + +use crate::doc::*; +use vlog_parser::ast::*; +use vlog_parser::token::Comment; + +use super::{name_doc, Fmt}; + +impl<'a> Fmt<'a> { + /// `covergroup g (args) with function sample (args); ... endgroup : g`. + /// + /// A covergroup is a block, so it is laid out like one: the whole header + /// on the header line, every cover item on a line of its own at one + /// further indent, and `endgroup` back at the header's column with + /// whatever label the source wrote. + pub(super) fn covergroup(&self, c: &CovergroupDecl) -> Doc { + let mut docs = Vec::new(); + self.qualifier_run(&c.qualifiers, &mut docs); + docs.push(text("covergroup")); + self.inline_comments_spaced(&c.before_name, &mut docs); + docs.push(name_doc(&c.name.text)); + if let Some(args) = &c.args { + if !c.before_args.is_empty() { + self.inline_comments_spaced(&c.before_args, &mut docs); + } + docs.push(self.tf_args(args, &[])); + } + match &c.event { + Some(CoverageEvent::Sample(s)) => { + self.inline_comments_spaced(&s.before_with, &mut docs); + docs.push(text("with")); + self.inline_comments_spaced(&s.after_with, &mut docs); + docs.push(text("function")); + self.inline_comments_spaced(&s.after_function, &mut docs); + docs.push(name_doc(&s.name.text)); + if s.has_parens { + if !s.before_args.is_empty() { + self.inline_comments_spaced(&s.before_args, &mut docs); + } + docs.push(self.tf_args(&s.args, &[])); + } + } + Some(CoverageEvent::Clocking { before, sens }) => { + self.inline_comments_spaced(before, &mut docs); + docs.push(self.sens_list(sens)); + } + None => {} + } + if self.inline_comments(&c.before_semi, &mut docs) { + docs.push(Doc::HardLine); + } + docs.push(text(";")); + let mut body = Vec::new(); + if !c.items.is_empty() { + body.push(Doc::HardLine); + body.extend(self.cover_items(&c.items)); + } + body.extend(self.dangling(&c.dangling)); + docs.push(indent(body)); + docs.push(Doc::HardLine); + let end_label = c.end_label.as_ref().map(|l| l.text.clone()); + docs.push(self.closing_labeled("endgroup", &end_label, &c.end_label_comments)); + if c.end_semi { + if self.inline_comments(&c.before_end_semi, &mut docs) { + docs.push(Doc::HardLine); + } + docs.push(text(";")); + } + concat(docs) + } + + pub(super) fn cover_items(&self, items: &[CoverItem]) -> Vec { + let mut docs = Vec::new(); + for (i, item) in items.iter().enumerate() { + if i > 0 { + docs.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); + } + docs.push(self.with_meta(&item.meta, self.cover_item(item))); + } + docs + } + + /// One cover item, and the `;` that ends it when its kind takes one — the + /// rule [`CoverItemKind::takes_semi`] is the single answer to, read here + /// and by the parser that consumed it. + fn cover_item(&self, item: &CoverItem) -> Doc { + let mut docs = vec![self.cover_item_kind(&item.kind)]; + if item.kind.takes_semi() { + if self.inline_comments(&item.before_semi, &mut docs) { + docs.push(Doc::HardLine); + } + docs.push(text(";")); + } + concat(docs) + } + + fn cover_item_kind(&self, kind: &CoverItemKind) -> Doc { + match kind { + CoverItemKind::Coverpoint(cp) => { + let mut head = Vec::new(); + self.cover_label(&cp.label, &mut head); + head.push(text("coverpoint")); + self.inline_comments_spaced(&cp.after_kw, &mut head); + head.push(self.expr(&cp.expr)); + self.cover_iff(&cp.iff, &mut head); + self.cover_body_as_body(concat(head), &cp.before_body, &cp.body) + } + CoverItemKind::Cross(cr) => { + let mut head = Vec::new(); + self.cover_label(&cr.label, &mut head); + head.push(text("cross")); + self.inline_comments_spaced(&cr.after_kw, &mut head); + head.push(self.plain_expr_list(&cr.items)); + self.cover_iff(&cr.iff, &mut head); + self.cover_body_as_body(concat(head), &cr.before_body, &cr.body) + } + CoverItemKind::Option(o) => self.option_assign(o), + CoverItemKind::Directive(raw) => self.raw_text(raw), + CoverItemKind::Empty => text(";"), + } + } + + /// The `name :` a coverpoint or a cross may be labelled with. + fn cover_label(&self, label: &Option, docs: &mut Vec) { + let Some(l) = label else { return }; + docs.push(name_doc(&l.name.text)); + if self.inline_comments(&l.comments.before, docs) { + docs.push(Doc::HardLine); + } + docs.push(text(":")); + self.inline_comments_spaced(&l.comments.after, docs); + } + + /// The ` iff ( expr )` guard of a coverpoint, a cross or a bin. + fn cover_iff(&self, iff: &Option>, docs: &mut Vec) { + let Some(i) = iff else { return }; + self.inline_comments_spaced(&i.before_kw, docs); + docs.push(text("iff")); + self.inline_comments_spaced(&i.after_kw, docs); + docs.push(self.guard_parens(&i.expr, &i.after_open, &i.before_close)); + } + + /// A coverpoint or cross header followed by its `{ bins }` body, or by + /// nothing at all — a body-less one ends in the `;` [`Fmt::cover_item`] + /// writes. + fn cover_body_as_body(&self, head: Doc, before: &[Comment], body: &Option) -> Doc { + let Some(body) = body else { return head }; + let mut docs = vec![head]; + if self.inline_comments(before, &mut docs) { + docs.push(Doc::HardLine); + } else { + docs.push(text(" ")); + } + docs.push(self.cover_block(body)); + concat(docs) + } + + /// The `{ ... }` of a coverpoint or cross body: one bin per line at one + /// further indent, the `}` back at the header's column — a constraint + /// set's layout, for a construct that reads the same way. + fn cover_block(&self, body: &CoverBody) -> Doc { + let mut inner = Vec::new(); + if !body.items.is_empty() { + inner.push(Doc::HardLine); + inner.extend(self.bin_items(&body.items)); + } + inner.extend(self.dangling(&body.dangling)); + if inner.is_empty() { + return text("{}"); + } + group(vec![text("{"), indent(inner), Doc::HardLine, text("}")]) + } + + fn bin_items(&self, items: &[BinItem]) -> Vec { + let mut docs = Vec::new(); + for (i, item) in items.iter().enumerate() { + if i > 0 { + docs.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); + } + docs.push(self.with_meta(&item.meta, self.bin_item(item))); + } + docs + } + + fn bin_item(&self, item: &BinItem) -> Doc { + let mut docs = vec![match &item.kind { + BinItemKind::Bin(b) => self.bin_decl(b), + BinItemKind::Option(o) => self.option_assign(o), + BinItemKind::Directive(raw) => self.raw_text(raw), + BinItemKind::Empty => text(";"), + }]; + if item.kind.takes_semi() { + if self.inline_comments(&item.before_semi, &mut docs) { + docs.push(Doc::HardLine); + } + docs.push(text(";")); + } + concat(docs) + } + + /// `option.per_instance = 1` / `type_option.weight = 5`. + fn option_assign(&self, o: &OptionAssign) -> Doc { + let mut docs = vec![self.expr(&o.target)]; + if self.inline_comments(&o.comments.before, &mut docs) { + docs.push(Doc::HardLine); + } else { + docs.push(text(" ")); + } + docs.push(text("=")); + self.inline_comments_spaced(&o.comments.after, &mut docs); + docs.push(self.expr(&o.value)); + concat(docs) + } + + /// `[wildcard ]bins name[4] = spec [with (expr)] [iff (expr)]`. + fn bin_decl(&self, b: &BinDecl) -> Doc { + let mut docs = Vec::new(); + if b.wildcard { + docs.push(text("wildcard")); + self.inline_comments_spaced(&b.after_wildcard, &mut docs); + } + docs.push(text(b.kind.as_str())); + self.inline_comments_spaced(&b.before_name, &mut docs); + docs.push(name_doc(&b.name.text)); + if let Some(a) = &b.array { + if !a.before.is_empty() { + self.inline_comments_spaced(&a.before, &mut docs); + } + docs.push(text("[")); + self.inline_comments(&a.comments.before, &mut docs); + if !a.comments.before.is_empty() { + docs.push(text(" ")); + } + if let Some(size) = &a.size { + docs.push(self.expr(size)); + } + if self.inline_comments(&a.comments.after, &mut docs) { + docs.push(Doc::HardLine); + } else if !a.comments.after.is_empty() { + docs.push(text(" ")); + } + docs.push(text("]")); + } + if self.inline_comments(&b.eq_comments.before, &mut docs) { + docs.push(Doc::HardLine); + } else { + docs.push(text(" ")); + } + docs.push(text("=")); + self.inline_comments_spaced(&b.eq_comments.after, &mut docs); + docs.push(self.bin_spec(&b.spec)); + if let Some(w) = &b.with_expr { + self.inline_comments_spaced(&w.before_kw, &mut docs); + docs.push(text("with")); + self.inline_comments_spaced(&w.after_kw, &mut docs); + docs.push(self.guard_parens(&w.expr, &w.after_open, &w.before_close)); + } + self.cover_iff(&b.iff, &mut docs); + concat(docs) + } + + fn bin_spec(&self, spec: &BinSpec) -> Doc { + match spec { + BinSpec::Values(items) => self.expr_list("{", items, "}"), + BinSpec::Transitions(sets) => self.trans_list(sets), + BinSpec::Default => text("default"), + BinSpec::DefaultSequence { comments } => { + let mut docs = vec![text("default")]; + self.inline_comments_spaced(comments, &mut docs); + docs.push(text("sequence")); + concat(docs) + } + BinSpec::Select(s) => self.select_expr(s), + } + } + + /// `(a => b), (c => d)` — the transition sets of a transition bin, joined + /// by the commas the source wrote. + fn trans_list(&self, sets: &[TransSet]) -> Doc { + self.plain_list(sets.iter().map(|s| (&s.meta, self.trans_set(s))).collect()) + } + + fn trans_set(&self, set: &TransSet) -> Doc { + let mut docs = vec![text("(")]; + for (i, r) in set.ranges.iter().enumerate() { + if i > 0 { + if self.inline_comments(&r.arrow_comments.before, &mut docs) { + docs.push(Doc::HardLine); + } else { + docs.push(text(" ")); + } + docs.push(text("=>")); + self.inline_comments_spaced(&r.arrow_comments.after, &mut docs); + } + docs.push(self.trans_range(r)); + } + if self.inline_comments(&set.dangling, &mut docs) { + docs.push(Doc::HardLine); + } else if !set.dangling.is_empty() { + docs.push(text(" ")); + } + docs.push(text(")")); + concat(docs) + } + + fn trans_range(&self, r: &TransRange) -> Doc { + let mut docs = vec![self.plain_expr_list(&r.items)]; + let Some(rep) = &r.repeat else { return concat(docs) }; + if !rep.before.is_empty() { + self.inline_comments_spaced(&rep.before, &mut docs); + } + docs.push(text("[")); + self.inline_comments(&rep.after_open, &mut docs); + if !rep.after_open.is_empty() { + docs.push(text(" ")); + } + docs.push(text(rep.op.clone())); + self.inline_comments(&rep.comments.before, &mut docs); + if !rep.comments.before.is_empty() { + docs.push(text(" ")); + } + docs.push(self.expr(&rep.lo)); + if let Some(hi) = &rep.hi { + self.inline_comments(&rep.colon_comments.before, &mut docs); + if !rep.colon_comments.before.is_empty() { + docs.push(text(" ")); + } + docs.push(text(":")); + self.inline_comments(&rep.colon_comments.after, &mut docs); + if !rep.colon_comments.after.is_empty() { + docs.push(text(" ")); + } + docs.push(self.expr(hi)); + } + if self.inline_comments(&rep.comments.after, &mut docs) { + docs.push(Doc::HardLine); + } else if !rep.comments.after.is_empty() { + docs.push(text(" ")); + } + docs.push(text("]")); + concat(docs) + } + + /// `binsof(a) intersect {0} && !binsof(b)` — a cross bin's select + /// expression, and the bare coverpoint name a coverpoint bin may name. + fn select_expr(&self, s: &SelectExpr) -> Doc { + match s { + SelectExpr::Binsof(b) => { + let mut docs = vec![text("binsof")]; + if !b.after_kw.is_empty() { + self.inline_comments_spaced(&b.after_kw, &mut docs); + } + docs.push(text("(")); + self.inline_comments(&b.after_open, &mut docs); + if !b.after_open.is_empty() { + docs.push(text(" ")); + } + docs.push(self.expr(&b.name)); + if self.inline_comments(&b.before_close, &mut docs) { + docs.push(Doc::HardLine); + } else if !b.before_close.is_empty() { + docs.push(text(" ")); + } + docs.push(text(")")); + if let Some(items) = &b.intersect { + self.inline_comments_spaced(&b.before_intersect, &mut docs); + docs.push(text("intersect")); + self.inline_comments_spaced(&b.after_intersect, &mut docs); + docs.push(self.expr_list("{", items, "}")); + } + concat(docs) + } + SelectExpr::Not { comments, expr } => { + let mut docs = vec![text("!")]; + if !comments.is_empty() { + self.inline_comments(comments, &mut docs); + docs.push(text(" ")); + } + docs.push(self.select_expr(expr)); + concat(docs) + } + SelectExpr::Binary { lhs, op, comments, rhs } => { + let mut docs = vec![self.select_expr(lhs)]; + if self.inline_comments(&comments.before, &mut docs) { + docs.push(Doc::HardLine); + } else { + docs.push(text(" ")); + } + docs.push(text(op.clone())); + self.inline_comments_spaced(&comments.after, &mut docs); + docs.push(self.select_expr(rhs)); + concat(docs) + } + SelectExpr::Paren { comments, expr } => { + let mut docs = vec![text("(")]; + self.inline_comments(&comments.before, &mut docs); + if !comments.before.is_empty() { + docs.push(text(" ")); + } + docs.push(self.select_expr(expr)); + if self.inline_comments(&comments.after, &mut docs) { + docs.push(Doc::HardLine); + } else if !comments.after.is_empty() { + docs.push(text(" ")); + } + docs.push(text(")")); + concat(docs) + } + SelectExpr::Expr(e) => self.expr(e), + } + } +} diff --git a/crates/vlog_formatter/src/format/decl.rs b/crates/vlog_formatter/src/format/decl.rs new file mode 100644 index 0000000..4fe756e --- /dev/null +++ b/crates/vlog_formatter/src/format/decl.rs @@ -0,0 +1,452 @@ +//! Declarations and the types they name: a `DataType` with its packed +//! dimensions, unpacked dimensions, the declarator list of a +//! `logic a, b = 1;`, `parameter`/`localparam` and their alignment, +//! `typedef`, and `enum`/`struct` bodies. +//! +//! An expression inside a dimension is printed by `expr_compact`, which +//! belongs to the expression module; only the brackets are this one's. + +use crate::align::{self, Align, ColSpec, Row}; +use crate::doc::*; +use vlog_parser::ast::*; + +use super::comment::is_line_comment; +use super::list::ListItem; +use super::{name_doc, Fmt}; + +/// 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 }]; + +impl<'a> Fmt<'a> { + /// Format a data type; `None` if fully implicit. + pub(super) 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(name_doc(&ty.name)); + 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() { + // A dimension that opens with a comment writes its own space. + if need_space && ty.packed[0].comments.opens_clean() { + 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)) + } + + pub(super) fn dim(&self, d: &Dim) -> Doc { + let c = &d.comments; + let brackets = match &d.kind { + DimKind::Range { a, b } => { + let rest = b.as_ref().map(|b| (":", self.expr_compact(b))); + self.bracket_slots(c, self.expr_compact(a), rest) + } + // `[]` and `[*]` have no operand, so the one inner slot they own + // is the gap before the `]`, which is where `parse_dims` puts + // anything written between the brackets. + DimKind::Dynamic => self.bracket_slots(c, text(""), None), + DimKind::Wildcard => self.bracket_slots(c, text("*"), None), + }; + if c.opens_clean() { + return brackets; + } + // `logic /*c*/ [3:0]` — the gap before the `[` belongs to the + // dimension, since nothing to its left has a slot for it. The space + // in front is the dimension's own: a caller that would have written + // one asks [`SegmentComments::opens_clean`] and leaves it out. + let mut docs = Vec::new(); + self.inline_comments_spaced(&c.before_open, &mut docs); + docs.push(brackets); + concat(docs) + } + + pub(super) fn unpacked_dims(&self, dims: &[Dim]) -> Vec { + let mut docs = Vec::new(); + if !dims.is_empty() { + if dims[0].comments.opens_clean() { + 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![name_doc(&d.name)]; + docs.extend(self.unpacked_dims(&d.unpacked)); + if let Some(init) = &d.init { + self.slot_comments(&d.eq_comments.before, &mut docs); + docs.push(text(if d.eq_comments.before.is_empty() { " =" } else { "=" })); + if d.eq_comments.after.is_empty() { + docs.push(group(vec![self.assign_rhs(self.expr(init))])); + } else { + self.inline_comments_spaced(&d.eq_comments.after, &mut docs); + docs.push(group(vec![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. + pub(super) 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::new(); + self.word_then(&d.kw, &d.after_kw, &mut docs); + 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![name_doc(&decl.name)]; + name.extend(self.unpacked_dims(&decl.unpacked)); + vec![ + concat(prefix), + concat(name), + concat(vec![text("="), group(vec![self.assign_rhs(self.expr(init))])]), + ] + } + + /// The alignment plan for the `parameter`/`localparam` declarations among + /// a run of module (or package, or class) items. + pub(super) 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() + // A comment after the keyword makes this row a width no other row + // shares, so it never joins an alignment group. + || !d.after_kw.is_empty() + { + 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) + } + + pub(super) 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(" ")); + } + self.qualifier_run(&d.qualifiers, &mut docs); + if let Some(t) = self.data_type(&d.ty) { + docs.push(t); + docs.push(text(" ")); + } + docs.push(self.declarators(&d.declarators)); + concat(docs) + } + + pub(super) 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) + } + + pub(super) fn typedef(&self, t: &Typedef) -> Doc { + let mut docs = Vec::new(); + self.word_then("typedef", &t.after_kw, &mut docs); + let base = match &t.kind { + TypedefKind::ForwardClass => Some(text("class")), + TypedefKind::Alias(ty) => self.data_type(ty), + TypedefKind::Enum(e) => Some(self.enum_type(e)), + TypedefKind::Struct(s) => Some(self.struct_type(s)), + }; + match base { + Some(d) => { + docs.push(d); + if t.before_name.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&t.before_name, &mut docs); + } + } + None => self.slot_comments(&t.before_name, &mut docs), + } + docs.push(name_doc(&t.name)); + docs.extend(self.unpacked_dims(&t.unpacked)); + docs.push(self.semi(&t.before_semi)); + concat(docs) + } + + /// `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")]; + let mut spaced = false; + if !e.after_kw.is_empty() { + self.inline_comments_spaced(&e.after_kw, &mut docs); + spaced = true; + } + if let Some(base) = &e.base { + if let Some(d) = self.data_type(base) { + if !spaced { + docs.push(text(" ")); + } + docs.push(d); + spaced = false; + } + } + if e.before_open.is_empty() { + if !spaced { + docs.push(text(" ")); + } + } else { + self.inline_comments_spaced(&e.before_open, &mut docs); + } + let items = self.list_entries(self.enum_member_items(&e.members), &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) + } + + /// One list entry per enum member. Shared by the `enum { ... }` body and + /// by an enum-member fragment, so the two lay a member out identically. + pub(super) fn enum_member_items(&self, members: &[EnumMember]) -> Vec { + members + .iter() + .map(|m| { + let mut d = vec![name_doc(&m.name)]; + // Tight against the name: `OtbnDmem[16]` is one enum name + // range, not a name with a dimension beside it. + d.extend(m.range.iter().map(|r| self.dim(r))); + if let Some(v) = &m.value { + self.slot_comments(&m.eq_comments.before, &mut d); + d.push(text(if m.eq_comments.before.is_empty() { " =" } else { "=" })); + if m.eq_comments.after.is_empty() { + d.push(text(" ")); + } else { + self.inline_comments_spaced(&m.eq_comments.after, &mut d); + } + d.push(self.expr(v)); + } + ListItem::from_meta(&m.meta, concat(d)).with_comma(m.comma) + }) + .collect() + } + + /// `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 c = &s.header_comments; + // `union tagged packed`, in the LRM's order, each word followed by + // whatever the source wrote after it. + let mut head = Vec::new(); + self.word_then(&s.kw, &c.after_kw, &mut head); + if s.tagged { + self.word_then("tagged", &c.after_tagged, &mut head); + } + if s.packed { + self.word_then("packed", &c.after_packed, &mut head); + } + if let Some(sig) = &s.signing { + self.word_then(sig, &c.after_signing, &mut head); + } + head.push(text("{")); + 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(); + self.qualifier_run(&m.qualifiers, &mut d); + 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![concat(head), indent(inner), Doc::HardLine, text("}")]) + } +} diff --git a/crates/vlog_formatter/src/format/expr.rs b/crates/vlog_formatter/src/format/expr.rs new file mode 100644 index 0000000..9d8af3e --- /dev/null +++ b/crates/vlog_formatter/src/format/expr.rs @@ -0,0 +1,481 @@ +//! Expressions: the dispatch from `ExprKind` to its layout, the binary +//! chain that breaks `a + b + c` as one unit, the ternary with comments +//! inside it, the compact spelling used inside `[ ... ]`, and the small +//! postfix forms (`base.name`, `base::name`, `lhs inside {…}`, `with`). +//! +//! `expr` is a dispatch table over `ExprKind` and stays whole; the +//! helpers after it are the arms that grew a shape of their own. + +use crate::doc::*; +use vlog_parser::ast::*; +use vlog_parser::token::Comment; + +use super::comment::is_line_comment; +use super::list::ListItem; +use super::{name_doc, named, Fmt}; + +/// One operator of a flattened binary chain, with the comments written on +/// either side of it. +struct BinaryOp<'e> { + op: &'e str, + before: &'e [Comment], + after: &'e [Comment], +} + +impl<'a> Fmt<'a> { + fn binary_prec(op: &str) -> u8 { + match op { + "||" => 1, + "&&" => 2, + "|" => 3, + "^" | "^~" | "~^" => 4, + "&" => 5, + "==" | "!=" | "===" | "!==" | "==?" | "!=?" => 6, + "<" | "<=" | ">" | ">=" => 7, + "<<" | ">>" | "<<<" | ">>>" => 8, + "+" | "-" => 9, + "*" | "/" | "%" => 10, + "**" => 11, + // `->` and `<->` are the lowest-precedence binary operators + // (IEEE 1800 §11.3.2). This table is only ever compared for + // equality — it decides which neighbours flatten into one + // chain — and no other operator reaches the fallback. + "->" | "<->" => 0, + _ => 0, + } + } + + /// True when a call's callee is a **macro name the source separated from + /// its `(`** — `` `WIDTH (a + b) ``, the expression-position spelling of + /// the `` `uvm_field_int (x, y) `` an item already keeps + /// (`Parser::at_spaced_macro_call`). + /// + /// The gap is data, not layout: `` `A (b) `` and `` `A(b) `` are one token + /// each, of *different text*, so closing it is a token rewrite the safety + /// net refuses — pinned in both directions by + /// `verification::{tightening,loosening}_a_*_macro_call_is_rejected`. And + /// lucisv cannot know which spelling was meant, because that depends on + /// whether the macro was defined with formals (IEEE 1800 §22.5.1), which + /// lives in a file this formatter does not read. + /// + /// The question is asked of `src` rather than of the AST for the reason + /// [`Fmt::glued_null_item`] gives: it is a fact about the gap between two + /// tokens, and this is the one place that gap is laid out. It is a fixed + /// point by construction — the printed gap is one space, which reads back + /// as a gap on the next pass. + fn spaced_macro_callee(&self, callee: &Expr) -> bool { + let ExprKind::Ident(name) = &callee.kind else { return false }; + name.starts_with('`') + && self + .src + .get(callee.span.end as usize..) + .and_then(|rest| rest.chars().next()) + .is_some_and(char::is_whitespace) + } + + /// One arm per `ExprKind`. A dispatch table over the enum, so it stays + /// whole past the 150-line mark: the shapes with a layout of their own + /// (a binary chain, a ternary with comments, `base.name`) are the + /// functions after it. + pub(super) fn expr(&self, e: &Expr) -> Doc { + match &e.kind { + ExprKind::Ident(s) => name_doc(s), + ExprKind::Number(s) => text(s.clone()), + ExprKind::Str(s) => text(s.clone()), + // Only reachable through `connection`, which handles the comments. + ExprKind::Empty(_) => text(""), + ExprKind::Unary { op, comments, expr } => { + let mut docs = vec![text(op.clone())]; + self.slot_comments(comments, &mut docs); + docs.push(self.expr(expr)); + concat(docs) + } + ExprKind::Binary { .. } => self.binary_chain(e), + ExprKind::Ternary { cond, then, els, comments } => { + if comments.is_empty() { + return group(vec![ + self.expr(cond), + indent(vec![ + Doc::Line, + text("? "), + self.expr(then), + Doc::Line, + text(": "), + self.expr(els), + ]), + ]); + } + self.ternary_with_comments(cond, then, els, comments) + } + ExprKind::Call { callee, args, comments } => { + let spaced = self.spaced_macro_callee(callee); + if comments.is_empty() { + let mut docs = vec![self.expr(callee)]; + if spaced { + docs.push(text(" ")); + } + docs.push(self.expr_list("(", args, ")")); + return concat(docs); + } + // A comment written around the brackets prints back between + // the same two tokens it was written between: after the + // callee, and inside the empty `()` that had nowhere else to + // put it. + let mut docs = vec![self.expr(callee)]; + if !comments.before_open.is_empty() { + self.inline_comments_spaced(&comments.before_open, &mut docs); + } else if spaced { + docs.push(text(" ")); + } + let items: Vec = + args.iter().map(|i| ListItem::from_meta(&i.meta, self.expr(&i.expr))).collect(); + docs.push(self.delimited_dangling("(", items, &comments.dangling, ")", false)); + concat(docs) + } + // `new src` — one space, never a break: the source handle is a + // postfix expression that breaks internally if it must. + ExprKind::New(src) => concat(vec![text("new "), self.expr(src)]), + ExprKind::Index { base, index, comments } => { + let mut docs = vec![self.expr(base)]; + self.slot_comments(&comments.before_open, &mut docs); + docs.push(self.bracket_slots(comments, self.expr_compact(index), None)); + concat(docs) + } + ExprKind::Range { base, op, msb, lsb, comments } => { + let mut docs = vec![self.expr(base)]; + self.slot_comments(&comments.before_open, &mut docs); + docs.push(self.bracket_slots( + comments, + self.expr_compact(msb), + Some((op, self.expr_compact(lsb))), + )); + concat(docs) + } + ExprKind::Member { base, name, comments } => { + self.chain_segment(base, ".", name, comments) + } + ExprKind::Scope { base, name, comments } => { + self.chain_segment(base, "::", name, comments) + } + // Written tight, like the `::` it almost always precedes. + ExprKind::Parameterized { base, params } => { + concat(vec![self.expr(base), self.raw_inline(params)]) + } + ExprKind::Concat(items) => self.expr_list("{", items, "}"), + ExprKind::Repl { count, inner } => concat(vec![ + text("{"), + self.expr(count), + self.expr_list("{", inner, "}"), + text("}"), + ]), + // `{<<8{v}}` — written tight, like a replication. + ExprKind::Stream { dir, slice, inner } => { + let mut docs = vec![text("{"), text(dir.clone())]; + if let Some(s) = slice { + docs.push(self.expr(s)); + } + docs.push(self.expr_list("{", inner, "}")); + docs.push(text("}")); + concat(docs) + } + ExprKind::Paren { inner, before, after } => { + if before.is_empty() && after.is_empty() { + return self.parens(inner); + } + let before: Vec<&Comment> = before.iter().collect(); + let after: Vec<&Comment> = after.iter().collect(); + self.paren_comments(inner, &before, &after) + } + // `ty'{...}` prints no brackets of its own: the assignment + // pattern already carries the `'{` and the `}`. + ExprKind::Cast { ty, comments, expr, pattern: true } => { + let mut docs = vec![self.expr(ty)]; + self.slot_comments(&comments.before_tick, &mut docs); + self.slot_comments(&comments.after_tick, &mut docs); + docs.push(self.expr(expr)); + concat(docs) + } + ExprKind::Cast { ty, comments, expr, .. } => { + if comments.is_empty() { + return concat(vec![self.expr(ty), text("'("), self.expr(expr), text(")")]); + } + let mut docs = vec![self.expr(ty)]; + self.slot_comments(&comments.before_tick, &mut docs); + docs.push(text("'")); + self.slot_comments(&comments.after_tick, &mut docs); + docs.push(text("(")); + self.slot_comments(&comments.after_open, &mut docs); + docs.push(self.expr(expr)); + self.slot_comments(&comments.before_close, &mut docs); + docs.push(text(")")); + concat(docs) + } + ExprKind::AssignPattern(items) => { + let items: Vec = items + .iter() + .map(|pi| { + let mut d = Vec::new(); + if let Some(k) = &pi.key { + d.push(self.expr(k)); + d.push(text(": ")); + } + d.push(self.expr(&pi.value)); + ListItem::from_meta(&pi.meta, concat(d)) + }) + .collect(); + self.delimited("'{", items, "}", false) + } + // `'{N{0}}` — written tight, like the `{N{0}}` it replicates. + ExprKind::AssignPatternRepl { count, inner } => concat(vec![ + text("'{"), + self.expr(count), + self.expr_list("{", inner, "}"), + text("}"), + ]), + ExprKind::Postfix { expr, op, comments } => { + let mut docs = vec![self.expr(expr)]; + self.slot_comments(comments, &mut docs); + docs.push(text(op.clone())); + concat(docs) + } + ExprKind::With { base, arg, comments } => { + concat(vec![self.with_head(base, comments), self.expr(arg)]) + } + ExprKind::WithConstraint { base, block, comments } => { + let body = match &**block { + ConstraintBody::Items(set) => self.with_constraint_block(set), + ConstraintBody::Verbatim(raw) => self.with_block(raw), + }; + concat(vec![self.with_head(base, comments), body]) + } + ExprKind::Dist { expr, comments, weights } => self.dist(expr, comments, weights), + ExprKind::Inside { lhs, ranges, comments } => { + self.inside_head(lhs, comments, self.expr_list("{", ranges, "}")) + } + ExprKind::InsideMacro { lhs, set, comments } => { + self.inside_head(lhs, comments, text(set.clone())) + } + // A named call argument, printed the way a named connection is: + // `.name(value)`, tight, with a break opportunity inside. + ExprKind::NamedArg { name, value, comments, .. } => match &value.kind { + ExprKind::Empty(inner) => { + let comments_inner = inner; + let mut docs = vec![text(".")]; + self.slot_comments(&comments.after_dot, &mut docs); + docs.push(text(named(name))); + self.slot_comments(&comments.before_open, &mut docs); + docs.push(text("(")); + self.slot_comments(&comments.after_open, &mut docs); + let comments = comments_inner; + let mut ends_line = false; + for cm in comments { + if ends_line { + docs.push(Doc::HardLine); + } + docs.push(self.comment(cm)); + ends_line = is_line_comment(&cm.text); + } + if ends_line { + docs.push(Doc::HardLine); + } + docs.push(text(")")); + concat(docs) + } + _ => { + let mut inner = vec![Doc::SoftLine, self.expr(value)]; + let ends_line = self.inline_comments(&comments.close, &mut inner); + let close = if ends_line { Doc::HardLine } else { Doc::SoftLine }; + let mut docs = vec![text(".")]; + self.slot_comments(&comments.after_dot, &mut docs); + docs.push(text(named(name))); + self.slot_comments(&comments.before_open, &mut docs); + docs.push(text("(")); + self.slot_comments(&comments.after_open, &mut docs); + docs.push(group(vec![indent(inner), close])); + docs.push(text(")")); + concat(docs) + } + }, + ExprKind::ValueRange { lo, hi, comments } => { + self.bracket_slots(comments, self.expr(lo), Some((":", self.expr(hi)))) + } + ExprKind::Type(ty) => self.data_type(ty).unwrap_or_else(|| text("")), + // Byte for byte, like every other verbatim leaf, and `Inline` + // rather than re-indented for the reason `raw_inline` gives: the + // region never begins its own line, so a dedent-by-column would + // drift instead of reaching a fixed point. + ExprKind::Verbatim(raw) => self.raw_inline(raw), + ExprKind::MinTypMax { min, typ, max } => { + concat(vec![self.expr(min), text(":"), self.expr(typ), text(":"), self.expr(max)]) + } + } + } + + /// Flatten a left-nested chain of same-precedence binary operators so + /// `a + b + c` breaks as one unit instead of stair-stepping. An operator + /// carrying comments (written after the operand before it) starts its own + /// line, so the comment stays last on the line it was written on. + fn binary_chain(&self, e: &Expr) -> Doc { + let ExprKind::Binary { op, .. } = &e.kind else { unreachable!() }; + let prec = Self::binary_prec(op); + let mut operands: Vec<&Expr> = Vec::new(); + let mut ops: Vec> = Vec::new(); + fn walk<'e>( + e: &'e Expr, + prec: u8, + operands: &mut Vec<&'e Expr>, + ops: &mut Vec>, + ) { + match &e.kind { + ExprKind::Binary { lhs, op, rhs, comments } if Fmt::binary_prec(op) == prec => { + walk(lhs, prec, operands, ops); + ops.push(BinaryOp { op, before: &comments.before, after: &comments.after }); + operands.push(rhs); + } + _ => operands.push(e), + } + } + walk(e, prec, &mut operands, &mut ops); + let mut docs = vec![self.expr(operands[0])]; + let mut cont = Vec::new(); + for (op, rhs) in ops.iter().zip(operands[1..].iter()) { + // Comments written before the operator stay on the left operand's + // line; the operator then starts a new one. + self.inline_comments(op.before, &mut cont); + if op.before.is_empty() { + cont.push(text(format!(" {}", op.op))); + } else { + cont.push(Doc::HardLine); + cont.push(text(op.op.to_string())); + } + // Comments written after the operator stay on the operator's line; + // the right operand then starts a new one. + let hard = self.inline_comments(op.after, &mut cont); + if hard { + cont.push(Doc::HardLine); + } else if !op.after.is_empty() || !op.before.is_empty() { + cont.push(text(" ")); + } else { + cont.push(Doc::Line); + } + cont.push(self.expr(rhs)); + } + docs.push(indent(cont)); + group(docs) + } + + /// A `? :` with comments written inside it. Each comment stays between the + /// two tokens it was written between, and a line comment forces the break + /// that follows it, so the layout can never fold a comment over the `?`, + /// the `:` or an operand. + fn ternary_with_comments( + &self, + cond: &Expr, + then: &Expr, + els: &Expr, + comments: &TernaryComments, + ) -> Doc { + let mut head = vec![self.expr(cond)]; + let hard = self.inline_comments(&comments.before_question, &mut head); + let mut inner = vec![if hard { Doc::HardLine } else { Doc::Line }]; + inner.push(text("?")); + let hard = self.inline_comments(&comments.after_question, &mut inner); + inner.push(if hard { Doc::HardLine } else { text(" ") }); + inner.push(self.expr(then)); + let hard = self.inline_comments(&comments.before_colon, &mut inner); + inner.push(if hard { Doc::HardLine } else { Doc::Line }); + inner.push(text(":")); + let hard = self.inline_comments(&comments.after_colon, &mut inner); + inner.push(if hard { Doc::HardLine } else { text(" ") }); + inner.push(self.expr(els)); + head.push(indent(inner)); + group(head) + } + + /// Compact rendering used inside `[...]` brackets: arithmetic and shift + /// operators lose their surrounding spaces (`[WIDTH-1:0]`), and no line + /// breaks are introduced. + pub(super) fn expr_compact(&self, e: &Expr) -> Doc { + match &e.kind { + ExprKind::Binary { lhs, op, rhs, comments } => { + if comments.before.is_empty() && comments.after.is_empty() { + let tight = Self::binary_prec(op) >= 8; + let sep = if tight { op.clone() } else { format!(" {op} ") }; + return concat(vec![self.expr_compact(lhs), text(sep), self.expr_compact(rhs)]); + } + // A comment written next to the operator has nowhere to go in + // the tight spelling, so the operator gets its spaces back; + // a line comment pushes what follows onto the next line. + let mut docs = vec![self.expr_compact(lhs)]; + self.inline_comments_spaced(&comments.before, &mut docs); + docs.push(text(op.clone())); + self.inline_comments_spaced(&comments.after, &mut docs); + docs.push(self.expr_compact(rhs)); + concat(docs) + } + // The compact spelling has nowhere to put a comment written + // inside the `? :` or just inside the parentheses, so a shape + // that carries one falls back to the ordinary layout, which does. + ExprKind::Ternary { cond, then, els, comments } if comments.is_empty() => concat(vec![ + self.expr_compact(cond), + text(" ? "), + self.expr_compact(then), + text(" : "), + self.expr_compact(els), + ]), + ExprKind::Paren { inner, before, after } if before.is_empty() && after.is_empty() => { + concat(vec![text("("), self.expr_compact(inner), text(")")]) + } + ExprKind::Unary { op, comments, expr } if comments.is_empty() => { + concat(vec![text(op.clone()), self.expr_compact(expr)]) + } + _ => self.expr(e), + } + } + + /// `base.name` / `base::name`, with the comments the source wrote on + /// either side of the joining token. + fn chain_segment( + &self, + base: &Expr, + joiner: &str, + name: &str, + comments: &SegmentComments, + ) -> Doc { + if comments.is_empty() { + return concat(vec![self.expr(base), text(format!("{joiner}{}", named(name)))]); + } + let mut docs = vec![self.expr(base)]; + self.slot_comments(&comments.before_open, &mut docs); + docs.push(text(joiner.to_string())); + self.slot_comments(&comments.after_open, &mut docs); + docs.push(text(named(name))); + concat(docs) + } + + /// `lhs inside set`, with the comments written on either side of the word + /// kept on their own side of it, as every binary operator's are. + fn inside_head(&self, lhs: &Expr, comments: &BinaryComments, set: Doc) -> Doc { + if comments.before.is_empty() && comments.after.is_empty() { + return concat(vec![self.expr(lhs), text(" inside "), set]); + } + let mut docs = vec![self.expr(lhs)]; + self.inline_comments_spaced(&comments.before, &mut docs); + docs.push(text("inside")); + self.inline_comments_spaced(&comments.after, &mut docs); + docs.push(set); + concat(docs) + } + + /// ` with ` — the head both postfix `with` forms share, with the + /// comments written on either side of the keyword printed back where they + /// were written. Anywhere else they would move across `with` and the + /// safety net would reject the output. + fn with_head(&self, base: &Expr, comments: &WithComments) -> Doc { + let mut docs = vec![self.expr(base)]; + self.inline_comments_spaced(&comments.before_kw, &mut docs); + docs.push(text("with")); + self.inline_comments_spaced(&comments.after_kw, &mut docs); + concat(docs) + } +} diff --git a/crates/vlog_formatter/src/format/instance.rs b/crates/vlog_formatter/src/format/instance.rs new file mode 100644 index 0000000..0cde745 --- /dev/null +++ b/crates/vlog_formatter/src/format/instance.rs @@ -0,0 +1,385 @@ +//! Instantiations: a module instance with its parameter overrides and +//! named or ordered connections, the alignment of a connection list, +//! `bind`, and gate instances. +//! +//! A connection's `(` is the one column an instance list aligns on; the +//! cells, the column spec and the planner all live here, so a change to +//! how connections align touches one file. + +use crate::align::{self, Align, ColSpec, Row}; +use crate::doc::*; +use vlog_parser::ast::*; + +use super::comment::is_line_comment; +use super::list::ListItem; +use super::{join_names, name_doc, named, Fmt}; + +/// 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 }]; + +impl<'a> Fmt<'a> { + pub(super) fn instantiation(&self, inst: &Instantiation, depth: usize) -> Doc { + let mut docs = vec![name_doc(&inst.module)]; + 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() || holds_verbatim_value(params); + docs.push(text(if on_fresh_line { "#" } else { " #" })); + self.slot_comments(&inst.after_hash, &mut docs); + 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(self.semi(&inst.before_semi)); + 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![name_doc(&instance.name)]; + if !instance.dims.is_empty() { + if instance.dims[0].comments.opens_clean() { + 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) || holds_verbatim_value(list); + 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) + } + + /// 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) + } + + /// 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) + } + + pub(super) 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(); + } + // A comment written in one of the connection's own gaps makes the row + // a width no other row shares, so it never joins an alignment group. + if !c.after_dot.is_empty() || !c.before_open.is_empty() || !c.after_open.is_empty() { + return plain(); + } + let Some(e) = &c.expr else { return plain() }; + // A verbatim conditional region is many lines of bytes; a row that + // wide shares its width with nothing, and the `)` after it has a line + // break of its own to keep (`Fmt::verbatim_value_breaks`). + if matches!(e.kind, ExprKind::Empty(_) | ExprKind::Verbatim(_)) { + 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!(".{}", named(&c.name))), + concat(vec![text("("), group(vec![indent(inner), close]), text(")")]), + ] + } + + /// True when a connection's value is a **verbatim conditional region** + /// the source ended a line after — which it always does when the region + /// ends on a `` `endif ``. + /// + /// A line-oriented directive runs to the end of its line (`lexer.rs`'s + /// `is_line_directive`), so a `)` printed after one on the same line is + /// swallowed into the directive's own token — a rewrite the safety net + /// refuses. The break is read back from `src` rather than stored, for the + /// reason [`Fmt::glued_null_item`] gives, and is a fixed point by + /// construction: the break printed here reads back as the same break. + fn verbatim_value_breaks(&self, c: &Connection) -> bool { + let Some(Expr { kind: ExprKind::Verbatim(raw), .. }) = &c.expr else { return false }; + self.src + .get(raw.span.end as usize..c.span.end as usize) + .is_some_and(|gap| gap.contains('\n')) + } + + 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 == "*" { + if c.after_dot.is_empty() { + return text(".*"); + } + let mut docs = vec![text(".")]; + self.slot_comments(&c.after_dot, &mut docs); + docs.push(text("*")); + return concat(docs); + } + if c.name.is_empty() { + // Positional parameter value. + return match &c.expr { + Some(e) => self.expr(e), + None => text(""), + }; + } + // `.` then the name, with whatever the source wrote between them. + let head = |f: &Self| { + let mut docs = vec![text(".")]; + f.slot_comments(&c.after_dot, &mut docs); + docs.push(text(named(&c.name))); + docs + }; + // …and the `(` that follows the name, with its two gaps. + let open = |f: &Self, docs: &mut Vec| { + f.slot_comments(&c.before_open, docs); + docs.push(text("(")); + f.slot_comments(&c.after_open, docs); + }; + match &c.expr { + None => concat(head(self)), + Some(Expr { kind: ExprKind::Empty(comments), .. }) => { + let mut docs = head(self); + open(self, &mut docs); + 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 broke = ends_line || self.verbatim_value_breaks(c); + let close = if broke { Doc::HardLine } else { Doc::SoftLine }; + let mut docs = head(self); + open(self, &mut docs); + docs.push(group(vec![indent(inner), close])); + docs.push(text(")")); + 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. + pub(super) fn bind(&self, b: &BindDirective, depth: usize) -> Doc { + // 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); + // One segment at a time, for the reason `scope_prefix` prints a `::` + // chain that way: `named` supplies the space an escaped segment needs + // to terminate, and a joined string could not carry it. + for (i, seg) in b.target.iter().enumerate() { + if i > 0 { + docs.push(text(".")); + } + docs.push(text(named(&seg.name))); + if let Some(index) = &seg.index { + docs.push(text("[")); + docs.push(self.expr_compact(index)); + docs.push(text("]")); + } + } + if !b.instances.is_empty() { + docs.push(text(format!(" : {}", join_names(&b.instances)))); + } + self.inline_comments_spaced(&b.module_comments, &mut docs); + docs.push(self.instantiation(&b.inst, depth)); + concat(docs) + } + + pub(super) fn gate_instantiation(&self, g: &GateInstantiation) -> Doc { + let mut docs = vec![text(g.gate.clone())]; + if let Some(s) = &g.strength { + docs.push(text(format!(" {}", drive_strength(s)))); + } + if let [delay] = g.delay.as_slice() { + // One value prints itself, brackets and all (`#5`, `#(5)`). + docs.push(text(" #")); + docs.push(self.expr(delay)); + } else if !g.delay.is_empty() { + // `#(rise, fall[, turn-off])` — the parens are the list's own. + docs.push(text(" #(")); + for (i, d) in g.delay.iter().enumerate() { + if i > 0 { + docs.push(text(", ")); + } + docs.push(self.expr(d)); + } + docs.push(text(")")); + } + for (i, inst) in g.instances.iter().enumerate() { + docs.push(if i > 0 { text(", ") } else { text(" ") }); + if let Some(name) = &inst.name { + docs.push(name_doc(name)); + docs.push(text(" ")); + } + docs.push(self.expr_list("(", &inst.args, ")")); + } + docs.push(text(";")); + concat(docs) + } +} + +/// True when any entry of a connection or override list carries a +/// **multi-line verbatim value** — a conditional region +/// ([`ExprKind::Verbatim`]). +/// +/// Such a value brings its own line breaks, which `Doc::Inline` copies +/// through without telling the enclosing group; without this the list would +/// be measured as one short line and flattened around a value that is +/// twenty lines tall. It is exactly the reason a list holding a +/// [`ListDirective`] is broken, for exactly the same construct. +fn holds_verbatim_value(list: &[Connection]) -> bool { + list.iter().any(|c| match &c.expr { + Some(Expr { kind: ExprKind::Verbatim(raw), .. }) => raw.text.contains('\n'), + _ => false, + }) +} + +/// `(weak0, pull1)`, or the single-strength `(weak1)` a pull gate may write. +pub(super) fn drive_strength(s: &DriveStrength) -> String { + match &s.second { + Some(second) => format!("({}, {})", s.first, second), + None => format!("({})", s.first), + } +} diff --git a/crates/vlog_formatter/src/format/item.rs b/crates/vlog_formatter/src/format/item.rs new file mode 100644 index 0000000..6134339 --- /dev/null +++ b/crates/vlog_formatter/src/format/item.rs @@ -0,0 +1,535 @@ +//! The file and its items: a source file or fragment, the sequence of +//! items at one indent level with the blank lines the source wrote, the +//! dispatch from `ItemKind` to the construct that prints it, and the +//! items that are only containers or one-liners — `package`, the +//! generate constructs, `assign`. +//! +//! Everything with a shape worth a file of its own — the module header, +//! an instantiation, a declaration, a class — is dispatched to from +//! `item_kind` and lives in a sibling module. + +use crate::align::Align; +use crate::doc::*; +use crate::range::Split; +use vlog_parser::ast::*; +use vlog_parser::token::Comment; + +use super::instance::drive_strength; +use super::list::ListItem; +use super::verbatim::Slot; +use super::{join_names, join_paths, named, Fmt}; + +impl<'a> Fmt<'a> { + pub(super) fn file(&self, f: &SourceFile) -> Doc { + let mut docs = match &f.fragment { + Some(fragment) => self.fragment(fragment), + None => 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) + } + + /// A whole file that is the middle of some body, printed at indent 0 + /// through the very printers that body uses — a statement sequence, an + /// enum's member list, a covergroup's items. Nothing here is a layout of + /// its own: the fragment is the piece of code it was written as, minus the + /// construct around it, and it must come back the way that construct would + /// have printed it. See `docs/features/fragment-mode/README.md`. + fn fragment(&self, fragment: &Fragment) -> Vec { + match fragment { + Fragment::Statements(stmts) => self.stmt_seq(stmts), + Fragment::EnumMembers { members, directives } => { + let items = self.list_entries(self.enum_member_items(members), directives); + let mut docs = Vec::new(); + // The file's own dangling comments are `SourceFile::dangling` + // and `Fmt::file` prints them, so the list has none of its own. + self.list_rows(items, &[], &mut docs); + docs + } + Fragment::CoverItems(items) => self.cover_items(items), + } + } + + /// 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. + pub(super) fn item_seq(&self, items: &[Item], depth: usize) -> Vec { + let aligns = self.param_decl_aligns(items, depth); + let mut docs = Vec::new(); + // The last item that actually emitted something, which is what a + // glued null item glues to. + let mut prev: Option<&Item> = None; + 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() && !prev.is_some_and(|p| self.glued_null_item(p, item)) { + docs.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); + } + docs.extend(item_docs); + prev = Some(item); + } + docs + } + + /// True when `item` is a null item (`;`) the source wrote on the line the + /// item before it ended on, which is how it is printed back: + /// `endgenerate;`, `end;`, `endmodule;`, `;;`. + /// + /// The question is asked of the source rather than of the AST because it + /// is a layout fact about the gap between two siblings, and this is the + /// one place that gap is laid out — the same reason `eq_offset` and + /// `default_has_colon` read `src` here. A null item that begins a body has + /// no sibling to glue to and prints on its own line. + /// + /// Anything that gives the `;` docs of its own — a leading comment, an + /// attribute, a blank line, a format-off fence opening on it — takes the + /// own-line path instead, so the glue only ever appends a bare `;`. Note + /// that a `//` comment cannot stand in a newline-free gap: it would + /// swallow the `;` that follows it. The only comment that fits is a + /// one-line block comment, which prints inline before the `;`, in the + /// order it was written. + fn glued_null_item(&self, prev: &Item, item: &Item) -> bool { + if !matches!(item.kind, ItemKind::Empty) { + return false; + } + if item.meta.blank_before || !item.meta.leading.is_empty() || !item.meta.attrs.is_empty() { + return false; + } + if self.is_verbatim(item.span) || self.opens_at(item.span.start as usize).is_some() { + return false; + } + self.src + .get(prev.span.end as usize..item.span.start as usize) + .is_some_and(|gap| !gap.contains('\n')) + } + + 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, before_name, name, before_semi, .. } => { + Some(self.package_head(kw, before_name, name, before_semi)) + } + _ => None, + } + } + + /// A split item's closing keyword, laid out. + fn tail_doc(&self, kind: &ItemKind) -> Option { + match kind { + ItemKind::Module(m) => { + Some(self.closing_labeled(m.end_kw(), &m.end_label, &m.end_label_comments)) + } + ItemKind::Package { end_label, end_label_comments, .. } => { + Some(self.closing_labeled("endpackage", end_label, end_label_comments)) + } + _ => None, + } + } + + pub(super) fn item_kind(&self, kind: &ItemKind, align: Option<&Align>, depth: usize) -> Doc { + match kind { + ItemKind::Module(m) => self.module(m, depth), + ItemKind::Package { + kw, + before_name, + name, + before_semi, + items, + dangling, + end_label, + end_label_comments, + .. + } => { + let mut docs = vec![self.package_head(kw, before_name, name, before_semi)]; + 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_labeled("endpackage", end_label, end_label_comments)); + 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::Constraint(c) => self.constraint(c), + ItemKind::Covergroup(c) => self.covergroup(c), + ItemKind::PropSeqDecl(d) => self.prop_seq_decl(d), + ItemKind::Assertion(a) => self.assertion(a), + ItemKind::DefaultDisable(d) => self.default_disable(d), + ItemKind::Verbatim(raw) => self.raw_text(raw), + // A null item is its `;`. Whether it keeps the previous item's + // line or takes one of its own is `item_seq`'s call. + ItemKind::Empty => text(";"), + 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) + } + // `alias a = b = c;` — one line, one space around every `=`, the + // spacing every other assignment-shaped item already uses. + ItemKind::Alias(nets) => { + let mut docs = vec![text("alias ")]; + docs.extend(join(nets.iter().map(|n| self.expr(n)).collect(), text(" = "))); + docs.push(text(";")); + concat(docs) + } + } + } + + /// `package p;` — the two comment slots a package header owns. + fn package_head( + &self, + kw: &str, + before_name: &[Comment], + name: &str, + before_semi: &[Comment], + ) -> Doc { + let mut docs = vec![text(kw.to_string())]; + if before_name.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(before_name, &mut docs); + } + docs.push(text(named(name))); + docs.push(self.semi(before_semi)); + concat(docs) + } + + fn cont_assign(&self, a: &ContAssign) -> Doc { + // `assign /*c*/ y = x;` — the first pair's own leading comments were + // written after the keyword, and print there. + let lead = a.assigns.first().map(|p| p.meta.leading.as_slice()).unwrap_or(&[]); + let mut docs = vec![text("assign")]; + if lead.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(lead, &mut docs); + } + if let Some(s) = &a.strength { + docs.push(text(format!("{} ", drive_strength(s)))); + } + if let Some(delay) = &a.delay { + docs.push(text("#")); + docs.push(self.expr(delay)); + docs.push(text(" ")); + } + let items: Vec = a + .assigns + .iter() + .enumerate() + .map(|(i, p)| { + // The first pair's leading comments are printed above, after + // the keyword; printing them twice would duplicate them. + let skip = usize::from(i == 0) * lead.len(); + let mut item = ListItem::from_meta(&p.meta, self.assign_pair(p)); + item.leading.drain(..skip.min(item.leading.len())); + item + }) + .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) + } + + /// `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 { + // `y /*c*/ =` — the comments stay on the operator's left. + let mut head = vec![self.expr(&p.lhs)]; + self.slot_comments(&p.op_comments, &mut head); + head.push(text(if p.op_comments.is_empty() { " =" } else { "=" })); + if p.rhs_comments.is_empty() { + head.push(self.assign_rhs(self.expr(&p.rhs))); + return group(head); + } + 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)); + head.push(indent(inner)); + group(head) + } + + 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 { + if b.before_kw.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&b.before_kw, docs); + } + docs.push(text("begin")); + if let Some(l) = &b.label { + self.slot_comments(&b.before_colon, docs); + docs.push(text(if b.before_colon.is_empty() { " :" } else { ":" })); + if b.after_colon.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&b.after_colon, docs); + } + docs.push(text(named(l))); + } + 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_labeled("end", &b.end_label, &b.end_label_comments)); + 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::new(); + self.for_open(&g.comments, &mut header); + if g.init_genvar { + header.push(text("genvar")); + if g.after_genvar.is_empty() { + header.push(text(" ")); + } else { + self.inline_comments_spaced(&g.after_genvar, &mut header); + } + } + self.simple_assign(&g.init, &mut header); + self.for_semi(&g.comments.before_first_semi, &g.comments.after_first_semi, &mut header); + header.push(self.expr(&g.cond)); + self.for_semi(&g.comments.before_second_semi, &g.comments.after_second_semi, &mut header); + header.push(self.for_step(&g.step)); + self.slot_comments(&g.comments.before_close, &mut header); + 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.before_colon, 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) + } +} diff --git a/crates/vlog_formatter/src/format/list.rs b/crates/vlog_formatter/src/format/list.rs new file mode 100644 index 0000000..4509d29 --- /dev/null +++ b/crates/vlog_formatter/src/format/list.rs @@ -0,0 +1,335 @@ +//! Comma-separated lists and how their elements are aligned: the +//! bracketed list that breaks one element per line when it does not fit +//! (`delimited`), the bare list with no brackets to open (`plain_list`), +//! the `` `ifdef``-style directives written between elements, and the +//! alignment planner that pads a run of rows to shared columns. +//! +//! What a *row* of a given list looks like — an ANSI port, a named +//! connection, a `parameter` declaration — is the construct's own +//! business and lives beside it; this module only knows how to break, +//! separate and pad the rows it is handed. + +use crate::align::{self, Align, ColSpec, Row}; +use crate::doc::*; +use vlog_parser::ast::*; +use vlog_parser::token::Comment; + +use super::comment::is_line_comment; +use super::Fmt; + +/// A list element ready for comma-list layout. Blank lines between elements +/// are deliberately dropped, so only the comments ride along. +pub(super) struct ListItem { + pub(super) leading: Vec, + pub(super) doc: Doc, + /// Comments written between the element and the separator that follows. + pub(super) before_sep: Vec, + pub(super) 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 { + pub(super) 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. + pub(super) fn with_comma(mut self, comma: bool) -> Self { + self.comma = Some(comma); + self + } +} + +impl<'a> Fmt<'a> { + /// A bracketed expression list (concatenation, call arguments, `inside` + /// set). Comments on an element ride along and break the list open. + pub(super) 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) + } + + /// Comma-separated list inside `open`/`close`, one per line when broken. + /// `force_break` lays every element on its own line regardless of width. + pub(super) 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. + pub(super) 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 close_needs_hardline = self.list_rows(items, dangling, &mut inner) || force_break; + // 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) + } + + /// The elements of a list, their separators and the comments written + /// around each one, appended to `inner`. Returns whether what follows the + /// last element must start on a new line — a trailing comment, or a + /// comment written where the separator would have been, cannot share it. + /// + /// Split out of [`Fmt::delimited_dangling`] so a fragment's enum members + /// go through the very layout their enum body would have given them, at + /// indent 0 and with no braces around them. + pub(super) fn list_rows( + &self, + items: Vec, + dangling: &[Comment], + inner: &mut Vec, + ) -> bool { + let last = items.len().saturating_sub(1); + let mut close_needs_hardline = false; + 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, 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; + } + close_needs_hardline + } + + /// 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. + pub(super) 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, + } + } + + /// A comma-separated expression list with no brackets around it: the two + /// halves of a `solve a, b before c, d;`. + /// + /// Not [`Fmt::delimited`], which is written for a *bracketed* list: its + /// closing break would land the `before` keyword — or the item's `;` — + /// on a line of its own the moment any comment forced the group open. + /// A list with no brackets has nothing to open, so every comment prints + /// where it was written and only a `//` costs a line break. + pub(super) fn plain_expr_list(&self, items: &[ExprItem]) -> Doc { + self.plain_list(items.iter().map(|i| (&i.meta, self.expr(&i.expr))).collect()) + } + + /// The same, over elements the caller has already rendered: a transition + /// bin's `(a => b), (c => d)` sets are laid out by exactly this rule. + pub(super) fn plain_list(&self, items: Vec<(&Meta, Doc)>) -> Doc { + let mut docs = Vec::new(); + let last = items.len().saturating_sub(1); + for (i, (meta, doc)) in items.into_iter().enumerate() { + let leading: Vec<&Comment> = meta.leading.iter().collect(); + let mut ends_line = false; + for c in leading { + docs.push(self.comment(c)); + docs.push(if is_line_comment(&c.text) { Doc::HardLine } else { text(" ") }); + ends_line = is_line_comment(&c.text); + } + docs.push(doc); + ends_line = self.inline_comments(&meta.before_sep, &mut docs) || ends_line; + if i < last { + if ends_line { + docs.push(Doc::HardLine); + } + docs.push(text(",")); + } + if let Some(tr) = &meta.trailing { + docs.push(text(" ")); + docs.push(self.comment(tr)); + if is_line_comment(&tr.text) { + docs.push(Doc::HardLine); + continue; + } + } + if i < last { + docs.push(text(" ")); + } + } + concat(docs) + } + + /// 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. + pub(super) 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. + pub(super) 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. + pub(super) 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 + } +} diff --git a/crates/vlog_formatter/src/format/mod.rs b/crates/vlog_formatter/src/format/mod.rs new file mode 100644 index 0000000..f7e716f --- /dev/null +++ b/crates/vlog_formatter/src/format/mod.rs @@ -0,0 +1,259 @@ +//! 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`. +//! +//! The rules are one `Fmt` whose methods are spread over the sibling +//! modules by grammar domain — `item`, `module`, `instance`, `decl`, +//! `routine`, `class`, `cover`, `sva`, `stmt`, `expr` — on top of the +//! shared machinery they all print through — `comment`, `verbatim`, +//! `phrase`, `list`. This file holds what the crate exports (`Config`, +//! `FormatError`, `format_source`, `format_range`), the `Fmt` state, and +//! the name helpers every module writes an identifier through. + +mod class; +mod comment; +mod cover; +mod decl; +mod expr; +mod instance; +mod item; +mod list; +mod module; +mod phrase; +mod routine; +mod stmt; +mod sva; +mod verbatim; + +use crate::doc::{text, Doc}; +use crate::fence::{self, Region}; +use crate::printer::Printer; +use crate::range::{self, Split}; +use crate::verify::{verify_convergence, verify_equivalence, VerificationError}; +use vlog_parser::ast::*; + +#[derive(Debug, Clone)] +pub struct Config { + pub max_width: usize, + pub indent_width: usize, +} + +impl Default for Config { + fn default() -> Self { + Config { max_width: 100, indent_width: 2 } + } +} + +/// Everything that can stop the formatter from producing output. +#[derive(Debug)] +pub enum FormatError { + /// The input could not be lexed or parsed. + Source(vlog_parser::Error), + /// A safety check failed; the formatted text was discarded. + Verification(VerificationError), +} + +impl std::fmt::Display for FormatError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + FormatError::Source(e) => write!(f, "{e}"), + FormatError::Verification(e) => write!(f, "{e}"), + } + } +} + +impl std::error::Error for FormatError {} + +impl From 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, +} + +/// A name, plus the space that terminates it when it is an escaped identifier. +/// +/// An escaped identifier runs from its `\` to the next **whitespace** +/// character and to nothing else (IEEE 1800-2017 §5.6.1), so `\my-signal;` +/// lexes as one identifier that swallows the `;`, and `.\my-port(x)` as one +/// that swallows the rest of the line. Every name the formatter writes goes +/// through here (or through [`name_doc`], its `Doc` twin): declarators, +/// ANSI and non-ANSI ports, parameters and their aligned cells, type names, +/// typedef/enum/genvar/`let` names, module, package, class, function, task, +/// modport and clocking names, instance and module-instance names, port +/// connections and named call arguments, `extends`, scopes, hierarchical +/// members, tf arguments, block/fork/statement labels, every `end : label`, +/// `disable`, and the `join_names`/`join_paths` lists. The audit that built +/// that list is a grep of `text(` and `format!(` over `format/`; a site that +/// grows a name later belongs on it. +/// +/// The space is unconditional. Where the layout already writes a separator +/// the output carries two (`logic \a = 1;`) — legal, a fixed point under +/// re-formatting, and cheaper than a second rule about what comes next. +fn named(s: &str) -> String { + if ends_escaped(s) { + format!("{s} ") + } else { + s.to_string() + } +} + +/// [`named`] as a `Doc`. +fn name_doc(s: &str) -> Doc { + text(named(s)) +} + +/// Whether `s` ends *inside* an escaped identifier, and so cannot be followed +/// directly by punctuation. +/// +/// Whitespace is the only terminator, so the question is exactly whether a +/// `\` survives in the run of characters after the last whitespace — which +/// also answers it for the composites the AST hands over already joined +/// (`a.\b`, `pkg::\x`). Conservative by construction: a false positive +/// writes one harmless extra space. `vlog_refactor::instantiate` carries the +/// same two-line rule for the skeletons it splices. +fn ends_escaped(s: &str) -> bool { + s.rsplit(char::is_whitespace).next().unwrap_or(s).contains('\\') +} + +/// 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| named(&n.text)).collect::>().join(", ") +} + +/// The same for a list of `pkg::item` import paths. +fn join_paths(paths: &[ImportPath]) -> String { + paths + .iter() + .map(|p| format!("{}::{}", named(&p.pkg.text), named(&p.item.text))) + .collect::>() + .join(", ") +} + +/// 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 +} diff --git a/crates/vlog_formatter/src/format/module.rs b/crates/vlog_formatter/src/format/module.rs new file mode 100644 index 0000000..75233ea --- /dev/null +++ b/crates/vlog_formatter/src/format/module.rs @@ -0,0 +1,365 @@ +//! What a module or interface declares at its boundary: the header +//! through its `;` (name, imports, parameter ports, ANSI or non-ANSI +//! ports), the alignment of an ANSI port list, `modport`s and clocking +//! blocks. +//! +//! The header is split from the body (`module_head` vs `module`) so a +//! range run can keep one verbatim and lay out the other. + +use crate::align::{self, Align, ColSpec, Row}; +use crate::doc::*; +use vlog_parser::ast::*; + +use super::list::ListItem; +use super::{join_names, join_paths, name_doc, named, Fmt}; + +/// An ANSI port's one alignment column: the name, one space off the type. +const ANSI_PORT_COLS: &[ColSpec] = &[ColSpec { flush: 1, min: 1 }]; + +impl<'a> Fmt<'a> { + pub(super) 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_labeled(m.end_kw(), &m.end_label, &m.end_label_comments)); + 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. + pub(super) fn module_head(&self, m: &Module, depth: usize) -> Doc { + let mut docs = vec![text(m.kw.clone())]; + if m.before_name.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&m.before_name, &mut docs); + } + docs.push(text(named(&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 { " #" })); + self.slot_comments(&m.param_after_hash, &mut docs); + 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(self.semi(&m.before_semi)), + 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, name_doc(&p.name)).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(self.semi(&m.before_semi)); + } + } + concat(docs) + } + + pub(super) fn param_port(&self, p: &ParamPort) -> Doc { + let mut docs = Vec::new(); + if let Some(kw) = &p.kw { + self.word_then(kw, &p.after_kw, &mut docs); + } else { + self.slot_comments(&p.after_kw, &mut docs); + } + if p.is_type { + docs.push(text("type ")); + } + match self.data_type(&p.ty) { + Some(t) => { + docs.push(t); + if p.before_name.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&p.before_name, &mut docs); + } + } + None => self.slot_comments(&p.before_name, &mut docs), + } + docs.push(name_doc(&p.name)); + docs.extend(self.unpacked_dims(&p.unpacked)); + if let Some(d) = &p.default { + self.eq_default(&p.eq_comments, group(vec![self.expr(d)]), &mut docs); + } + 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 { + // A comment in one of the port's own gaps makes the row a width no + // other row shares, so it is one cell and joins no alignment group — + // the rule an attributed connection already follows. + if !p.after_dir.is_empty() || !p.before_name.is_empty() { + return vec![self.ansi_port_plain(p)]; + } + 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![name_doc(&p.name)]; + docs.extend(self.unpacked_dims(&p.unpacked)); + if let Some(d) = &p.default { + self.eq_default(&p.eq_comments, self.expr(d), &mut docs); + } + if prefix.is_empty() { + return vec![concat(docs)]; + } + vec![concat(prefix), concat(docs)] + } + + /// An ANSI port written out in one piece, for the rows that carry a + /// comment in one of their own gaps and so cannot be aligned. + fn ansi_port_plain(&self, p: &AnsiPort) -> Doc { + let mut docs = Vec::new(); + if let Some(dir) = &p.dir { + self.word_then(dir, &p.after_dir, &mut docs); + } + if let Some(net) = &p.net { + docs.push(text(format!("{net} "))); + } + match self.data_type(&p.ty) { + Some(t) => { + docs.push(t); + if p.before_name.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&p.before_name, &mut docs); + } + } + None => self.slot_comments(&p.before_name, &mut docs), + } + docs.push(name_doc(&p.name)); + docs.extend(self.unpacked_dims(&p.unpacked)); + if let Some(d) = &p.default { + self.eq_default(&p.eq_comments, self.expr(d), &mut docs); + } + concat(docs) + } + + /// 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) + } + + /// `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. + pub(super) 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!("{} ", named(&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. + pub(super) 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(&named(&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_labeled("endclocking", &c.end_label, &c.end_label_comments)); + } + concat(docs) + } + + /// One clocking-block item. A `= expression` binding + /// (`output tms = _tms_internal;`) prints on the item's own line: the + /// bound expression is a signal name, never long enough to be worth a + /// breakable group. + 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, signals } => { + let mut head = dir.clone(); + if let Some(skew) = skew { + head.push(' '); + head.push_str(skew); + } + head.push(' '); + let mut docs = vec![text(head)]; + for (i, sig) in signals.iter().enumerate() { + if i > 0 { + docs.push(text(", ")); + } + docs.push(name_doc(&sig.name.text)); + if let Some(value) = &sig.value { + docs.push(text(" = ")); + docs.push(self.expr(value)); + } + } + concat(docs) + } + } + } +} diff --git a/crates/vlog_formatter/src/format/phrase.rs b/crates/vlog_formatter/src/format/phrase.rs new file mode 100644 index 0000000..19e0b6e --- /dev/null +++ b/crates/vlog_formatter/src/format/phrase.rs @@ -0,0 +1,257 @@ +//! Recurring two- and three-token phrases, each printed with the +//! comments written in its gaps: a keyword and what follows it, `= value`, +//! the `;` that ends a statement, `end : label`, `[msb:lsb]`, the +//! punctuation of a `for` header, the `[i, j]` of a `foreach`. +//! +//! They are here rather than beside one user because each has at least +//! two — a statement `for` and a generate `for`, a declarator and a port +//! default — and the two must agree byte for byte, since the safety net +//! compares token streams, not intentions. + +use crate::doc::*; +use crate::printer::contains_hard_line; +use vlog_parser::ast::*; +use vlog_parser::token::Comment; + +use super::{join_names, named, Fmt}; + +impl<'a> Fmt<'a> { + /// A keyword and whatever the source wrote between it and what follows — + /// a space when that is nothing. + pub(super) fn word_then(&self, word: &str, comments: &[Comment], docs: &mut Vec) { + docs.push(text(word.to_string())); + if comments.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(comments, docs); + } + } + + /// A run of qualifier keywords, each followed by the space or the comment + /// the source wrote after it (`local /*c*/ static `). Always ends in a + /// separator, so the caller writes what follows without one of its own. + pub(super) fn qualifier_run(&self, run: &[Qualifier], docs: &mut Vec) { + for q in run { + docs.push(text(q.text.clone())); + if q.after.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&q.after, docs); + } + } + } + + /// The `pkg::cls::` written in front of an out-of-body definition's name, + /// one segment at a time so a comment beside a `::` prints where it was + /// written — and so an escaped segment keeps the space that terminates + /// it, which `named` supplies. + pub(super) fn scope_prefix(&self, scope: &[ScopeSeg], docs: &mut Vec) { + for seg in scope { + docs.push(text(named(&seg.name.text))); + self.slot_comments(&seg.before_sep, docs); + docs.push(text("::")); + self.slot_comments(&seg.after_sep, docs); + } + } + + /// `= value`, with the comments written on either side of the `=`. + pub(super) fn eq_default(&self, comments: &BinaryComments, value: Doc, docs: &mut Vec) { + self.slot_comments(&comments.before, docs); + docs.push(text(if comments.before.is_empty() { " =" } else { "=" })); + if comments.after.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&comments.after, docs); + } + docs.push(value); + } + + /// 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. + pub(super) 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]) + } + } + + /// The `;` that ends a statement, with whatever the source wrote in front + /// of it (`x = 1 /* inclusive */ ;`). [`StmtKind::takes_semi`] is what + /// says which kinds reach this; every other one prints its own `;` as + /// part of a body it does not own the end of. + pub(super) fn semi(&self, before_semi: &[Comment]) -> Doc { + if before_semi.is_empty() { + return text(";"); + } + let mut docs = Vec::new(); + if self.inline_comments(before_semi, &mut docs) { + docs.push(Doc::HardLine); + } else { + docs.push(text(" ")); + } + docs.push(text(";")); + 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} : {}", named(l))), + None => text(kw), + } + } + + /// The same, with the comments the source wrote in the label's two gaps + /// (`endgroup /*a*/ : /*b*/ cg`). The common case — no comment — is + /// [`Fmt::closing`] verbatim. + pub(super) fn closing_labeled( + &self, + kw: &str, + label: &Option, + c: &LabelComments, + ) -> Doc { + if c.is_empty() { + return Self::closing(kw, label); + } + let mut docs = vec![text(kw.to_string())]; + self.label_tail(label, c, &mut docs); + concat(docs) + } + + /// ` : name`, with the comments written in its two gaps. A no-op when no + /// label was written. + pub(super) fn label_tail( + &self, + label: &Option, + c: &LabelComments, + docs: &mut Vec, + ) { + let Some(l) = label else { + // A comment before a `:` that was never written belongs to + // whatever follows, and `gap_before` never took it. + debug_assert!(c.is_empty()); + return; + }; + self.slot_comments(&c.before_colon, docs); + docs.push(text(if c.before_colon.is_empty() { " :" } else { ":" })); + if c.after_colon.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&c.after_colon, docs); + } + docs.push(text(named(l))); + } + + /// `[ … ]` with the comments written in a segment's or a dimension's own + /// slots printed back between the same two tokens the source wrote them + /// between. `rest` is the `: lsb` half of a range, absent for an index. + /// + /// The opener's own slot (`base /*c*/ [`) belongs to whoever emitted the + /// base, so it is not printed here. + pub(super) fn bracket_slots( + &self, + comments: &SegmentComments, + first: Doc, + rest: Option<(&str, Doc)>, + ) -> Doc { + let mut docs = vec![text("[")]; + self.slot_comments(&comments.after_open, &mut docs); + docs.push(first); + if let Some((op, second)) = rest { + self.slot_comments(&comments.before_op, &mut docs); + docs.push(text(op.to_string())); + self.slot_comments(&comments.after_op, &mut docs); + docs.push(second); + } + self.slot_comments(&comments.before_close, &mut docs); + docs.push(text("]")); + concat(docs) + } + + /// `for` plus its `(`, with the gap between them. + pub(super) fn for_open(&self, comments: &ForComments, docs: &mut Vec) { + docs.push(text("for")); + if comments.after_kw.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&comments.after_kw, docs); + } + docs.push(text("(")); + self.slot_comments(&comments.after_open, docs); + } + + /// The `; ` between two sections of a `for` header, carrying whatever the + /// source wrote in the two gaps around it. + pub(super) fn for_semi(&self, before: &[Comment], after: &[Comment], docs: &mut Vec) { + self.slot_comments(before, docs); + docs.push(text(";")); + if after.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(after, docs); + } + } + + /// The `lhs op rhs` of a `for` header's initialiser or step. + pub(super) fn simple_assign(&self, a: &SimpleAssign, docs: &mut Vec) { + docs.push(self.expr(&a.lhs)); + self.slot_comments(&a.op_comments.before, docs); + docs.push(text(if a.op_comments.before.is_empty() { + format!(" {}", a.op) + } else { + a.op.clone() + })); + if a.op_comments.after.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&a.op_comments.after, docs); + } + docs.push(self.expr(&a.rhs)); + } + + pub(super) fn for_step(&self, step: &ForStep) -> Doc { + match step { + ForStep::Assign(a) => { + let mut docs = Vec::new(); + self.simple_assign(a, &mut docs); + concat(docs) + } + ForStep::Expr(e) => self.expr(e), + } + } + + /// The `[i, j]` of a `foreach` header — the one bracket group that + /// declares loop variables — with every comment written in it printed + /// back between the two tokens it was written between. + /// + /// Shared by the statement `foreach` and the constraint one, which write + /// the same grammar. + pub(super) fn foreach_vars(&self, vars: &[ForeachVar], comments: &SegmentComments) -> Doc { + if comments.is_empty() && vars.iter().all(|v| v.before.is_empty() && v.after.is_empty()) { + let names: Vec = vars.iter().map(|v| v.name.clone()).collect(); + return text(format!("[{}]", join_names(&names))); + } + let mut docs = Vec::new(); + self.slot_comments(&comments.before_open, &mut docs); + docs.push(text("[")); + self.slot_comments(&comments.after_open, &mut docs); + for (i, v) in vars.iter().enumerate() { + if i > 0 { + docs.push(text(",")); + } + self.slot_comments(&v.before, &mut docs); + if i > 0 && v.before.is_empty() { + docs.push(text(" ")); + } + docs.push(text(named(&v.name.text))); + self.slot_comments(&v.after, &mut docs); + } + self.slot_comments(&comments.before_close, &mut docs); + docs.push(text("]")); + concat(docs) + } +} diff --git a/crates/vlog_formatter/src/format/routine.rs b/crates/vlog_formatter/src/format/routine.rs new file mode 100644 index 0000000..6a55a98 --- /dev/null +++ b/crates/vlog_formatter/src/format/routine.rs @@ -0,0 +1,192 @@ +//! Functions and tasks: the argument list a `function`, `task`, +//! `covergroup` and `property` share (`tf_args`), the two declarations +//! with their prototype forms, `let`, and the DPI `import`/`export` +//! linkage. + +use crate::doc::*; +use vlog_parser::ast::*; +use vlog_parser::token::Comment; + +use super::list::ListItem; +use super::{join_paths, name_doc, named, Fmt}; + +impl<'a> Fmt<'a> { + pub(super) fn tf_args(&self, args: &[TfArg], dangling: &[Comment]) -> Doc { + let items: Vec = args + .iter() + .map(|a| { + let mut docs = Vec::new(); + if let Some(dir) = &a.dir { + docs.push(text(dir.clone())); + if a.after_dir.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&a.after_dir, &mut docs); + } + } + if let Some(t) = self.data_type(&a.ty) { + docs.push(t); + if a.before_name.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&a.before_name, &mut docs); + } + } else { + self.slot_comments(&a.before_name, &mut docs); + } + docs.push(name_doc(&a.name)); + docs.extend(self.unpacked_dims(&a.unpacked)); + if let Some(d) = &a.default { + self.slot_comments(&a.eq_comments.before, &mut docs); + docs.push(text(if a.eq_comments.before.is_empty() { " =" } else { "=" })); + if a.eq_comments.after.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&a.eq_comments.after, &mut docs); + } + docs.push(self.expr(d)); + } + ListItem::from_meta(&a.meta, concat(docs)) + }) + .collect(); + self.delimited_dangling("(", items, dangling, ")", false) + } + + pub(super) fn function(&self, f: &FunctionDecl) -> Doc { + let mut header = Vec::new(); + if let Some(d) = &f.dpi { + header.push(text(dpi_import_prefix(d))); + } + self.qualifier_run(&f.prefix, &mut header); + header.push(text("function")); + if f.after_kw.is_empty() { + header.push(text(" ")); + } else { + self.inline_comments_spaced(&f.after_kw, &mut header); + } + self.qualifier_run(&f.qualifiers, &mut header); + let mut named_ret = false; + if let Some(ret) = &f.ret { + if let Some(t) = self.data_type(ret) { + header.push(t); + named_ret = true; + } + } + if named_ret { + if f.before_name.is_empty() { + header.push(text(" ")); + } else { + self.inline_comments_spaced(&f.before_name, &mut header); + } + } else { + self.slot_comments(&f.before_name, &mut header); + } + self.scope_prefix(&f.scope, &mut header); + header.push(name_doc(&f.name)); + if f.has_parens { + self.slot_comments(&f.before_args, &mut header); + header.push(self.tf_args(&f.args, &f.args_dangling)); + } + header.push(self.semi(&f.before_semi)); + // 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_labeled("endfunction", &f.end_label, &f.end_label_comments), + text(if f.end_semi { ";" } else { "" }), + ]) + } + + pub(super) fn task(&self, t: &TaskDecl) -> Doc { + let mut header = Vec::new(); + if let Some(d) = &t.dpi { + header.push(text(dpi_import_prefix(d))); + } + self.qualifier_run(&t.prefix, &mut header); + header.push(text("task")); + if t.after_kw.is_empty() { + header.push(text(" ")); + } else { + self.inline_comments_spaced(&t.after_kw, &mut header); + } + self.qualifier_run(&t.qualifiers, &mut header); + self.slot_comments(&t.before_name, &mut header); + self.scope_prefix(&t.scope, &mut header); + header.push(name_doc(&t.name)); + if t.has_parens { + self.slot_comments(&t.before_args, &mut header); + header.push(self.tf_args(&t.args, &t.args_dangling)); + } + header.push(self.semi(&t.before_semi)); + 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_labeled("endtask", &t.end_label, &t.end_label_comments), + text(if t.end_semi { ";" } else { "" }), + ]) + } + + /// `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. + pub(super) fn let_decl(&self, l: &LetDecl) -> Doc { + let mut docs = vec![text(format!("let {}", named(&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(";")]) + } + + /// `export "DPI-C" function f;` / `export pkg::*;` — one line either way; + /// no list here is long enough to be worth a breakable group. + pub(super) 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(&named(&c.text)); + head.push_str(" = "); + } + text(format!("{head}{} {};", d.kw, named(&d.name.text))) + } + ExportDecl::Package(paths) => text(format!("export {};", join_paths(paths))), + } + } +} + +/// `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(&named(&c.text)); + s.push_str(" = "); + } + s +} diff --git a/crates/vlog_formatter/src/format/stmt.rs b/crates/vlog_formatter/src/format/stmt.rs new file mode 100644 index 0000000..19d4e60 --- /dev/null +++ b/crates/vlog_formatter/src/format/stmt.rs @@ -0,0 +1,659 @@ +//! Statements: the `begin … end` block, a statement as the body of a +//! header (a cuddled block or an indented line), the dispatch from +//! `StmtKind` to its layout, `if`/`else` chains, `case` items, and the +//! timing controls and sensitivity lists that head an `always` block or +//! a clocking event. +//! +//! `stmt_kind` is a dispatch table over `StmtKind` — one arm per +//! statement form — and stays whole; the forms with a layout of their own +//! (`if`, `case`) are the functions after it. + +use crate::doc::*; +use vlog_parser::ast::*; +use vlog_parser::span::TextRange; +use vlog_parser::token::Comment; + +use super::comment::{is_line_comment, trailing_ends_line}; +use super::{join_paths, named, skip_trivia, Fmt}; + +/// The pieces of a `begin … end` block a printer needs, gathered so the +/// two spellings (a statement, and a body cuddled onto a header) pass one +/// argument instead of six. +struct BlockDoc<'a> { + label_comments: &'a LabelComments, + label: &'a Option, + stmts: &'a [Stmt], + dangling: &'a [Comment], + end_label_comments: &'a LabelComments, + end_label: &'a Option, +} + +impl<'a> Fmt<'a> { + fn stmt(&self, s: &Stmt) -> Doc { + self.with_meta(&s.meta, self.stmt_kind(&s.kind, &s.before_semi)) + } + + pub(super) 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 + } + + /// 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. + pub(super) 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_comments, + label, + stmts, + dangling, + end_label_comments, + end_label, + .. + } => { + let mut docs = vec![prefix, text(" ")]; + docs.extend(self.leading_from(&s.meta, skip)); + docs.push(self.block_doc(BlockDoc { + label_comments, + label, + stmts, + dangling, + end_label_comments, + 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, &s.before_semi)); + body.extend(self.trailing(&s.meta)); + group(vec![prefix, indent(vec![Doc::Line, concat(body)])]) + } + } + } + + fn block_doc(&self, b: BlockDoc<'_>) -> Doc { + let mut docs = vec![text("begin")]; + self.label_tail(b.label, b.label_comments, &mut docs); + let mut body = Vec::new(); + if !b.stmts.is_empty() { + body.push(Doc::HardLine); + body.extend(self.stmt_seq(b.stmts)); + } + body.extend(self.dangling(b.dangling)); + docs.push(indent(body)); + docs.push(Doc::HardLine); + docs.push(self.closing_labeled("end", b.end_label, b.end_label_comments)); + concat(docs) + } + + fn timing_control(&self, tc: &TimingControl) -> Doc { + match tc { + TimingControl::Delay { after_hash, expr } => { + let mut docs = vec![text("#")]; + self.slot_comments(after_hash, &mut docs); + docs.push(self.expr(expr)); + concat(docs) + } + TimingControl::Event(sens) => self.sens_list(sens), + } + } + + pub(super) 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 { expr, after_at } => { + let mut docs = vec![text("@")]; + self.slot_comments(after_at, &mut docs); + docs.push(self.expr(expr)); + concat(docs) + } + 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, after_at } => { + // 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(e.clone())); + if i.after_edge.is_empty() { + parts.push(text(" ")); + } else { + self.inline_comments_spaced(&i.after_edge, &mut parts); + } + } + parts.push(self.expr(&i.expr)); + // `posedge clk iff enable` — the gate belongs to this + // term, so it prints before the separator, not after it. + if let Some(iff) = &i.iff { + parts.push(text(" iff ")); + parts.push(self.expr(iff)); + } + if self.inline_comments(&i.meta.before_sep, &mut parts) { + parts.push(Doc::HardLine); + } + } + let mut docs = vec![text("@")]; + self.slot_comments(after_at, &mut docs); + docs.push(text("(")); + docs.push(group(vec![indent(vec![Doc::SoftLine, concat(parts)]), Doc::SoftLine])); + docs.push(text(")")); + concat(docs) + } + } + } + + /// One arm per `StmtKind`. A dispatch table over the enum, so it stays + /// whole past the 150-line mark: the forms that grew a layout of their + /// own (`if`, `case`) are the functions after it, and every remaining + /// arm is a few lines of spelling. + fn stmt_kind(&self, kind: &StmtKind, before_semi: &[Comment]) -> Doc { + match kind { + StmtKind::Block { + label_comments, + label, + stmts, + dangling, + end_label_comments, + end_label, + .. + } => self.block_doc(BlockDoc { + label_comments, + label, + stmts, + dangling, + end_label_comments, + end_label, + }), + StmtKind::ForkJoin { + label_comments, + label, + join_kw, + stmts, + dangling, + end_label_comments, + end_label, + .. + } => { + let mut docs = vec![text("fork")]; + self.label_tail(label, label_comments, &mut docs); + 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_labeled(join_kw, end_label, end_label_comments)); + concat(docs) + } + StmtKind::If { qualifier, after_kw, cond, then, else_comments, els } => { + self.if_stmt(qualifier, after_kw, cond, then, else_comments, els) + } + StmtKind::Case { qualifier, kw, after_kw, expr, inside, items, dangling } => { + let mut docs = Vec::new(); + if let Some(q) = qualifier { + docs.push(text(format!("{q} "))); + } + self.word_then(kw, after_kw, &mut docs); + let (parens, taken) = match items.first() { + Some(first) => self.header_parens(expr, &first.meta), + None => (self.parens(expr), 0), + }; + docs.push(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, comments, body } => { + let mut header = Vec::new(); + self.for_open(comments, &mut header); + 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); + if fi.before_name.is_empty() { + d.push(text(" ")); + } else { + self.inline_comments_spaced(&fi.before_name, &mut d); + } + } + } else { + self.slot_comments(&fi.before_name, &mut d); + } + self.simple_assign(&fi.assign, &mut d); + concat(d) + }) + .collect(); + header.extend(join(init_parts, text(", "))); + self.for_semi(&comments.before_first_semi, &comments.after_first_semi, &mut header); + if let Some(c) = cond { + header.push(self.expr(c)); + } + self.for_semi( + &comments.before_second_semi, + &comments.after_second_semi, + &mut header, + ); + let step_parts: Vec = step.iter().map(|s| self.for_step(s)).collect(); + header.extend(join(step_parts, text(", "))); + self.slot_comments(&comments.before_close, &mut header); + 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, comments } => { + let mut docs = vec![text("do")]; + match &body.kind { + StmtKind::Block { + label_comments, + label, + stmts, + dangling, + end_label_comments, + end_label, + .. + } => { + docs.push(text(" ")); + docs.push(self.block_doc(BlockDoc { + label_comments, + label, + stmts, + dangling, + end_label_comments, + end_label, + })); + docs.push(text(" ")); + self.word_then("while", &comments.after_kw, &mut docs); + } + _ => { + docs.push(group(vec![indent(vec![Doc::Line, self.stmt(body)])])); + docs.push(Doc::HardLine); + self.word_then("while", &comments.after_kw, &mut docs); + } + } + docs.push(self.header_slots(cond, comments)); + docs.push(self.semi(before_semi)); + 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, var_comments, comments, body } => { + let mut head = vec![text("foreach")]; + self.slot_comments(&comments.after_kw, &mut head); + if comments.after_kw.is_empty() { + head.push(text(" ")); + } + head.push(text("(")); + self.slot_comments(&comments.after_open, &mut head); + head.push(self.expr(target)); + head.push(self.foreach_vars(vars, var_comments)); + self.slot_comments(&comments.before_close, &mut head); + head.push(text(")")); + self.stmt_as_body(concat(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), self.semi(before_semi)]) + } + 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(self.semi(before_semi)); + 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, self.semi(before_semi)]), + } + } + 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), self.semi(before_semi)]), + }, + StmtKind::ExprStmt(e) => concat(vec![self.expr(e), self.semi(before_semi)]), + StmtKind::EventTrigger(e) => { + concat(vec![text("-> "), self.expr(e), self.semi(before_semi)]) + } + StmtKind::VarDecl(d) => concat(vec![self.data_decl(d), self.semi(before_semi)]), + // The item form prints its own `;`. + StmtKind::Typedef(t) => self.typedef(t), + StmtKind::ParamDecl(d) => { + concat(vec![self.param_decl(d, None), self.semi(before_semi)]) + } + StmtKind::PortDecl(d) => concat(vec![self.port_decl(d), self.semi(before_semi)]), + StmtKind::Return { after_kw, expr } => match expr { + Some(e) => { + let mut docs = Vec::new(); + self.word_then("return", after_kw, &mut docs); + docs.push(self.expr(e)); + docs.push(self.semi(before_semi)); + concat(docs) + } + None => concat(vec![text("return"), self.semi(before_semi)]), + }, + StmtKind::Break => concat(vec![text("break"), self.semi(before_semi)]), + StmtKind::Continue => concat(vec![text("continue"), self.semi(before_semi)]), + StmtKind::Disable(name) => { + concat(vec![text(format!("disable {}", named(name))), self.semi(before_semi)]) + } + StmtKind::WaitFork => concat(vec![text("wait fork"), self.semi(before_semi)]), + 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!("{}: ", named(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::Assertion(a) => self.assertion(a), + StmtKind::Assert { kw, cond, then, els } => { + let mut docs = vec![text(format!("{kw} ")), self.parens(cond)]; + match (then, els) { + (None, None) => docs.push(self.semi(before_semi)), + (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, + after_kw: &[Comment], + cond: &Expr, + then: &Stmt, + else_comments: &[Comment], + els: &Option>, + ) -> Doc { + let mut head = Vec::new(); + if let Some(q) = qualifier { + head.push(text(format!("{q} "))); + } + self.word_then("if", after_kw, &mut head); + let (parens, taken) = self.header_parens(cond, &then.meta); + head.push(parens); + let prefix = concat(head); + // 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, + after_kw: ea, + 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, ea, 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. + pub(super) fn case_labels( + &self, + labels: &[ExprItem], + before_colon: &[Comment], + item: TextRange, + ) -> Doc { + if labels.is_empty() { + if !self.default_has_colon(item) { + return text("default"); + } + let mut docs = vec![text("default")]; + self.slot_comments(before_colon, &mut docs); + docs.push(text(":")); + return concat(docs); + } + 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.before_colon, 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")]) + } + + /// 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':') + } +} + +/// 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() +} diff --git a/crates/vlog_formatter/src/format/sva.rs b/crates/vlog_formatter/src/format/sva.rs new file mode 100644 index 0000000..d33c1af --- /dev/null +++ b/crates/vlog_formatter/src/format/sva.rs @@ -0,0 +1,519 @@ +//! Assertions (IEEE 1800-2017 §16): `property`/`sequence` declarations, +//! concurrent assertions with their action blocks, `disable iff`, and +//! the property-expression grammar. +//! +//! One layout rule, stated in `docs/features/sva-bodies/README.md`: the +//! spec's top-level operators — `|->`, `|=>`, `##`, `and`, `or` — break +//! one per line at the parent's indent when the spec does not fit on one +//! line; everything else is inline. Each operand is then laid out by the +//! same rule, so a wide operand of a broken operator breaks in turn and a +//! narrow one does not. + +use crate::doc::*; +use vlog_parser::ast::*; +use vlog_parser::token::Comment; + +use super::comment::{is_line_comment, trailing_ends_line}; +use super::{name_doc, Fmt}; + +impl<'a> Fmt<'a> { + /// `property p (args); … endproperty : p` and its `sequence` twin. + pub(super) fn prop_seq_decl(&self, d: &PropSeqDecl) -> Doc { + let end_kw = if d.kw == "sequence" { "endsequence" } else { "endproperty" }; + let mut docs = vec![text(d.kw.clone())]; + self.inline_comments_spaced(&d.before_name, &mut docs); + docs.push(name_doc(&d.name.text)); + if let Some(args) = &d.args { + // The parens hug the name, as a function's do; only a comment + // written in that gap puts anything between the two. + if !d.before_args.is_empty() { + self.inline_comments_spaced(&d.before_args, &mut docs); + } + docs.push(self.tf_args(&args.args, &args.dangling)); + } + if self.inline_comments(&d.before_semi, &mut docs) { + docs.push(Doc::HardLine); + } + docs.push(text(";")); + let mut body = Vec::new(); + for local in &d.locals { + body.push(if local.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); + body.push(self.with_meta(&local.meta, self.item_kind(&local.kind, None, 0))); + } + body.push(Doc::HardLine); + body.push(self.prop_spec(&d.spec)); + if d.spec_semi { + if self.inline_comments(&d.before_spec_semi, &mut body) { + body.push(Doc::HardLine); + } + body.push(text(";")); + } + body.extend(self.dangling(&d.dangling)); + docs.push(indent(body)); + docs.push(Doc::HardLine); + let end_label = d.end_label.as_ref().map(|l| l.text.clone()); + docs.push(self.closing_labeled(end_kw, &end_label, &d.end_label_comments)); + concat(docs) + } + + /// `[lbl :] assert property ( spec ) action_block`. + pub(super) fn assertion(&self, a: &AssertionDecl) -> Doc { + let mut docs = Vec::new(); + if let Some(label) = &a.label { + docs.push(name_doc(&label.text)); + self.slot_comments(&a.label_comments.before_colon, &mut docs); + docs.push(text(":")); + if a.label_comments.after_colon.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&a.label_comments.after_colon, &mut docs); + } + } + docs.push(text(a.kw.clone())); + if !a.kw2.is_empty() { + self.inline_comments_spaced(&a.after_kw, &mut docs); + docs.push(text(a.kw2.clone())); + } + if a.before_open.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&a.before_open, &mut docs); + } + docs.push(self.prop_parens(&a.after_open, &a.spec, &a.before_close)); + self.action_block(concat(docs), &a.action) + } + + /// `( spec )`. The parentheses hug the spec's first and last lines — a + /// spec that breaks does so *inside* them, one indent in, which is what + /// every multi-line assertion in the corpus is already written as. + fn prop_parens( + &self, + after_open: &[Comment], + spec: &PropSpec, + before_close: &[Comment], + ) -> Doc { + let mut inner = Vec::new(); + if self.inline_comments(after_open, &mut inner) { + inner.push(Doc::HardLine); + } else if !after_open.is_empty() { + inner.push(text(" ")); + } + inner.push(self.prop_spec(spec)); + let mut docs = vec![text("("), indent(inner)]; + if self.inline_comments(before_close, &mut docs) { + docs.push(Doc::HardLine); + } else if !before_close.is_empty() { + docs.push(text(" ")); + } + docs.push(text(")")); + concat(docs) + } + + /// `head` — the assertion through its closing `)` — followed by the + /// action block's pass and fail statements, laid out exactly as an `if` + /// statement's branches are: a block cuddles onto the line before it, a + /// single statement goes there if it fits and on an indented next line if + /// it does not, and `else` follows a block on its closing line. + fn action_block(&self, head: Doc, a: &ActionBlock) -> Doc { + if a.pass.is_none() && a.fail.is_none() { + let mut docs = vec![head]; + if self.inline_comments(&a.before, &mut docs) { + docs.push(Doc::HardLine); + } + docs.push(text(";")); + return concat(docs); + } + let Some(pass) = &a.pass else { + // `assert property (p) else $error(…);` — the `else` follows the + // spec's `)` directly, and takes the next line when it does not + // fit beside it. + let Some(fail) = &a.fail else { return head }; + let mut head = vec![head]; + self.inline_comments(&a.before_else, &mut head); + let head = concat(head); + let mut els = vec![text("else")]; + self.inline_comments(&a.after_else, &mut els); + // A `begin ... end` fail statement cuddles onto the assertion's + // own line, the way an `if`'s block branch does; measuring it + // would only ever say "does not fit", because a block holds a + // hard line break. + if matches!(fail.kind, StmtKind::Block { .. } | StmtKind::ForkJoin { .. }) { + return concat(vec![head, text(" "), self.stmt_as_body(concat(els), fail)]); + } + return group(vec![ + head, + indent(vec![Doc::Line, self.stmt_as_body(concat(els), fail)]), + ]); + }; + // A line comment trailing the pass statement runs to end of line, so + // a cuddled `else` would be swallowed into its text — `if_stmt`'s + // rule, for the same reason. + let pass_is_block = matches!(pass.kind, StmtKind::Block { .. } | StmtKind::ForkJoin { .. }) + && !trailing_ends_line(&pass.meta); + let mut docs = vec![self.stmt_as_body(head, pass)]; + let Some(fail) = &a.fail else { return concat(docs) }; + if !a.before_else.is_empty() { + docs.push(Doc::HardLine); + for c in &a.before_else { + docs.push(self.comment(c)); + docs.push(Doc::HardLine); + } + docs.push(text("else")); + } else if pass_is_block { + docs.push(text(" else")); + } else { + docs.push(Doc::HardLine); + docs.push(text("else")); + } + self.inline_comments(&a.after_else, &mut docs); + // The fail statement is measured on its own, not against the pass + // statement that already broke across lines: `if_stmt` passes an + // empty prefix here for the same reason, and the `else` above + // supplies the separator's left half. + docs.push(self.stmt_as_body(text(""), fail)); + concat(docs) + } + + /// `default disable iff ( expr );`. + pub(super) fn default_disable(&self, d: &DisableIff) -> Doc { + let mut docs = vec![text("default")]; + if d.before_kw.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&d.before_kw, &mut docs); + } + docs.push(self.disable_iff(d)); + if self.inline_comments(&d.before_semi, &mut docs) { + docs.push(Doc::HardLine); + } + docs.push(text(";")); + concat(docs) + } + + /// `disable iff ( expr )`, without the `default` spelling's `;`. + fn disable_iff(&self, d: &DisableIff) -> Doc { + let mut docs = vec![text("disable")]; + if d.after_disable.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&d.after_disable, &mut docs); + } + docs.push(text("iff")); + if d.after_iff.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&d.after_iff, &mut docs); + } + if d.parens { + docs.push(self.guard_parens(&d.expr, &d.after_open, &d.before_close)); + } else { + docs.push(self.expr(&d.expr)); + } + concat(docs) + } + + /// A `property_spec`: the clocking event, the `disable iff` and the + /// property expression, each on its own line when the three do not fit + /// on one. + fn prop_spec(&self, spec: &PropSpec) -> Doc { + let mut docs = Vec::new(); + for c in &spec.leading { + docs.push(self.comment(c)); + docs.push(if is_line_comment(&c.text) { Doc::HardLine } else { Doc::Line }); + } + if let Some(sens) = &spec.clocking { + docs.push(self.sens_list(sens)); + docs.push(Doc::Line); + } + if let Some(dis) = &spec.disable { + self.slot_comments(&dis.before_kw, &mut docs); + docs.push(self.disable_iff(dis)); + docs.push(Doc::Line); + } + // A comment written in front of the property expression prints where + // it was written — after whatever `Doc::Line` the header already + // pushed, so it starts the line rather than trailing a space onto it. + for c in &spec.before_expr { + docs.push(self.comment(c)); + docs.push(if is_line_comment(&c.text) { Doc::HardLine } else { Doc::Line }); + } + docs.push(self.prop_expr(&spec.expr)); + group(docs) + } + + /// True when a top-level operator of a spec breaks onto its own line. + /// The five the round's one layout rule names. + fn breaks_line(op: &PropOp) -> bool { + match op { + PropOp::Delay(_) => true, + PropOp::Word(w) => matches!(w.as_str(), "|->" | "|=>" | "and" | "or"), + } + } + + /// One arm per `PropKind`. A dispatch table over the enum, so it stays + /// whole past the 150-line mark; the `Paren` and `Call` arms spell the + /// same `( … , match items )` shape, which a later change may fold. + fn prop_expr(&self, e: &PropExpr) -> Doc { + match &e.kind { + PropKind::Expr(inner) => self.expr(inner), + PropKind::Paren(p) => { + let mut docs = vec![text("(")]; + if self.inline_comments(&p.after_open, &mut docs) { + docs.push(Doc::HardLine); + } else if !p.after_open.is_empty() { + docs.push(text(" ")); + } + docs.push(self.prop_expr(&p.expr)); + docs.extend(self.match_items(&p.items)); + if self.inline_comments(&p.before_close, &mut docs) { + docs.push(Doc::HardLine); + } else if !p.before_close.is_empty() { + docs.push(text(" ")); + } + docs.push(text(")")); + concat(docs) + } + PropKind::Binary(b) => { + let mut op = Vec::new(); + self.slot_comments(&b.comments.before, &mut op); + match &b.op { + PropOp::Word(w) => op.push(text(w.clone())), + PropOp::Delay(d) => op.push(self.cycle_delay(d)), + } + if b.comments.after.is_empty() { + op.push(text(" ")); + } else { + self.inline_comments_spaced(&b.comments.after, &mut op); + } + let lhs = self.prop_expr(&b.lhs); + let rhs = self.prop_expr(&b.rhs); + if Self::breaks_line(&b.op) { + return group(vec![lhs, Doc::Line, concat(op), rhs]); + } + concat(vec![lhs, text(" "), concat(op), rhs]) + } + PropKind::Unary(u) => { + let mut docs = vec![text(u.op.clone())]; + if u.comments.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&u.comments, &mut docs); + } + if let Some(count) = &u.count { + docs.push(self.sva_range("", &[], count)); + if u.after_count.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&u.after_count, &mut docs); + } + } + docs.push(self.prop_expr(&u.expr)); + concat(docs) + } + PropKind::Call(c) => { + let mut docs = vec![text(c.name.clone())]; + self.slot_comments(&c.before_open, &mut docs); + docs.push(text("(")); + if self.inline_comments(&c.after_open, &mut docs) { + docs.push(Doc::HardLine); + } else if !c.after_open.is_empty() { + docs.push(text(" ")); + } + docs.push(self.prop_expr(&c.expr)); + docs.extend(self.match_items(&c.items)); + if self.inline_comments(&c.before_close, &mut docs) { + docs.push(Doc::HardLine); + } else if !c.before_close.is_empty() { + docs.push(text(" ")); + } + docs.push(text(")")); + concat(docs) + } + PropKind::Abort(a) => { + let mut docs = vec![text(a.kw.clone())]; + if a.comments.after_kw.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&a.comments.after_kw, &mut docs); + } + docs.push(self.guard_parens( + &a.cond, + &a.comments.after_open, + &a.comments.before_close, + )); + if a.comments.before_body.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&a.comments.before_body, &mut docs); + } + docs.push(self.prop_expr(&a.expr)); + concat(docs) + } + PropKind::Delay(d) => { + let mut docs = vec![self.cycle_delay(&d.delay)]; + if d.after_delay.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&d.after_delay, &mut docs); + } + docs.push(self.prop_expr(&d.expr)); + concat(docs) + } + PropKind::Repeat(r) => { + let mut docs = vec![self.prop_expr(&r.expr)]; + self.slot_comments(&r.before_open, &mut docs); + docs.push(self.sva_range(&r.op, &r.after_op, &r.range)); + concat(docs) + } + PropKind::If(i) => { + let mut docs = vec![text("if")]; + if i.comments.after_kw.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&i.comments.after_kw, &mut docs); + } + docs.push(self.guard_parens( + &i.cond, + &i.comments.after_open, + &i.comments.before_close, + )); + if i.comments.before_body.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&i.comments.before_body, &mut docs); + } + docs.push(self.prop_expr(&i.then)); + if let Some(els) = &i.els { + self.slot_comments(&i.before_else, &mut docs); + docs.push(text(" else")); + if i.after_else.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&i.after_else, &mut docs); + } + docs.push(self.prop_expr(els)); + } + concat(docs) + } + PropKind::Case(c) => { + let mut docs = vec![text("case")]; + if c.comments.after_kw.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&c.comments.after_kw, &mut docs); + } + docs.push(self.guard_parens( + &c.cond, + &c.comments.after_open, + &c.comments.before_close, + )); + let mut body = Vec::new(); + for item in &c.items { + body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); + body.push(self.with_meta(&item.meta, self.prop_case_item(item))); + } + body.extend(self.dangling(&c.dangling)); + docs.push(indent(body)); + docs.push(Doc::HardLine); + docs.push(text("endcase")); + concat(docs) + } + PropKind::Spec(spec) => self.prop_spec(spec), + } + } + + fn prop_case_item(&self, item: &PropCaseItem) -> Doc { + let mut docs = Vec::new(); + if item.is_default { + docs.push(text("default")); + } else { + docs.push(self.plain_expr_list(&item.labels)); + } + self.slot_comments(&item.before_colon, &mut docs); + docs.push(text(":")); + if item.after_colon.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&item.after_colon, &mut docs); + } + docs.push(self.prop_expr(&item.expr)); + if self.inline_comments(&item.before_semi, &mut docs) { + docs.push(Doc::HardLine); + } + docs.push(text(";")); + concat(docs) + } + + /// `, x = e, y++` — the match items of a parenthesised sequence. + fn match_items(&self, items: &[MatchItem]) -> Vec { + let mut docs = Vec::new(); + for item in items { + self.slot_comments(&item.before_comma, &mut docs); + docs.push(text(", ")); + docs.extend(self.leading(&item.meta)); + docs.push(self.expr(&item.lhs)); + if let Some(op) = &item.op { + self.slot_comments(&item.comments.before, &mut docs); + docs.push(text(format!(" {op}"))); + if item.comments.after.is_empty() { + docs.push(text(" ")); + } else { + self.inline_comments_spaced(&item.comments.after, &mut docs); + } + } + if let Some(rhs) = &item.rhs { + docs.push(self.expr(rhs)); + } + } + docs + } + + /// `##3`, `##[1:$]`, `##[+]`. + fn cycle_delay(&self, d: &CycleDelay) -> Doc { + let mut docs = vec![text("##")]; + self.slot_comments(&d.after_hash, &mut docs); + if let Some(e) = &d.expr { + docs.push(self.expr(e)); + } + if let Some(range) = &d.range { + docs.push(self.sva_range("", &[], range)); + } + concat(docs) + } + + /// `[*3]`, `[=1:2]`, `[->1]`, `[+]`, and the bare `[2]` count of a + /// `nexttime`. `op` is empty for the two that write none. + fn sva_range(&self, op: &str, after_op: &[Comment], r: &SvaRange) -> Doc { + let mut docs = vec![text("[")]; + self.slot_comments_tight(&r.after_open, &mut docs); + if !op.is_empty() { + docs.push(text(op.to_string())); + self.slot_comments_tight(after_op, &mut docs); + } + if !r.shorthand.is_empty() { + docs.push(text(r.shorthand.clone())); + } + if let Some(lo) = &r.lo { + docs.push(self.expr(lo)); + } + if let Some(hi) = &r.hi { + self.slot_comments_tight(&r.before_colon, &mut docs); + docs.push(text(":")); + self.slot_comments_tight(&r.after_colon, &mut docs); + docs.push(self.expr(hi)); + } + self.slot_comments_tight(&r.before_close, &mut docs); + docs.push(text("]")); + concat(docs) + } + + /// [`Fmt::slot_comments`] for a slot that writes no space of its own: the + /// inside of a `[ ... ]` bound, where `[*3]` must stay tight. + fn slot_comments_tight(&self, comments: &[Comment], docs: &mut Vec) { + if comments.is_empty() { + return; + } + self.inline_comments(comments, docs); + docs.push(text(" ")); + } +} diff --git a/crates/vlog_formatter/src/format/verbatim.rs b/crates/vlog_formatter/src/format/verbatim.rs new file mode 100644 index 0000000..c2741a6 --- /dev/null +++ b/crates/vlog_formatter/src/format/verbatim.rs @@ -0,0 +1,171 @@ +//! Bytes the formatter copies rather than lays out: fenced +//! (`// verilog_format: off`) regions, the untouched runs of a `--lines` +//! pass, compiler directives, attributes and macro invocations — and the +//! one rule that keeps a multi-line copy a fixed point, `raw_lines`'s +//! dedent by original column. +//! +//! The cut is "text that has no layout of its own": everything here is +//! reproduced, at most re-indented, so a change to *what* is verbatim (a +//! new fence kind, a new directive shape) lands in this file and no other. + +use crate::doc::*; +use crate::fence::{self, Region}; +use crate::range::Split; +use crate::verify::line_starts_inside_string; +use vlog_parser::ast::*; +use vlog_parser::span::TextRange; +use vlog_parser::token::Comment; + +use super::Fmt; + +/// What a comment turns into: itself, the verbatim region it opens, or +/// nothing at all because a region already covers its bytes. +pub(super) enum Slot<'r> { + Normal, + Opens(&'r Region), + Covered, +} + +impl<'a> Fmt<'a> { + /// What to do with one comment, given the fenced regions of the source. + pub(super) 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. + pub(super) 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. + pub(super) 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. + pub(super) 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. + pub(super) 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. + pub(super) fn verbatim(&self, r: &Region) -> Doc { + Doc::Verbatim(self.src.get(r.start..r.end).unwrap_or_default().to_string()) + } + + /// 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). + pub(super) 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). + pub(super) 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. + pub(super) fn with_block(&self, raw: &RawText) -> Doc { + Doc::Inline(raw.text.clone()) + } + + /// 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. + pub(super) fn macro_call(&self, call: &MacroCall) -> Doc { + let body = self.raw_text(&call.raw); + if call.semi { + concat(vec![body, text(";")]) + } else { + body + } + } + + /// 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. + pub(super) 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) + } +} + +/// 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) +} + +/// Drop up to `n` leading spaces or tabs. +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 +} diff --git a/docs/features/decomposition-formatter/README.md b/docs/features/decomposition-formatter/README.md new file mode 100644 index 0000000..86115ed --- /dev/null +++ b/docs/features/decomposition-formatter/README.md @@ -0,0 +1,423 @@ +# decomposition-formatter — TODO §28 Lane B: `vlog_formatter/src/format.rs` → `format/` + +## Goal + +Split the 5 443-line `crates/vlog_formatter/src/format.rs` into a +`format/` module directory a human can navigate: one file per grammar +domain (items, module boundary, instantiations, declarations, routines, +classes, covergroups, SVA, statements, expressions) on top of four files +of shared machinery (comments, verbatim bytes, recurring phrases, lists +and alignment), each describable in one sentence. A **pure move**: no +behaviour change, no renamed item, every public path preserved from +`vlog_formatter::format`, formatter output byte-identical over the corpus +and opentitan, test counts unchanged. The reason beyond the file-size rule +is the same as for the whole round: `format.rs` is where every formatter +feature lane collided, and after this lanes that touch different grammar +domains can run in parallel. + +## Assumptions + +- The four public items (`Config`, `FormatError`, `format_source`, + `format_range`) stay in `format/mod.rs`, so the public path + `vlog_formatter::format::*` and the crate-root re-exports are unchanged + by construction; the sibling modules are private (`mod x;`, not `pub`), + so no new public path appears. +- `Fmt`'s fields stay private; child modules read them because Rust lets a + descendant see its ancestors' private items. Methods a *sibling* file + calls are `pub(super)` — visible inside `format/` and nowhere else — + and that marking doubles as the reader's list of a module's entry + points. +- `verify.rs` is not touched (hard invariant 4). `lib.rs` is not touched: + its `pub mod format;` resolves to `format/mod.rs` unchanged. +- No `#[cfg(test)]` block lives in `format.rs`; the crate's 31 unit tests + are in the sibling modules (`align`, `fence`, `printer`, `range`, + `verify`), so nothing moves in the test tree. +- Byte-identity is measured over the Verilog files under `corpus/` + (`.sv .svh .v .vh`) and `opentitan/hw`, `--stdout` only, against + `/tmp/lucisv-0.33.0-baseline` (a release build of 159f6a0). + +## Handshakes + +- **Consumes** (unchanged): `vlog_parser::ast::*`, `crate::doc`, + `crate::align`, `crate::fence`, `crate::printer`, `crate::range`, + `crate::verify`. +- **Promises** (unchanged): `vlog_formatter::format::{Config, + FormatError, format_source, format_range}` at the same paths with the + same signatures; `lib.rs` re-exports untouched. +- **Requests**: none. Nothing outside `crates/vlog_formatter/src/format/` + and this README (plus the Lane B line of `TODO.md`) changes. + +## Status / TODO + +- [x] Baseline pinned: test counts, public item list (`cargo doc`), + longest-function census, `/tmp/lucisv-0.33.0-baseline` present +- [x] `git mv src/format.rs src/format/mod.rs` +- [x] Sibling files carved; `cargo build -p vlog_formatter` green +- [x] `cargo test -p vlog_formatter` counts equal to baseline + (31/1/5/6/2/22/208/0 — identical) +- [x] Text-level purity: every non-blank line of the old file appears in + the new tree (line multiset diff) +- [x] `cargo fmt -p vlog_formatter` (`--check` clean), `cargo clippy + --all-targets --workspace` 0 warnings, `cargo doc` 0 warnings, + `cargo test --workspace` 48 binaries / 3 215 passed / 0 failed +- [x] Byte-identity: corpus + opentitan `--stdout` vs baseline — 4 807 + files, 0 differing (stdout, exit code and stderr all identical) +- [x] Public item list diffed: no path changed (46 `cargo doc` pages, + `diff` empty) +- [x] `TODO.md` Lane B line ticked + +## Work log + +### 2026-09-02 — baseline + +Branch `decomp-formatter` at 159f6a0 (v0.33.0), worktree +`.claude/worktrees/decomp-formatter`. + +Pinned `cargo test -p vlog_formatter` (per binary): + +| binary | tests | +|---|---| +| `src/lib.rs` unit tests | 31 | +| `tests/cases.rs` | 1 (the snapshot + idempotency suite, 941 cases inside) | +| `tests/deep_nesting.rs` | 5 | +| `tests/fences.rs` | 6 | +| `tests/fixtures.rs` | 2 | +| `tests/ranges.rs` | 22 | +| `tests/verification.rs` | 208 | +| doc-tests | 0 | +| **sum** | **275** | + +Public items of `vlog_formatter` per `cargo doc --no-deps`: 46 HTML +pages, of which under `format/`: `enum.FormatError`, `fn.format_range`, +`fn.format_source`, `struct.Config`, `index`. + +Longest functions in `format.rs` before (production lines, brace-matched): + +| fn | lines | old line | +|---|---|---| +| `stmt_kind` | 279 | 4413 | +| `expr` | 233 | 4890 | +| `prop_expr` | 168 | 3959 | +| `constraint_item_kind` | 98 | 3079 | +| `item_kind` | 96 | 1325 | +| `sens_list` | 83 | 4329 | +| `module_head` | 81 | 1463 | +| `cont_assign` | 71 | 2093 | +| `select_expr` | 66 | 3648 | +| `data_type` | 65 | 1652 | + +Three functions are over 150 lines and all three are dispatch tables over +an enum (`StmtKind`, `ExprKind`, `PropKind`): they stay whole, each with +a comment saying so. `prop_expr` was given the look §28 asks for: its +`Paren` and `Call` arms share a shape (`(`, comments, expr, match items, +comments, `)`) that a future lane could fold into one helper, but that is +a code change, not a move, and is left as a note. + +### 2026-09-02 — the split (method) + +`git mv src/format.rs src/format/mod.rs` first, so history follows the +file that keeps the public items. Every sibling file was then assembled +by *copying* line ranges out of the pristine `mod.rs` (a module doc +comment, the `use` lines, one `impl<'a> Fmt<'a> { … }` block, the free +functions), and `mod.rs` was rewritten through the Write tool to exactly +the items it keeps. No sed/Python deletion touched any source file. The +proof that nothing was lost is the line-multiset comparison below plus +the gates. + +Deviations from a literal move, all documentation-only: + +- Three doc comments in the old file were attached to the wrong item + (a blank-line slip): `ListItem`'s ("A list element ready for comma-list + layout…") sat above `BlockDoc`; `named`'s ("A name, plus the space…") + ran straight into `holds_verbatim_value`'s; `strip_blanks`'s one-liner + ("Drop up to `n` leading spaces or tabs.") sat above + `crosses_line_inside_string`. Each now sits on its own item. +- Section banners (`// ---- Module ----`) became module doc comments; the + SVA banner's layout-rule paragraph is now `sva.rs`'s module doc. +- Three doc comments said "this file" about a fact that now spans the + directory (`named`'s audit note twice, `with_constraint_block`'s "the one + thing this file already reads `src` for"); each now says "the formatter" + or "`format/`". The three dispatch tables (`stmt_kind`, `expr`, + `prop_expr`) each gained the one-line doc comment §28 asks for, saying + why they stay whole. +- Visibility: `Fmt`, its fields and the free helpers in `mod.rs` stay + private (children see them). Inside the siblings, exactly the methods, + associated functions, the `ListItem` struct with four of its fields, the + `Slot` enum and `drive_strength` that another sibling calls are + `pub(super)`; everything else stays private to its file. The set was + taken from the compiler (E0624/E0603/E0616), not guessed, so it is the + minimal cross-file interface. + +The line-multiset check: `git show HEAD:…/format.rs` vs `cat format/*.rs`, +`pub(super) ` stripped, blank lines dropped, both sorted, `comm`. Lines +only in the original: the fifteen `// ---- Section ----` banner lines, +the SVA banner's six prose lines (now `sva.rs`'s `//!`), and the three +reshuffled `use` lines. Lines only in the new tree: `//!` module docs, +`use`/`mod` lines, `impl<'a> Fmt<'a> {` / `}` wrappers. Nothing else. + +### 2026-09-02 — module map + +Old `format.rs` line ranges (159f6a0) → new file. "prod" is non-blank, +non-comment lines; "total" is `wc -l`. Old file: 5 443 total. + +| new file | one sentence | prod | total | old `format.rs` lines | +|---|---|---|---|---| +| `mod.rs` | What the crate exports, the `Fmt` state, and the name helpers every module writes an identifier through. | 152 | 259 | 1–30, 43–161, 5279–5297 + 5314–5325, 5327–5354, 5414–5443 | +| `verbatim.rs` | Bytes copied rather than laid out: fences, `--lines` runs, directives, attributes, macro calls, and the re-indent rule for multi-line raw text. | 87 | 171 | 163–169, 236–278, 292–303, 310–330, 376–418, 5371–5388 | +| `comment.rs` | Where a comment prints relative to the tokens around it: leading/trailing, gap slots, inside parentheses, dangling. | 192 | 301 | 305–308, 420–557, 650–662, 690–695, 1027–1090, 1166–1178, 3185–3195, 5390–5393, 5404–5412 | +| `phrase.rs` | Recurring two/three-token phrases with comment gaps: keyword-then, `= value`, `;`, `end : label`, `[a:b]`, `for` punctuation, `foreach [i,j]`. | 188 | 257 | 332–370, 559–648, 664–688, 1015–1025, 2590–2599, 4231–4247, 5124–5153 | +| `list.rs` | Comma lists — bracketed, bare, with directives between elements — and the alignment planner that pads rows. | 226 | 335 | 179–180, 193–229, 697–827, 833–903, 1007–1013, 3235–3281 | +| `item.rs` | File/fragment, item sequences and blank lines, `ItemKind` dispatch, `package`, generate constructs, `assign`. | 436 | 535 | 1100–1153, 1184–1420, 1426–1443, 2074–2163, 2480–2588 | +| `module.rs` | A module or interface's boundary: header through `;`, ANSI/non-ANSI ports and their alignment, modports, clocking. | 301 | 365 | 31–32, 905–924, 1445–1645, 2708–2829 | +| `instance.rs` | Instantiations: overrides, instance lists, named/ordered connections and their alignment, `bind`, gates. | 292 | 385 | 34–37, 926–942, 997–1005, 2165–2474, 5271–5277, 5298–5312 | +| `decl.rs` | Data types, dimensions, declarators, `parameter`/`localparam` and their alignment, `typedef`, `enum`/`struct` bodies. | 367 | 452 | 39–41, 944–995, 1651–1742, 1785–2068 | +| `routine.rs` | Functions, tasks, the argument list they share with covergroups and properties, `let`, DPI import/export. | 172 | 192 | 2605–2644, 2831–2857, 2859–2952, 5356–5369 | +| `class.rs` | Class headers/bodies and every constraint form, including `dist`. | 283 | 369 | 2646–2706, 2958–3183, 3197–3233, 3283–3306 | +| `cover.rs` | Covergroups: header, coverpoints/crosses, bins and their specs, options. | 369 | 414 | 3312–3713 | +| `sva.rs` | Assertions: property/sequence declarations, action blocks, `disable iff`, the property-expression grammar. | 448 | 519 | 3715–4221 | +| `stmt.rs` | Statements: blocks, body-of-header, `StmtKind` dispatch, `if`/`case`, timing controls and sensitivity lists. | 573 | 659 | 181–191, 1092–1098, 1155–1164, 4227–4229, 4249–4834, 5395–5402 | +| `expr.rs` | Expressions: `ExprKind` dispatch, binary chains, ternaries with comments, the compact `[…]` spelling, postfix forms. | 387 | 481 | 171–177, 280–290, 1744–1783, 4840–5122, 5155–5268 | + +Cut points that differ from §28's sketch, and why: + +- §28 put instantiations, connections and `bind` in `module.rs`. Together + with the header, ports, modports and clocking that is ~800 lines, so the + instantiation side is `instance.rs`: a connection's `(` is the one column + an instance list aligns on, and its cells, column spec and planner now + sit in one file. +- §28 put constraints and covergroups in `class.rs`. That is ~820 lines + and two sentences, so covergroups are `cover.rs`. +- §28 had `directive.rs`. What is actually directive-shaped in the code is + "text reproduced rather than laid out" — directives, attributes, macro + calls *and* fenced regions share one `raw_text`/`Doc::Inline` path — so + the file is `verbatim.rs` and says so. +- §28 kept the comment-slot machinery in `mod.rs`. With the entry points + and name helpers that is ~1 000 lines, so the machinery is three files + by what it does: `comment.rs` (placing comments), `phrase.rs` (the + small phrases every construct spells the same way), `list.rs` (lists + and alignment). Each construct's *row* — an ANSI port's cells, a + connection's, a `parameter`'s — lives beside the construct, not in + `list.rs`, so a change to how one construct aligns touches one file. +- `routine.rs` (functions/tasks/`let`/DPI) is under the 300-line target on + purpose: folding it into `decl.rs` would make that file's sentence grow + an "and function bodies", and `tf_args` is called from three domains + (`routine`, `cover`, `sva`) so it wants a named home. + +No file is over 600 production lines (`stmt.rs` at 573 is the largest; +280 of it is the `stmt_kind` dispatch table). The only functions over 150 +lines are the three dispatch tables (`stmt_kind` 279, `expr` 233, +`prop_expr` 168), unchanged in length, each with a doc comment saying so. +No function was split. + +### 2026-09-02 — gates + +- `cargo fmt -p vlog_formatter` applied; `-- --check` clean. +- `cargo clippy --all-targets --workspace`: 0 warnings. No `#[allow]` + introduced. +- `cargo doc -p vlog_formatter --no-deps`: 0 warnings (one intra-doc link + from the public `format` module doc to the private `Fmt` was turned + into plain code font to keep it so). +- `cargo test -p vlog_formatter`: 31 / 1 / 5 / 6 / 2 / 22 / 208 / 0 — + identical to the pinned baseline, sum 275. +- `cargo test --workspace`: 48 binaries, 3 215 passed, 0 failed. +- Public item list (`cargo doc` page list, 46 pages): `diff` against the + baseline list is empty. +- `cargo build --release -p lucisv` in the worktree for the byte-identity + run (result in the next entry). + +Git state note: the rename was staged by `git mv` at the start; a +pathspec `git reset` used while measuring the diff un-staged it, and it +was re-staged with `git add`. The index now shows `D format.rs` + +`A format/mod.rs` rather than `R`, because git labels a rename only while +the new file is ≥50 % similar and the 259-line `mod.rs` is not — the +`git blame` discontinuity §28 accepts. Nothing was committed. + +### 2026-09-02 — byte-identity + +`target/release/lucisv` (this worktree) vs `/tmp/lucisv-0.33.0-baseline`, +`--stdout` on every `.sv/.svh/.v/.vh` under +`/Users/guoliangchen/repo/verilogrustformatter/corpus` (860 files) and +`/Users/guoliangchen/repo/opentitan/hw` (3 947 files), stdout, stderr and +exit code captured per file and compared with `cmp`: + +``` +files=4807 stdout_differing=0 exit_code_differing=0 stderr_differing=0 +exit0=4790 exit_nonzero=17 +``` + +The 17 non-zero exits are the same 17 on both binaries (the files the +formatter refuses at 0.33.0). opentitan was touched with `--stdout` only; +`git -C …/opentitan status --porcelain` before and after shows exactly +`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ast.sv`, +`hw/top_earlgrey/ip/ast/rtl/ast.sv` — the pre-existing modifications. + +Handshake requests: none. Files changed: `crates/vlog_formatter/src/ +format.rs` → `format/{mod,verbatim,comment,phrase,list,item,module, +instance,decl,routine,class,cover,sva,stmt,expr}.rs`, this README, and +the Lane B line of `TODO.md`. + +## QA log + +### 2026-09-02 — verification + +Scope check first: `git diff --stat 159f6a0 -- crates/vlog_formatter/src/verify.rs` +empty, `crates/vlog_formatter/src/lib.rs` diff empty. `git status --porcelain` +touches only `crates/vlog_formatter/src/`, `docs/features/ +decomposition-formatter/`, `TODO.md`; `TODO.md`'s diff is exactly the +Lane B line flipped to `[x]`. + +**Gates** (all in the dev worktree): + +- `cargo fmt -p vlog_formatter -- --check`: clean. +- `cargo clippy --all-targets --workspace` (forced a rebuild with `touch` + first, since a cached run prints nothing): 0 warnings. + `git diff 159f6a0 -- crates/vlog_formatter/` has no added `+#[allow` + line anywhere. +- `cargo doc -p vlog_formatter --no-deps`: 0 warnings. +- `cargo test -p vlog_formatter --no-fail-fast`: per-binary 31 / 1 / 5 / + 6 / 2 / 22 / 208 / 0 — identical to the pinned baseline. +- `cargo test --workspace --no-fail-fast`: 48 binaries, sum of + `test result:` lines = 3 215 passed, 0 failed — matches the claim + exactly. + +**Pure-move, mechanically.** Line-multiset check reproduced independently +(not from a throwaway worktree — none of this touches a tracked file): +`git show 159f6a0:…/format.rs` vs `cat format/*.rs`, both with leading/ +trailing whitespace stripped, `^pub(super) ` stripped, blank lines +dropped, sorted, `comm -23`/`comm -13`. Old-only: 64 lines — the 28 +banner/divider lines, 14 section-title lines, 5 SVA-banner prose lines, +3 "this file" doc-comment originals, 4 reshuffled `use` lines, and 8 +single-line versions of function signatures that rustfmt rewrapped once +`pub(super)` pushed them past 100 columns. New-only: 300 lines — `use`/ +`mod`/`impl<'a> Fmt<'a> {` structure, `//!` doc comments (including the +new "why it stays whole" lines on the three dispatch tables and the +three reworded "this file" → "the formatter"/`format/` comments the work +log logs), and the wrapped continuation lines of those same 8 +signatures. Every line on either side is accounted for by the dev's +logged deviations; nothing else differs. + +Function-signature census (own script, not the dev's): extracted every +`fn` signature (name + params + return type, whitespace-normalized, +visibility keyword stripped) from old `format.rs` and from the new tree. +201 signatures on each side. The only 8 that don't match textually are +exactly the same 8 rustfmt-rewrapped ones above — same name, same +params in the same order and types, same return type; the only +difference is a trailing comma rustfmt inserts on a multi-line arg list. +No function added, removed, renamed, retyped, reordered, or split. + +**Public API.** `cargo doc -p vlog_formatter --no-deps` in the dev +worktree: 46 HTML pages. Built independently at 159f6a0 in a throwaway +worktree (`git worktree add .claude/worktrees/qa-baseline-b 159f6a0`, +removed after): also 46 pages, `diff` of the sorted page-path lists is +empty — no path added, removed, or renamed. The workspace test run +above already proves every other crate compiles unchanged against the +new `format/` tree. + +**Byte-identity, independently reproduced.** Rebuilt +`/tmp/lucisv-0.33.0-baseline` myself from the 159f6a0 worktree +(`cargo build --release -p lucisv`) and `shasum -a 256` matched the +dev's pinned baseline exactly, so the baseline binary is a genuine +159f6a0 build. Built `target/release/lucisv` in the dev worktree and +ran `--stdout` over every `.sv/.svh/.v/.vh` under `corpus/` (860 files) +and `opentitan/hw` (3 947 files) against that baseline, comparing +stdout, stderr and exit code per file: + +``` +files=4807 stdout_differing=0 exit_code_differing=0 stderr_differing=0 +exit0=4790 exit_nonzero=17 +``` + +Identical to the dev's numbers. `git -C opentitan status --porcelain` +before and after the run shows exactly the same three pre-existing +modified files (`hw/ip/aes/dv/tb/tb.sv`, `hw/top_darjeeling/ip/ast/rtl/ +ast.sv`, `hw/top_earlgrey/ip/ast/rtl/ast.sv`) — opentitan untouched by +the run itself. + +**Size rule.** Recounted production/total lines per file with an +independent script (non-blank, non-`//`/`///`/`//!`-only lines; no +`#[cfg(test)]` block in any of the 15 files). All 15 files' production +counts match the README's table exactly. One discrepancy in the +**total** column: `sva.rs` is 519 lines by `wc -l`, not the 516 the +README's table states (the production count, 448, is correct on both +sides — this is a `wc -l` transcription slip in the "total" column +only, not a content or size-rule problem). Longest-function census +(brace-matched, independent script) over all 15 files: only `stmt_kind` +(279), `expr` (233) and `prop_expr` (168) exceed 150 lines, matching +the claim exactly; each carries a one-line doc comment saying it is a +dispatch table over an enum and stays whole. No file exceeds 800 +production lines (`stmt.rs` at 573 is the largest). + +**One-sentence test**, read fresh off each file's contents and `//!` +doc, not the README's table: + +- `mod.rs`, `verbatim.rs`, `comment.rs`, `phrase.rs`, `list.rs`, + `item.rs`, `module.rs`, `instance.rs`, `decl.rs`, `routine.rs`, + `class.rs`, `stmt.rs`, `expr.rs`, `sva.rs`: each describable in one + sentence whose "and" clauses enumerate forms inside a single grammar + domain or a single piece of shared machinery (not two unrelated + responsibilities) — no MEDIUM here. `mod.rs`'s sentence joins three + things (exports, `Fmt` state, name helpers), but that is the ordinary + shape of a directory's `mod.rs` and stays small (152 prod lines); not + flagged. +- Every file's `//!` states why the cut is where it is (a shared + boundary, a dispatch-table rationale, a "this belongs to the sibling + that already owns X" note) **except `cover.rs`**: its doc comment + is purely descriptive (header/coverpoint/cross/bins/options) with no + sentence saying why covergroups are their own file. The rationale + exists — one sentence, in `class.rs`'s doc ("Covergroups, the other DV + construct a class holds, are large enough to be a sibling module") and + in the work log — but `cover.rs` itself doesn't carry it. LOW: add one + clause to `cover.rs`'s `//!` (or leave as is; it is discoverable from + `class.rs` and the README). + +**Docs.** README has all seven required sections in order. Module-map +spot-check, five ranges read out of `git show 159f6a0:…/format.rs` and +matched against file contents: `verbatim.rs` 163–169 (the `Slot` enum +doc + body), `routine.rs` 2605–2644 (`tf_args` — confirmed only in +`routine.rs` by `grep -l`), `cover.rs` 3312–3713 (covergroup doc comment +at the start; the range end lands inside `select_expr`, at first glance +an odd fit for a "covergroup" file, but `SelectExpr` (`vlog_parser::ast` +line 2886) is the bin-select-expression AST node from IEEE 1800 §19 — +`binsof`/`with`/`select` — so it is covergroup-only and correctly +carved into `cover.rs`; confirmed `select_expr` exists only in +`cover.rs` by `grep -l`), `sva.rs` 3715–4221 (SVA section banner at the +start, `slot_comments_tight`'s body at the end, both present verbatim in +`sva.rs`), `instance.rs` 5271–5277 + 5298–5312 (`drive_strength` and +`holds_verbatim_value`, both confirmed only in `instance.rs`). All five +check out. + +`TODO.md`: only the Lane B line changed, `[ ]` → `[x]`, text otherwise +identical — confirmed by `git diff 159f6a0 -- TODO.md`. + +**Findings summary** + +- LOW: `sva.rs` table "total" column says 516, actual `wc -l` is 519 + (production count 448 is correct both places). +- LOW: `cover.rs`'s `//!` doc doesn't itself say why covergroups are a + separate file (rationale lives in `class.rs`'s doc and the work log + instead). + +No HIGH or CRITICAL findings: no changed code line, no dropped or +altered content, no public path change, no test-count drop, no output +or exit-code difference, opentitan untouched beyond its pre-existing +diffs. + +**Verdict: PASS** — three LOW doc nits, no forcing findings. + +## Review + +**2026-09-02 — lead.** Accepted; merged fast-forward as the first lane of +§28. This is what a pure move should look like: fifteen files a reader +can name in one sentence each, the three dispatch tables left whole and +saying so, `pub(super)` entry points taken from the compiler rather than +guessed, and the proof done twice — the dev's line-multiset and +signature census, then QA's from scratch — on top of the gates +(per-binary counts identical, 4 807 files byte-identical, public item +list unchanged). The cuts that differ from the plan are better than the +plan: `instance` out of `module`, `cover` out of `class`, `verbatim` +instead of `directive`, and the comment machinery out of `mod.rs`, which +would otherwise have been the thousand-line file the round exists to +remove. The wholesale `Write` of `mod.rs` is acceptable because the +multiset check exists; it would not be without it. QA's two LOW nits +fixed at review: the `sva.rs` total and a why-sentence in `cover.rs`'s +module doc.