Files
lucisv/crates/vlog_formatter/src/format/comment.rs
T
lucioandClaude Fable 5 35f0b8d371
ci / checks (push) Successful in 1m1s
ci / corpus (push) Successful in 28s
Decomposition, lane B: vlog_formatter's format.rs becomes fifteen modules, a pure move
TODO section 28, lane B (the file-size rule in CLAUDE.md).
format.rs (5 444 production lines) becomes format/{mod, verbatim,
comment, phrase, list, item, module, instance, decl, routine, class,
cover, sva, stmt, expr}.rs - no file over 600 production lines, the
three dispatch tables (stmt_kind, expr, prop_expr) left whole and
documented as such, sibling modules private with pub(super) entry
points, every public path unchanged (cargo doc item list identical).
Proof: per-binary test counts identical (31/1/5/6/2/22/208/0; workspace
3 215 / 48), 4 807 corpus + opentitan files byte-identical to the
v0.33.0 binary in stdout, exit code and stderr, and a line-multiset +
function-signature census showing only use lines, visibility keywords,
banners and doc comments differ - done by the dev and re-done from
scratch by QA. verify.rs untouched.

docs/features/decomposition-formatter/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 16:39:08 -07:00

302 lines
12 KiB
Rust

//! 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<Doc> {
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<Doc>, 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<Doc> {
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<Doc> {
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: 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<Doc> {
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<Doc>) -> 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<Doc>) {
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<Doc>) {
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<Doc>,
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<Doc> {
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)),
}
}