TODO section 31 (coverage_gaps M9, docs/topo.md 2.9-3). fence::collect enters class bodies, functions, tasks and always/ initial/final blocks, and statement lists - begin/end, fork/join and every compound body - through scan_stmt_scope/scan_nested_stmt on the one scan_units both scope kinds share; stmt_docs/stmt_seq obey the two swallowed-unit rules item_docs/item_seq had; fence regions merge into range.rs's plan, which was load-bearing (a fenced statement has no verbatim run behind it; proved by disabling it). A region opens only at a line start (opens_line) - the rule the format-fences README has stated since round 1 - so a fence after code on the same line is an ordinary comment everywhere, which narrows one accidental item-level shape (module m; // lucisv: off) and is ruled a drift fix. Deferred with reasons: port lists, case-item label lists, same-line fences, a property's locals. verify.rs, lucisv/src/lint.rs and lucisv_server/src/lint.rs untouched. Proof: 3 244 tests / 48 binaries, fences.cases 25 -> 38 with the statement-level entry inverted, corpus 814/820 and 860 files byte- identical to 0.34.0, opentitan: 4 of its 9 fenced files now keep their fenced bytes and are fixed points, --check counts identical; 3 348 fence-injection trials with no new refusals. docs/features/statement-fences/README.md. Co-Authored-By: Claude Fable 5 <[email protected]>
692 lines
30 KiB
Rust
692 lines
30 KiB
Rust
//! 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<String>,
|
|
stmts: &'a [Stmt],
|
|
dangling: &'a [Comment],
|
|
end_label_comments: &'a LabelComments,
|
|
end_label: &'a Option<String>,
|
|
}
|
|
|
|
impl<'a> Fmt<'a> {
|
|
fn stmt(&self, s: &Stmt) -> Doc {
|
|
concat(self.stmt_docs(s))
|
|
}
|
|
|
|
/// One statement: its leading comments, then — unless a verbatim region is
|
|
/// already emitting its bytes — its code and trailing comment. The
|
|
/// statement twin of `Fmt::item_docs`, with the same two rules: comments
|
|
/// written before the `off` fence are still emitted, because comments are
|
|
/// never dropped, and a statement the region swallowed emits nothing.
|
|
fn stmt_docs(&self, s: &Stmt) -> Vec<Doc> {
|
|
// A verbatim run whose first statement carries no leading comment opens
|
|
// at the statement's own code; there is no comment to emit it from.
|
|
if let Some(region) = self.opens_at(s.span.start as usize) {
|
|
return vec![self.verbatim(region)];
|
|
}
|
|
if self.is_verbatim(s.span) {
|
|
// The statement's own bytes, its attributes included, are emitted
|
|
// verbatim by the fence; only its leading comments are ours.
|
|
let mut docs = self.leading_comments(&s.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;
|
|
}
|
|
vec![self.with_meta(&s.meta, self.stmt_kind(&s.kind, &s.before_semi))]
|
|
}
|
|
|
|
/// Sequence of statements at one indent level, preserving single blank
|
|
/// lines between them. A statement a fenced region swallowed emits
|
|
/// nothing, and contributes no separator either.
|
|
pub(super) fn stmt_seq(&self, stmts: &[Stmt]) -> Vec<Doc> {
|
|
let mut docs = Vec::new();
|
|
for s in stmts {
|
|
let stmt_docs = self.stmt_docs(s);
|
|
if stmt_docs.is_empty() {
|
|
continue;
|
|
}
|
|
if !docs.is_empty() {
|
|
docs.push(if s.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
|
}
|
|
docs.extend(stmt_docs);
|
|
}
|
|
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<Doc> = 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<Doc> = 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<Doc> = 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<String>,
|
|
after_kw: &[Comment],
|
|
cond: &Expr,
|
|
then: &Stmt,
|
|
else_comments: &[Comment],
|
|
els: &Option<Box<Stmt>>,
|
|
) -> 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<Doc> = 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()
|
|
}
|