Fix six formatter bugs; case table grows to 200 with zero skips
All five briefed bugs fixed, plus a sixth found during the work: 1. Block-comment continuation drift: token::Comment gained line/col; continuation lines are dedented by the comment's original column before re-indenting, making reformatting a true fixed point while preserving the author's relative indentation inside the comment. 2. Comments inside expression groups (concat, parens, call args, assignment patterns, binary operands) now force the group to break instead of being lifted out. 3. Closing block labels preserved for end/join*/endfunction/endtask/ endpackage, matching endmodule. 4. Multi-instance declarations fit on one line when they fit and indent their continuations when they break. 5. @( /* c */ * ) keeps its comments (SensList::Star before/after). 6. Multi-line `define/attribute bodies no longer drift (RawText.col). verify.rs comparison logic untouched (diagnostic positions only) — QA audited the diff to confirm the safety net was not weakened. All four #SKIP cases un-skipped verbatim as spec; 17 cases added (183 -> 200, 0 skipped). QA triple-formatted 204 inputs with zero regressions. Clippy is now fully silent workspace-wide. Remaining comment-placement refusals (4) and a pre-existing @(* ) lexer limitation are documented as open items, not hacked around. Dev: Opus agent; QA: Sonnet agent; review in docs/features/formatter-bug-fixes/README.md. Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
0a6c365ec2
commit
9f1a6cf1d2
15 files changed
+1277
-213
No files matched your search
@@ -30,6 +30,10 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
|
||||
- [x] **[R] Panic containment.** ruff catches panics per-file and reports
|
||||
them as errors instead of killing the whole run. Wrap per-file work in
|
||||
`crates/vfmt/src/main.rs` with `std::panic::catch_unwind`.
|
||||
- [ ] **`@(* )` fails to lex** (bug-fix QA find): `(*` followed by anything
|
||||
but `)` is unconditionally lexed as an attribute (`lexer.rs`), so a bare
|
||||
space inside `@( * )`-style spellings errors out. Make the attribute
|
||||
scan back off when the contents are just `*`.
|
||||
- [ ] **Recursion-depth limit in the parser.** Found by cli-polish QA:
|
||||
~150 levels of expression nesting overflow the stack and abort the whole
|
||||
process — uncatchable by `catch_unwind`, so mid-batch files after the
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
//! on a single line, cuddled `begin`/`end`.
|
||||
|
||||
use crate::doc::*;
|
||||
use crate::printer::Printer;
|
||||
use crate::printer::{contains_hard_line, Printer};
|
||||
use crate::verify::{verify_convergence, verify_equivalence, VerificationError};
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::token::Comment;
|
||||
@@ -86,26 +86,21 @@ struct Fmt<'a> {
|
||||
_cfg: &'a Config,
|
||||
}
|
||||
|
||||
/// A list element ready for comma-list layout.
|
||||
/// A list element ready for comma-list layout. Blank lines between elements
|
||||
/// are deliberately dropped, so only the comments ride along.
|
||||
struct ListItem {
|
||||
leading: Vec<Comment>,
|
||||
doc: Doc,
|
||||
trailing: Option<String>,
|
||||
blank_before: bool,
|
||||
}
|
||||
|
||||
impl ListItem {
|
||||
fn plain(doc: Doc) -> Self {
|
||||
ListItem { leading: Vec::new(), doc, trailing: None, blank_before: false }
|
||||
ListItem { leading: Vec::new(), doc, trailing: None }
|
||||
}
|
||||
|
||||
fn from_meta(meta: &Meta, doc: Doc) -> Self {
|
||||
ListItem {
|
||||
leading: meta.leading.clone(),
|
||||
doc,
|
||||
trailing: meta.trailing.clone(),
|
||||
blank_before: meta.blank_before,
|
||||
}
|
||||
ListItem { leading: meta.leading.clone(), doc, trailing: meta.trailing.clone() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,22 +109,47 @@ impl<'a> Fmt<'a> {
|
||||
// Shared helpers
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Turn possibly-multi-line raw text (comments, directives) into a Doc.
|
||||
fn raw_text(&self, s: &str) -> Doc {
|
||||
let lines: Vec<&str> = s.split('\n').collect();
|
||||
if lines.len() == 1 {
|
||||
/// Verbatim text (a directive or an attribute), ready to be re-indented.
|
||||
fn raw_text(&self, raw: &RawText) -> Doc {
|
||||
self.raw_lines(&raw.text, raw.col)
|
||||
}
|
||||
|
||||
/// 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 lines.iter().enumerate() {
|
||||
if i > 0 {
|
||||
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<String>) -> Doc {
|
||||
match label {
|
||||
Some(l) => text(format!("{kw} : {l}")),
|
||||
None => text(kw),
|
||||
}
|
||||
}
|
||||
|
||||
/// Leading comments (each on its own line) preceding a node.
|
||||
fn leading(&self, meta: &Meta) -> Vec<Doc> {
|
||||
let mut docs = Vec::new();
|
||||
@@ -137,7 +157,7 @@ impl<'a> Fmt<'a> {
|
||||
if i > 0 && c.blank_before {
|
||||
docs.push(Doc::BlankLine);
|
||||
}
|
||||
docs.push(self.raw_text(&c.text));
|
||||
docs.push(self.comment(c));
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
for attr in &meta.attrs {
|
||||
@@ -204,6 +224,26 @@ impl<'a> Fmt<'a> {
|
||||
group(docs)
|
||||
}
|
||||
|
||||
/// 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<ListItem> =
|
||||
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(")")])
|
||||
@@ -241,7 +281,7 @@ impl<'a> Fmt<'a> {
|
||||
} else {
|
||||
docs.push(Doc::HardLine);
|
||||
}
|
||||
docs.push(self.raw_text(&c.text));
|
||||
docs.push(self.comment(c));
|
||||
}
|
||||
docs
|
||||
}
|
||||
@@ -256,7 +296,7 @@ impl<'a> Fmt<'a> {
|
||||
if !docs.is_empty() || i > 0 {
|
||||
docs.push(if c.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
}
|
||||
docs.push(self.raw_text(&c.text));
|
||||
docs.push(self.comment(c));
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
@@ -268,7 +308,7 @@ impl<'a> Fmt<'a> {
|
||||
fn item_kind(&self, kind: &ItemKind) -> Doc {
|
||||
match kind {
|
||||
ItemKind::Module(m) => self.module(m),
|
||||
ItemKind::Package { kw, name, items, dangling } => {
|
||||
ItemKind::Package { kw, name, items, dangling, end_label } => {
|
||||
let mut docs = vec![text(format!("{kw} {name};"))];
|
||||
let mut body = Vec::new();
|
||||
if !items.is_empty() {
|
||||
@@ -278,7 +318,7 @@ impl<'a> Fmt<'a> {
|
||||
body.extend(self.dangling(dangling));
|
||||
docs.push(indent(body));
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(text("endpackage"));
|
||||
docs.push(Self::closing("endpackage", end_label));
|
||||
concat(docs)
|
||||
}
|
||||
ItemKind::Directive(d) => self.raw_text(d),
|
||||
@@ -379,10 +419,7 @@ impl<'a> Fmt<'a> {
|
||||
body.extend(self.dangling(&m.dangling));
|
||||
docs.push(indent(body));
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(match &m.end_label {
|
||||
Some(l) => text(format!("endmodule : {l}")),
|
||||
None => text("endmodule"),
|
||||
});
|
||||
docs.push(Self::closing("endmodule", &m.end_label));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
@@ -483,7 +520,7 @@ impl<'a> Fmt<'a> {
|
||||
/// breaks are introduced.
|
||||
fn expr_compact(&self, e: &Expr) -> Doc {
|
||||
match e {
|
||||
Expr::Binary { lhs, op, rhs } => {
|
||||
Expr::Binary { lhs, op, rhs, .. } => {
|
||||
let tight = Self::binary_prec(op) >= 8;
|
||||
let sep = if tight { op.clone() } else { format!(" {op} ") };
|
||||
concat(vec![self.expr_compact(lhs), text(sep), self.expr_compact(rhs)])
|
||||
@@ -495,7 +532,9 @@ impl<'a> Fmt<'a> {
|
||||
text(" : "),
|
||||
self.expr_compact(els),
|
||||
]),
|
||||
Expr::Paren(inner) => concat(vec![text("("), self.expr_compact(inner), text(")")]),
|
||||
Expr::Paren { inner, .. } => {
|
||||
concat(vec![text("("), self.expr_compact(inner), text(")")])
|
||||
}
|
||||
Expr::Unary { op, expr } => concat(vec![text(op.clone()), self.expr_compact(expr)]),
|
||||
_ => self.expr(e),
|
||||
}
|
||||
@@ -520,7 +559,7 @@ impl<'a> Fmt<'a> {
|
||||
docs.extend(self.unpacked_dims(&d.unpacked));
|
||||
if let Some(init) = &d.init {
|
||||
docs.push(text(" ="));
|
||||
docs.push(group(vec![indent(vec![Doc::Line, self.expr(init)])]));
|
||||
docs.push(group(vec![self.assign_rhs(self.expr(init))]));
|
||||
}
|
||||
ListItem::from_meta(&d.meta, concat(docs))
|
||||
})
|
||||
@@ -700,11 +739,8 @@ impl<'a> Fmt<'a> {
|
||||
.assigns
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let d = group(vec![
|
||||
self.expr(&p.lhs),
|
||||
text(" ="),
|
||||
indent(vec![Doc::Line, self.expr(&p.rhs)]),
|
||||
]);
|
||||
let d =
|
||||
group(vec![self.expr(&p.lhs), text(" ="), self.assign_rhs(self.expr(&p.rhs))]);
|
||||
ListItem::from_meta(&p.meta, d)
|
||||
})
|
||||
.collect();
|
||||
@@ -750,29 +786,51 @@ impl<'a> Fmt<'a> {
|
||||
docs.push(text(" #"));
|
||||
docs.push(self.delimited("(", items, ")", false));
|
||||
}
|
||||
let single = inst.instances.len() == 1;
|
||||
for (i, instance) in inst.instances.iter().enumerate() {
|
||||
if i > 0 {
|
||||
docs.push(text(","));
|
||||
docs.push(Doc::HardLine);
|
||||
} else {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
let _ = single;
|
||||
docs.push(text(instance.name.clone()));
|
||||
if !instance.dims.is_empty() {
|
||||
docs.push(text(" "));
|
||||
for d in &instance.dims {
|
||||
docs.push(self.dim(d));
|
||||
docs.push(text(" "));
|
||||
if let [only] = &inst.instances[..] {
|
||||
// The common case: no extra indent level, so a connection list
|
||||
// that breaks lines up under the instance itself.
|
||||
docs.push(self.instance(only));
|
||||
} else {
|
||||
// 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));
|
||||
if i < last {
|
||||
inner.push(text(","));
|
||||
}
|
||||
if let Some(tr) = &instance.meta.trailing {
|
||||
inner.push(text(format!(" {tr}")));
|
||||
if i < last {
|
||||
inner.push(Doc::HardLine);
|
||||
}
|
||||
} else if i < last {
|
||||
inner.push(Doc::Line);
|
||||
}
|
||||
}
|
||||
docs.push(text(" "));
|
||||
docs.push(self.connections(&instance.conns));
|
||||
docs.push(group(vec![indent(inner)]));
|
||||
}
|
||||
docs.push(text(";"));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// One instance of a module instantiation: `u0 [3:0] (.a(x))`.
|
||||
fn instance(&self, instance: &Instance) -> Doc {
|
||||
let mut docs = vec![text(instance.name.clone())];
|
||||
if !instance.dims.is_empty() {
|
||||
docs.push(text(" "));
|
||||
for d in &instance.dims {
|
||||
docs.push(self.dim(d));
|
||||
}
|
||||
}
|
||||
docs.push(text(" "));
|
||||
docs.push(self.connections(&instance.conns));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
fn connections(&self, conns: &Connections) -> Doc {
|
||||
match conns {
|
||||
Connections::Named(list) => {
|
||||
@@ -890,7 +948,7 @@ impl<'a> Fmt<'a> {
|
||||
body.extend(self.dangling(&b.dangling));
|
||||
docs.push(indent(body));
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(text("end"));
|
||||
docs.push(Self::closing("end", &b.end_label));
|
||||
true
|
||||
} else {
|
||||
let item = &b.items[0];
|
||||
@@ -1002,7 +1060,12 @@ impl<'a> Fmt<'a> {
|
||||
body.extend(self.stmt_seq(&f.stmts));
|
||||
}
|
||||
body.extend(self.dangling(&f.dangling));
|
||||
concat(vec![concat(header), indent(body), Doc::HardLine, text("endfunction")])
|
||||
concat(vec![
|
||||
concat(header),
|
||||
indent(body),
|
||||
Doc::HardLine,
|
||||
Self::closing("endfunction", &f.end_label),
|
||||
])
|
||||
}
|
||||
|
||||
fn task(&self, t: &TaskDecl) -> Doc {
|
||||
@@ -1021,7 +1084,12 @@ impl<'a> Fmt<'a> {
|
||||
body.extend(self.stmt_seq(&t.stmts));
|
||||
}
|
||||
body.extend(self.dangling(&t.dangling));
|
||||
concat(vec![concat(header), indent(body), Doc::HardLine, text("endtask")])
|
||||
concat(vec![
|
||||
concat(header),
|
||||
indent(body),
|
||||
Doc::HardLine,
|
||||
Self::closing("endtask", &t.end_label),
|
||||
])
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -1037,10 +1105,10 @@ impl<'a> Fmt<'a> {
|
||||
/// line if they fit, otherwise indented on the next line.
|
||||
fn stmt_as_body(&self, prefix: Doc, s: &Stmt) -> Doc {
|
||||
match &s.kind {
|
||||
StmtKind::Block { label, stmts, dangling } => {
|
||||
StmtKind::Block { label, stmts, dangling, end_label } => {
|
||||
let mut docs = vec![prefix, text(" ")];
|
||||
docs.extend(self.leading(&s.meta));
|
||||
docs.push(self.block_doc(label, stmts, dangling));
|
||||
docs.push(self.block_doc(label, stmts, dangling, end_label));
|
||||
docs.extend(self.trailing(&s.meta));
|
||||
concat(docs)
|
||||
}
|
||||
@@ -1057,7 +1125,13 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn block_doc(&self, label: &Option<String>, stmts: &[Stmt], dangling: &[Comment]) -> Doc {
|
||||
fn block_doc(
|
||||
&self,
|
||||
label: &Option<String>,
|
||||
stmts: &[Stmt],
|
||||
dangling: &[Comment],
|
||||
end_label: &Option<String>,
|
||||
) -> Doc {
|
||||
let mut docs = vec![match label {
|
||||
Some(l) => text(format!("begin : {l}")),
|
||||
None => text("begin"),
|
||||
@@ -1070,7 +1144,7 @@ impl<'a> Fmt<'a> {
|
||||
body.extend(self.dangling(dangling));
|
||||
docs.push(indent(body));
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(text("end"));
|
||||
docs.push(Self::closing("end", end_label));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
@@ -1083,7 +1157,32 @@ impl<'a> Fmt<'a> {
|
||||
|
||||
fn sens_list(&self, sens: &SensList) -> Doc {
|
||||
match sens {
|
||||
SensList::Star => text("@(*)"),
|
||||
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) => {
|
||||
let any_edge = items.iter().any(|i| i.edge.is_some());
|
||||
let sep = if any_edge { text(" or ") } else { text(", ") };
|
||||
@@ -1111,8 +1210,10 @@ impl<'a> Fmt<'a> {
|
||||
|
||||
fn stmt_kind(&self, kind: &StmtKind) -> Doc {
|
||||
match kind {
|
||||
StmtKind::Block { label, stmts, dangling } => self.block_doc(label, stmts, dangling),
|
||||
StmtKind::ForkJoin { label, join_kw, stmts, dangling } => {
|
||||
StmtKind::Block { label, stmts, dangling, end_label } => {
|
||||
self.block_doc(label, stmts, dangling, end_label)
|
||||
}
|
||||
StmtKind::ForkJoin { label, join_kw, stmts, dangling, end_label } => {
|
||||
let mut docs = vec![match label {
|
||||
Some(l) => text(format!("fork : {l}")),
|
||||
None => text("fork"),
|
||||
@@ -1125,7 +1226,7 @@ impl<'a> Fmt<'a> {
|
||||
body.extend(self.dangling(dangling));
|
||||
docs.push(indent(body));
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(text(join_kw.clone()));
|
||||
docs.push(Self::closing(join_kw, end_label));
|
||||
concat(docs)
|
||||
}
|
||||
StmtKind::If { qualifier, cond, then, els } => self.if_stmt(qualifier, cond, then, els),
|
||||
@@ -1188,9 +1289,9 @@ impl<'a> Fmt<'a> {
|
||||
StmtKind::DoWhile { body, cond } => {
|
||||
let mut docs = vec![text("do")];
|
||||
match &body.kind {
|
||||
StmtKind::Block { label, stmts, dangling } => {
|
||||
StmtKind::Block { label, stmts, dangling, end_label } => {
|
||||
docs.push(text(" "));
|
||||
docs.push(self.block_doc(label, stmts, dangling));
|
||||
docs.push(self.block_doc(label, stmts, dangling, end_label));
|
||||
docs.push(text(" while "));
|
||||
}
|
||||
_ => {
|
||||
@@ -1223,7 +1324,7 @@ impl<'a> Fmt<'a> {
|
||||
rhs_docs.push(text(" "));
|
||||
}
|
||||
rhs_docs.push(self.expr(rhs));
|
||||
docs.push(indent(vec![Doc::Line, concat(rhs_docs)]));
|
||||
docs.push(self.assign_rhs(concat(rhs_docs)));
|
||||
concat(vec![group(docs), text(";")])
|
||||
}
|
||||
StmtKind::ForceRelease { kw, lhs, rhs } => {
|
||||
@@ -1376,9 +1477,7 @@ impl<'a> Fmt<'a> {
|
||||
]),
|
||||
]),
|
||||
Expr::Call { callee, args } => {
|
||||
let items: Vec<ListItem> =
|
||||
args.iter().map(|a| ListItem::plain(self.expr(a))).collect();
|
||||
concat(vec![self.expr(callee), self.delimited("(", items, ")", false)])
|
||||
concat(vec![self.expr(callee), self.expr_list("(", args, ")")])
|
||||
}
|
||||
Expr::Index { base, index } => {
|
||||
concat(vec![self.expr(base), text("["), self.expr_compact(index), text("]")])
|
||||
@@ -1393,11 +1492,7 @@ impl<'a> Fmt<'a> {
|
||||
]),
|
||||
Expr::Member { base, name } => concat(vec![self.expr(base), text(format!(".{name}"))]),
|
||||
Expr::Scope { base, name } => concat(vec![self.expr(base), text(format!("::{name}"))]),
|
||||
Expr::Concat(items) => {
|
||||
let items: Vec<ListItem> =
|
||||
items.iter().map(|i| ListItem::plain(self.expr(i))).collect();
|
||||
self.delimited("{", items, "}", false)
|
||||
}
|
||||
Expr::Concat(items) => self.expr_list("{", items, "}"),
|
||||
Expr::Repl { count, inner } => {
|
||||
let inner_docs: Vec<Doc> = inner.iter().map(|i| self.expr(i)).collect();
|
||||
concat(vec![
|
||||
@@ -1408,7 +1503,28 @@ impl<'a> Fmt<'a> {
|
||||
text("}}"),
|
||||
])
|
||||
}
|
||||
Expr::Paren(inner) => self.parens(inner),
|
||||
Expr::Paren { inner, before, after } => {
|
||||
if before.is_empty() && after.is_empty() {
|
||||
return self.parens(inner);
|
||||
}
|
||||
// A comment inside the parens forces them open, the same way
|
||||
// a comment inside a port list does.
|
||||
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)
|
||||
}
|
||||
Expr::Cast { ty, expr } => {
|
||||
concat(vec![text(format!("{ty}'(")), self.expr(expr), text(")")])
|
||||
}
|
||||
@@ -1422,20 +1538,14 @@ impl<'a> Fmt<'a> {
|
||||
d.push(text(": "));
|
||||
}
|
||||
d.push(self.expr(&pi.value));
|
||||
ListItem::plain(concat(d))
|
||||
ListItem::from_meta(&pi.meta, concat(d))
|
||||
})
|
||||
.collect();
|
||||
self.delimited("'{", items, "}", false)
|
||||
}
|
||||
Expr::Postfix { expr, op } => concat(vec![self.expr(expr), text(op.clone())]),
|
||||
Expr::Inside { lhs, ranges } => {
|
||||
let items: Vec<ListItem> =
|
||||
ranges.iter().map(|r| ListItem::plain(self.expr(r))).collect();
|
||||
concat(vec![
|
||||
self.expr(lhs),
|
||||
text(" inside "),
|
||||
self.delimited("{", items, "}", false),
|
||||
])
|
||||
concat(vec![self.expr(lhs), text(" inside "), self.expr_list("{", ranges, "}")])
|
||||
}
|
||||
Expr::ValueRange { lo, hi } => {
|
||||
concat(vec![text("["), self.expr(lo), text(":"), self.expr(hi), text("]")])
|
||||
@@ -1448,17 +1558,24 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
|
||||
/// Flatten a left-nested chain of same-precedence binary operators so
|
||||
/// `a + b + c` breaks as one unit instead of stair-stepping.
|
||||
/// `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 Expr::Binary { op, .. } = e else { unreachable!() };
|
||||
let prec = Self::binary_prec(op);
|
||||
let mut operands: Vec<&Expr> = Vec::new();
|
||||
let mut ops: Vec<&str> = Vec::new();
|
||||
fn walk<'e>(e: &'e Expr, prec: u8, operands: &mut Vec<&'e Expr>, ops: &mut Vec<&'e str>) {
|
||||
let mut ops: Vec<(&str, &[Comment])> = Vec::new();
|
||||
fn walk<'e>(
|
||||
e: &'e Expr,
|
||||
prec: u8,
|
||||
operands: &mut Vec<&'e Expr>,
|
||||
ops: &mut Vec<(&'e str, &'e [Comment])>,
|
||||
) {
|
||||
match e {
|
||||
Expr::Binary { lhs, op, rhs } if Fmt::binary_prec(op) == prec => {
|
||||
Expr::Binary { lhs, op, rhs, comments } if Fmt::binary_prec(op) == prec => {
|
||||
walk(lhs, prec, operands, ops);
|
||||
ops.push(op);
|
||||
ops.push((op, comments));
|
||||
operands.push(rhs);
|
||||
}
|
||||
_ => operands.push(e),
|
||||
@@ -1467,12 +1584,38 @@ impl<'a> Fmt<'a> {
|
||||
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()) {
|
||||
cont.push(text(format!(" {op}")));
|
||||
cont.push(Doc::Line);
|
||||
for ((op, comments), rhs) in ops.iter().zip(operands[1..].iter()) {
|
||||
if comments.is_empty() {
|
||||
cont.push(text(format!(" {op}")));
|
||||
cont.push(Doc::Line);
|
||||
} else {
|
||||
for c in comments.iter() {
|
||||
cont.push(text(" "));
|
||||
cont.push(self.comment(c));
|
||||
}
|
||||
cont.push(Doc::HardLine);
|
||||
cont.push(text(format!("{op} ")));
|
||||
}
|
||||
cont.push(self.expr(rhs));
|
||||
}
|
||||
docs.push(indent(cont));
|
||||
group(docs)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
|
||||
/// True for `// ...` comments, which must end their line.
|
||||
fn is_line_comment(text: &str) -> bool {
|
||||
text.starts_with("//")
|
||||
}
|
||||
@@ -88,7 +88,7 @@ impl Printer {
|
||||
}
|
||||
out.push('\n');
|
||||
let spaces = ind * self.indent_width;
|
||||
out.extend(std::iter::repeat(' ').take(spaces));
|
||||
out.extend(std::iter::repeat_n(' ', spaces));
|
||||
*col = spaces;
|
||||
}
|
||||
|
||||
@@ -159,7 +159,7 @@ impl Printer {
|
||||
}
|
||||
}
|
||||
|
||||
fn contains_hard_line(items: &[Doc]) -> bool {
|
||||
pub(crate) fn contains_hard_line(items: &[Doc]) -> bool {
|
||||
items.iter().any(|d| match d {
|
||||
Doc::HardLine | Doc::BlankLine => true,
|
||||
Doc::Concat(inner) | Doc::Indent(inner) | Doc::Group(inner) => contains_hard_line(inner),
|
||||
|
||||
@@ -70,9 +70,9 @@ pub struct Item {
|
||||
pub kind: ItemKind,
|
||||
/// Token or comment text, normalized as described in the module docs.
|
||||
pub text: String,
|
||||
/// 1-based line of the token (of the owning token, for comments).
|
||||
/// 1-based line the token or comment starts on.
|
||||
pub line: u32,
|
||||
/// 1-based column of the token (of the owning token, for comments).
|
||||
/// 1-based column the token or comment starts on.
|
||||
pub col: u32,
|
||||
}
|
||||
|
||||
@@ -171,7 +171,7 @@ fn lex_stream(source: &str, side: Side) -> Result<Vec<Item>, VerificationError>
|
||||
let mut items = Vec::new();
|
||||
for token in &tokens {
|
||||
for comment in &token.leading {
|
||||
items.push(comment_item(&comment.text, token.line, token.col));
|
||||
items.push(comment_item(&comment.text, comment.line, comment.col));
|
||||
}
|
||||
// The `Eof` token itself carries no text, but its leading comments
|
||||
// (a comment at the very end of the file) do matter.
|
||||
@@ -184,7 +184,7 @@ fn lex_stream(source: &str, side: Side) -> Result<Vec<Item>, VerificationError>
|
||||
});
|
||||
}
|
||||
if let Some(trailing) = &token.trailing {
|
||||
items.push(comment_item(trailing, token.line, token.col));
|
||||
items.push(comment_item(&trailing.text, trailing.line, trailing.col));
|
||||
}
|
||||
}
|
||||
collapse_implicit_sensitivity(&mut items);
|
||||
|
||||
@@ -36,9 +36,7 @@ endmodule
|
||||
module m;
|
||||
endmodule
|
||||
====
|
||||
#SKIP bug: continuation lines of a multi-line block comment gain two spaces on
|
||||
#SKIP every format pass -- an unbounded idempotency violation (see feature README)
|
||||
# multi-line block comment is passed through verbatim
|
||||
# multi-line block comment keeps its shape relative to its own opening column
|
||||
module m;
|
||||
/*
|
||||
* doc block
|
||||
@@ -240,9 +238,7 @@ module m #(
|
||||
) ();
|
||||
endmodule
|
||||
====
|
||||
#SKIP bug: the comment is lifted out of the concatenation to the end of the
|
||||
#SKIP statement instead of forcing the group to break (see feature README)
|
||||
# comment inside a concatenation
|
||||
# comment inside a concatenation forces the group to break
|
||||
module m;
|
||||
assign y = {
|
||||
a, // high
|
||||
@@ -310,3 +306,132 @@ module m;
|
||||
(* dont_touch *)
|
||||
wire w;
|
||||
endmodule
|
||||
====
|
||||
# multi-line block comment already indented inside a block
|
||||
module m;
|
||||
initial begin
|
||||
/* banner
|
||||
line two
|
||||
line three */
|
||||
x = 1;
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
/* banner
|
||||
line two
|
||||
line three */
|
||||
x = 1;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# continuation lines left of the opening column land on the new indent
|
||||
module m;
|
||||
/* opener
|
||||
one
|
||||
two */
|
||||
wire w;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
/* opener
|
||||
one
|
||||
two */
|
||||
wire w;
|
||||
endmodule
|
||||
====
|
||||
# block comment inside the parens of an implicit sensitivity list
|
||||
module m;
|
||||
always @( /* everything */ * ) y = a;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always @(/* everything */ *) y = a;
|
||||
endmodule
|
||||
====
|
||||
# comment after the star of an implicit sensitivity list
|
||||
module m;
|
||||
always @( * /* everything */ ) y = a;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always @( * /* everything */) y = a;
|
||||
endmodule
|
||||
====
|
||||
# a continued `define inside a module keeps its continuation indent
|
||||
module m;
|
||||
`define FOO(a) \
|
||||
do_something(a)
|
||||
wire w;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
`define FOO(a) \
|
||||
do_something(a)
|
||||
wire w;
|
||||
endmodule
|
||||
====
|
||||
# comment inside a call argument list forces it to break
|
||||
module m;
|
||||
assign z = f(a, // first
|
||||
b);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign z = f(
|
||||
a, // first
|
||||
b
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# comment inside an assignment pattern forces it to break
|
||||
module m;
|
||||
assign w = '{a: 1, // one
|
||||
b: 2};
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign w = '{
|
||||
a: 1, // one
|
||||
b: 2
|
||||
};
|
||||
endmodule
|
||||
====
|
||||
# comment just inside a parenthesized expression forces it to break
|
||||
module m;
|
||||
assign v = ( // why
|
||||
a + b);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign v = (
|
||||
// why
|
||||
a + b
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# comment between the operands of a binary expression
|
||||
module m;
|
||||
assign y = (a // hi
|
||||
+ b);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign y = (
|
||||
a // hi
|
||||
+ b
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# comment before the operator of a long operator chain
|
||||
module m;
|
||||
assign ready = first
|
||||
// wait for the second one too
|
||||
&& second;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
assign ready = first // wait for the second one too
|
||||
&& second;
|
||||
endmodule
|
||||
@@ -225,3 +225,22 @@ package p;
|
||||
return a;
|
||||
endfunction
|
||||
endpackage
|
||||
====
|
||||
# closing labels on endfunction and endtask
|
||||
module m;
|
||||
function int f();
|
||||
return 1;
|
||||
endfunction : f
|
||||
task t;
|
||||
x = 1;
|
||||
endtask : t
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
function int f();
|
||||
return 1;
|
||||
endfunction : f
|
||||
task t;
|
||||
x = 1;
|
||||
endtask : t
|
||||
endmodule
|
||||
@@ -217,3 +217,20 @@ module m;
|
||||
end
|
||||
endgenerate
|
||||
endmodule
|
||||
====
|
||||
# closing label on a generate block end
|
||||
module m;
|
||||
generate
|
||||
for (genvar i = 0; i < 2; i = i + 1) begin : lane
|
||||
wire w;
|
||||
end : lane
|
||||
endgenerate
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
generate
|
||||
for (genvar i = 0; i < 2; i = i + 1) begin : lane
|
||||
wire w;
|
||||
end : lane
|
||||
endgenerate
|
||||
endmodule
|
||||
@@ -116,8 +116,6 @@ module m;
|
||||
sub u0 [3:0] (.a(x), .b(y));
|
||||
endmodule
|
||||
====
|
||||
#SKIP bug: multi-instance declarations always break and the continuation is
|
||||
#SKIP not indented (see feature README)
|
||||
# multiple instances in one statement
|
||||
module m;
|
||||
sub u0(.a(x)), u1(.a(y));
|
||||
@@ -127,6 +125,27 @@ module m;
|
||||
sub u0 (.a(x)), u1 (.a(y));
|
||||
endmodule
|
||||
====
|
||||
# multiple instances that do not fit break one per line, indented
|
||||
module m;
|
||||
subsystem_with_a_long_name u_instance_zero(.aaaa(xxxx),.bbbb(yyyy)), u_instance_one(.aaaa(x2),.bbbb(y2));
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
subsystem_with_a_long_name u_instance_zero (.aaaa(xxxx), .bbbb(yyyy)),
|
||||
u_instance_one (.aaaa(x2), .bbbb(y2));
|
||||
endmodule
|
||||
====
|
||||
# a comment after an instance breaks the instance list
|
||||
module m;
|
||||
sub u0(.a(x)), // the first one
|
||||
u1(.a(y));
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
sub u0 (.a(x)), // the first one
|
||||
u1 (.a(y));
|
||||
endmodule
|
||||
====
|
||||
# gate primitive instantiation
|
||||
module m;
|
||||
and g0(y, a, b);
|
||||
|
||||
@@ -137,3 +137,12 @@ endmodule : m
|
||||
----
|
||||
module m;
|
||||
endmodule : m
|
||||
====
|
||||
# closing label on endpackage
|
||||
package p;
|
||||
localparam int W = 8;
|
||||
endpackage : p
|
||||
----
|
||||
package p;
|
||||
localparam int W = 8;
|
||||
endpackage : p
|
||||
@@ -86,7 +86,6 @@ module m;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
#SKIP bug: the closing `end : main` label is dropped (see feature README)
|
||||
# labeled begin/end with a closing label
|
||||
module m;
|
||||
initial begin : main
|
||||
@@ -100,6 +99,52 @@ module m;
|
||||
end : main
|
||||
endmodule
|
||||
====
|
||||
# closing labels on all three join kinds
|
||||
module m;
|
||||
initial begin
|
||||
fork : a
|
||||
x = 1;
|
||||
join : a
|
||||
fork : b
|
||||
y = 2;
|
||||
join_any : b
|
||||
fork : c
|
||||
z = 3;
|
||||
join_none : c
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
fork : a
|
||||
x = 1;
|
||||
join : a
|
||||
fork : b
|
||||
y = 2;
|
||||
join_any : b
|
||||
fork : c
|
||||
z = 3;
|
||||
join_none : c
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# closing label on a nested begin/end
|
||||
module m;
|
||||
initial begin : outer
|
||||
begin : inner
|
||||
x = 1;
|
||||
end : inner
|
||||
end : outer
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin : outer
|
||||
begin : inner
|
||||
x = 1;
|
||||
end : inner
|
||||
end : outer
|
||||
endmodule
|
||||
====
|
||||
# nested begin blocks
|
||||
module m;
|
||||
initial begin
|
||||
|
||||
@@ -12,7 +12,17 @@ pub struct Meta {
|
||||
pub trailing: Option<String>,
|
||||
pub blank_before: bool,
|
||||
/// Attribute instances `(* ... *)` that preceded the node, verbatim.
|
||||
pub attrs: Vec<String>,
|
||||
pub attrs: Vec<RawText>,
|
||||
}
|
||||
|
||||
/// Source text passed through verbatim: a compiler directive or an attribute
|
||||
/// instance. `col` is the 1-based column it started in, which is what lets the
|
||||
/// formatter re-indent continuation lines of a multi-line one without drifting
|
||||
/// further right on every pass.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RawText {
|
||||
pub text: String,
|
||||
pub col: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -36,8 +46,10 @@ pub enum ItemKind {
|
||||
name: String,
|
||||
items: Vec<Item>,
|
||||
dangling: Vec<Comment>,
|
||||
/// Label after `endpackage :`.
|
||||
end_label: Option<String>,
|
||||
},
|
||||
Directive(String),
|
||||
Directive(RawText),
|
||||
Import(Vec<String>),
|
||||
Timeunit(String),
|
||||
Typedef(Typedef),
|
||||
@@ -242,8 +254,14 @@ pub struct AssignPair {
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum SensList {
|
||||
/// `@*` or `@(*)`
|
||||
Star,
|
||||
/// `@*` or `@(*)`, with any comments written next to the `*` so the
|
||||
/// formatter can print them back in the same place.
|
||||
Star {
|
||||
/// Comments between the `@`/`(` and the `*`.
|
||||
before: Vec<Comment>,
|
||||
/// Comments between the `*` and the closing `)`.
|
||||
after: Vec<Comment>,
|
||||
},
|
||||
List(Vec<SensItem>),
|
||||
}
|
||||
|
||||
@@ -350,6 +368,8 @@ pub struct GenBlock {
|
||||
pub is_block: bool,
|
||||
pub items: Vec<Item>,
|
||||
pub dangling: Vec<Comment>,
|
||||
/// Label after `end :`.
|
||||
pub end_label: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -362,6 +382,8 @@ pub struct FunctionDecl {
|
||||
pub args: Vec<TfArg>,
|
||||
pub stmts: Vec<Stmt>,
|
||||
pub dangling: Vec<Comment>,
|
||||
/// Label after `endfunction :`.
|
||||
pub end_label: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -373,6 +395,8 @@ pub struct TaskDecl {
|
||||
pub args: Vec<TfArg>,
|
||||
pub stmts: Vec<Stmt>,
|
||||
pub dangling: Vec<Comment>,
|
||||
/// Label after `endtask :`.
|
||||
pub end_label: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -397,12 +421,16 @@ pub enum StmtKind {
|
||||
label: Option<String>,
|
||||
stmts: Vec<Stmt>,
|
||||
dangling: Vec<Comment>,
|
||||
/// Label after `end :`.
|
||||
end_label: Option<String>,
|
||||
},
|
||||
ForkJoin {
|
||||
label: Option<String>,
|
||||
join_kw: String,
|
||||
stmts: Vec<Stmt>,
|
||||
dangling: Vec<Comment>,
|
||||
/// Label after `join :` (any join kind).
|
||||
end_label: Option<String>,
|
||||
},
|
||||
If {
|
||||
qualifier: Option<String>,
|
||||
@@ -478,7 +506,7 @@ pub enum StmtKind {
|
||||
Break,
|
||||
Continue,
|
||||
Disable(String),
|
||||
Directive(String),
|
||||
Directive(RawText),
|
||||
/// Immediate assertion: kept simple — `assert (expr) stmt else stmt;`
|
||||
Assert {
|
||||
kw: String,
|
||||
@@ -540,6 +568,9 @@ pub enum Expr {
|
||||
lhs: Box<Expr>,
|
||||
op: String,
|
||||
rhs: Box<Expr>,
|
||||
/// Comments written between the left operand and the operator. They
|
||||
/// force the chain to break, with the operator starting the new line.
|
||||
comments: Vec<Comment>,
|
||||
},
|
||||
Ternary {
|
||||
cond: Box<Expr>,
|
||||
@@ -548,7 +579,7 @@ pub enum Expr {
|
||||
},
|
||||
Call {
|
||||
callee: Box<Expr>,
|
||||
args: Vec<Expr>,
|
||||
args: Vec<ExprItem>,
|
||||
},
|
||||
Index {
|
||||
base: Box<Expr>,
|
||||
@@ -568,12 +599,18 @@ pub enum Expr {
|
||||
base: Box<Expr>,
|
||||
name: String,
|
||||
},
|
||||
Concat(Vec<Expr>),
|
||||
Concat(Vec<ExprItem>),
|
||||
Repl {
|
||||
count: Box<Expr>,
|
||||
inner: Vec<Expr>,
|
||||
},
|
||||
Paren(Box<Expr>),
|
||||
Paren {
|
||||
inner: Box<Expr>,
|
||||
/// Comments written just inside the `(`.
|
||||
before: Vec<Comment>,
|
||||
/// Comments left over just before the `)`.
|
||||
after: Vec<Comment>,
|
||||
},
|
||||
/// `ty'(expr)` cast; `ty` kept as raw text.
|
||||
Cast {
|
||||
ty: String,
|
||||
@@ -587,7 +624,7 @@ pub enum Expr {
|
||||
},
|
||||
Inside {
|
||||
lhs: Box<Expr>,
|
||||
ranges: Vec<Expr>,
|
||||
ranges: Vec<ExprItem>,
|
||||
},
|
||||
/// `[a:b]` inside an `inside` range list or value range.
|
||||
ValueRange {
|
||||
@@ -606,7 +643,17 @@ pub enum Expr {
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PatternItem {
|
||||
pub meta: Meta,
|
||||
/// `key: value` (key may be `default`, a type, or an expression).
|
||||
pub key: Option<Expr>,
|
||||
pub value: Expr,
|
||||
}
|
||||
|
||||
/// One element of a bracketed expression list (a concatenation, a call
|
||||
/// argument list, an `inside` set), with the comments written around it. A
|
||||
/// comment on an element is what forces its list to break one per line.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ExprItem {
|
||||
pub meta: Meta,
|
||||
pub expr: Expr,
|
||||
}
|
||||
@@ -561,21 +561,24 @@ pub fn tokenize(source: &str) -> Result<Vec<Token>, LexError> {
|
||||
RawKind::LineComment | RawKind::BlockComment => {
|
||||
let same_line_as_prev =
|
||||
raw.newlines_before == 0 && !tokens.is_empty() && pending.is_empty();
|
||||
let comment = Comment {
|
||||
text: raw.text,
|
||||
blank_before: raw.newlines_before > 1 || pending_blank,
|
||||
line: raw.line,
|
||||
col: raw.col,
|
||||
};
|
||||
if same_line_as_prev {
|
||||
// Trailing comment for the previous real token.
|
||||
let prev = tokens.last_mut().unwrap();
|
||||
match &mut prev.trailing {
|
||||
Some(existing) => {
|
||||
existing.push(' ');
|
||||
existing.push_str(&raw.text);
|
||||
existing.text.push(' ');
|
||||
existing.text.push_str(&comment.text);
|
||||
}
|
||||
None => prev.trailing = Some(raw.text),
|
||||
None => prev.trailing = Some(comment),
|
||||
}
|
||||
} else {
|
||||
pending.push(Comment {
|
||||
text: raw.text,
|
||||
blank_before: raw.newlines_before > 1 || pending_blank,
|
||||
});
|
||||
pending.push(comment);
|
||||
pending_blank = false;
|
||||
}
|
||||
}
|
||||
@@ -632,7 +635,9 @@ mod tests {
|
||||
fn trailing_comment_attaches() {
|
||||
let toks = tokenize("assign x = y; // comment\nwire z;").unwrap();
|
||||
let semi = toks.iter().find(|t| t.is_sym(";")).unwrap();
|
||||
assert_eq!(semi.trailing.as_deref(), Some("// comment"));
|
||||
let trailing = semi.trailing.as_ref().expect("trailing comment");
|
||||
assert_eq!(trailing.text, "// comment");
|
||||
assert_eq!((trailing.line, trailing.col), (1, 15));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -640,6 +645,16 @@ mod tests {
|
||||
let toks = tokenize("// header\n\n// second\nmodule m; endmodule").unwrap();
|
||||
assert_eq!(toks[0].leading.len(), 2);
|
||||
assert!(toks[0].leading[1].blank_before);
|
||||
assert_eq!((toks[0].leading[1].line, toks[0].leading[1].col), (3, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comment_records_its_own_column() {
|
||||
let toks = tokenize("module m;\n /* doc\n more */\n wire w;\nendmodule").unwrap();
|
||||
let wire = toks.iter().find(|t| t.is_kw("wire")).unwrap();
|
||||
let doc = &wire.leading[0];
|
||||
assert_eq!((doc.line, doc.col), (2, 3));
|
||||
assert!(doc.text.starts_with("/* doc"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -61,7 +61,7 @@ pub struct Parser {
|
||||
tokens: Vec<Token>,
|
||||
pos: usize,
|
||||
pending_leading: Vec<Comment>,
|
||||
pending_trailing: Vec<String>,
|
||||
pending_trailing: Vec<Comment>,
|
||||
}
|
||||
|
||||
pub fn parse(tokens: Vec<Token>) -> PResult<SourceFile> {
|
||||
@@ -155,9 +155,7 @@ impl Parser {
|
||||
let mut leading: Vec<Comment> = Vec::new();
|
||||
// Unharvested trailing comments from earlier tokens become leading
|
||||
// comments here so they are never lost.
|
||||
for tr in self.pending_trailing.drain(..) {
|
||||
leading.push(Comment { text: tr, blank_before: false });
|
||||
}
|
||||
leading.append(&mut self.pending_trailing);
|
||||
leading.append(&mut self.pending_leading);
|
||||
let tok = &mut self.tokens[self.pos];
|
||||
leading.append(&mut tok.leading);
|
||||
@@ -171,23 +169,79 @@ impl Parser {
|
||||
if self.pending_trailing.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(self.pending_trailing.drain(..).collect::<Vec<_>>().join(" "))
|
||||
Some(self.pending_trailing.drain(..).map(|c| c.text).collect::<Vec<_>>().join(" "))
|
||||
}
|
||||
}
|
||||
|
||||
/// Comments sitting right before a closing keyword (`end`, `endmodule`,
|
||||
/// ...) — they belong inside the enclosing construct.
|
||||
fn take_dangling(&mut self) -> Vec<Comment> {
|
||||
let mut out: Vec<Comment> = Vec::new();
|
||||
for tr in self.pending_trailing.drain(..) {
|
||||
out.push(Comment { text: tr, blank_before: false });
|
||||
}
|
||||
let mut out: Vec<Comment> = std::mem::take(&mut self.pending_trailing);
|
||||
out.append(&mut self.pending_leading);
|
||||
let tok = &mut self.tokens[self.pos];
|
||||
out.append(&mut tok.leading);
|
||||
out
|
||||
}
|
||||
|
||||
/// One element of a bracketed expression list, with the comments written
|
||||
/// before it. The caller harvests the trailing comment after the comma.
|
||||
fn parse_expr_item(&mut self) -> PResult<ExprItem> {
|
||||
let meta = self.take_meta();
|
||||
let expr = self.parse_expr()?;
|
||||
Ok(ExprItem { meta, expr })
|
||||
}
|
||||
|
||||
/// Continue a comma-separated expression list whose first element is
|
||||
/// already parsed, harvesting the comment written after each comma and
|
||||
/// the one before the closing bracket.
|
||||
fn parse_expr_list(&mut self, first: ExprItem) -> PResult<Vec<ExprItem>> {
|
||||
let mut items = vec![first];
|
||||
loop {
|
||||
let more = self.eat_sym(",");
|
||||
if let Some(last) = items.last_mut() {
|
||||
if last.meta.trailing.is_none() {
|
||||
last.meta.trailing = self.take_trailing();
|
||||
}
|
||||
}
|
||||
if !more {
|
||||
return Ok(items);
|
||||
}
|
||||
items.push(self.parse_expr_item()?);
|
||||
}
|
||||
}
|
||||
|
||||
/// Consume the current token as verbatim text, keeping the column it
|
||||
/// started in.
|
||||
fn take_raw_text(&mut self) -> RawText {
|
||||
let col = self.cur().col;
|
||||
RawText { text: self.bump().text, col }
|
||||
}
|
||||
|
||||
/// Take the comments the lexer attached *before* the current token,
|
||||
/// bypassing the usual pending-comment plumbing so a construct can keep
|
||||
/// them itself. Must be called before the token is consumed.
|
||||
fn take_leading_here(&mut self) -> Vec<Comment> {
|
||||
std::mem::take(&mut self.tokens[self.pos].leading)
|
||||
}
|
||||
|
||||
/// Same for the comment written *after* the current token on its line.
|
||||
fn take_trailing_here(&mut self) -> Vec<Comment> {
|
||||
match self.tokens[self.pos].trailing.take() {
|
||||
Some(comment) => vec![comment],
|
||||
None => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `: name` after a closing keyword (`end`, `join`, `endfunction`,
|
||||
/// ...), if present. Kept on the node so the formatter can print it back.
|
||||
fn parse_end_label(&mut self) -> PResult<Option<String>> {
|
||||
if self.eat_sym(":") {
|
||||
Ok(Some(self.expect_ident()?))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
/// Given `self.tokens[i]` == an opening bracket, return the index just
|
||||
/// past its matching close. Used for disambiguating lookahead only.
|
||||
fn scan_matching(&self, mut i: usize, open: &str, close: &str) -> usize {
|
||||
@@ -226,7 +280,7 @@ impl Parser {
|
||||
fn parse_item(&mut self) -> PResult<Item> {
|
||||
let mut meta = self.take_meta();
|
||||
while self.cur().kind == TokenKind::Attribute {
|
||||
meta.attrs.push(self.bump().text);
|
||||
meta.attrs.push(self.take_raw_text());
|
||||
let tok = &mut self.tokens[self.pos];
|
||||
meta.leading.append(&mut tok.leading);
|
||||
}
|
||||
@@ -240,7 +294,7 @@ impl Parser {
|
||||
fn parse_item_kind(&mut self) -> PResult<ItemKind> {
|
||||
let t = self.cur();
|
||||
match t.kind {
|
||||
TokenKind::Directive => Ok(ItemKind::Directive(self.bump().text)),
|
||||
TokenKind::Directive => Ok(ItemKind::Directive(self.take_raw_text())),
|
||||
TokenKind::Keyword => self.parse_keyword_item(),
|
||||
TokenKind::Ident => self.parse_ident_item(),
|
||||
_ => self.error("expected item"),
|
||||
@@ -385,10 +439,8 @@ impl Parser {
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_kw("endpackage")?;
|
||||
if self.eat_sym(":") {
|
||||
self.expect_ident()?;
|
||||
}
|
||||
Ok(ItemKind::Package { kw, name, items, dangling })
|
||||
let end_label = self.parse_end_label()?;
|
||||
Ok(ItemKind::Package { kw, name, items, dangling, end_label })
|
||||
}
|
||||
|
||||
fn parse_import_list(&mut self) -> PResult<Vec<String>> {
|
||||
@@ -445,7 +497,7 @@ impl Parser {
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_kw("endmodule")?;
|
||||
let end_label = if self.eat_sym(":") { Some(self.expect_ident()?) } else { None };
|
||||
let end_label = self.parse_end_label()?;
|
||||
Ok(Module { kw, name, imports, param_ports, ports, items, dangling, end_label })
|
||||
}
|
||||
|
||||
@@ -544,14 +596,14 @@ impl Parser {
|
||||
None
|
||||
}
|
||||
};
|
||||
let net = if NET_KEYWORDS.contains(&self.cur().text.as_str())
|
||||
&& self.cur().kind == TokenKind::Keyword
|
||||
{
|
||||
Some(self.bump().text)
|
||||
} else if self.cur().is_kw("var") {
|
||||
Some(self.bump().text)
|
||||
} else {
|
||||
None
|
||||
let net = {
|
||||
let t = self.cur();
|
||||
let is_net = t.kind == TokenKind::Keyword && NET_KEYWORDS.contains(&t.text.as_str());
|
||||
if is_net || t.is_kw("var") {
|
||||
Some(self.bump().text)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let ty = self.parse_opt_data_type()?;
|
||||
let name = self.expect_ident()?;
|
||||
@@ -686,14 +738,14 @@ impl Parser {
|
||||
|
||||
fn parse_port_decl(&mut self) -> PResult<PortDecl> {
|
||||
let dir = self.bump().text;
|
||||
let net = if NET_KEYWORDS.contains(&self.cur().text.as_str())
|
||||
&& self.cur().kind == TokenKind::Keyword
|
||||
{
|
||||
Some(self.bump().text)
|
||||
} else if self.cur().is_kw("var") {
|
||||
Some(self.bump().text)
|
||||
} else {
|
||||
None
|
||||
let net = {
|
||||
let t = self.cur();
|
||||
let is_net = t.kind == TokenKind::Keyword && NET_KEYWORDS.contains(&t.text.as_str());
|
||||
if is_net || t.is_kw("var") {
|
||||
Some(self.bump().text)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let ty = self.parse_opt_data_type()?;
|
||||
let declarators = self.parse_declarators()?;
|
||||
@@ -818,7 +870,7 @@ impl Parser {
|
||||
first
|
||||
};
|
||||
self.expect_sym(")")?;
|
||||
Ok(Expr::Paren(Box::new(expr)))
|
||||
Ok(Expr::Paren { inner: Box::new(expr), before: Vec::new(), after: Vec::new() })
|
||||
} else {
|
||||
self.parse_primary()
|
||||
}
|
||||
@@ -1076,13 +1128,17 @@ impl Parser {
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_kw("end")?;
|
||||
if self.eat_sym(":") {
|
||||
self.expect_ident()?;
|
||||
}
|
||||
Ok(GenBlock { label, is_block: true, items, dangling })
|
||||
let end_label = self.parse_end_label()?;
|
||||
Ok(GenBlock { label, is_block: true, items, dangling, end_label })
|
||||
} else {
|
||||
let item = self.parse_item()?;
|
||||
Ok(GenBlock { label: None, is_block: false, items: vec![item], dangling: Vec::new() })
|
||||
Ok(GenBlock {
|
||||
label: None,
|
||||
is_block: false,
|
||||
items: vec![item],
|
||||
dangling: Vec::new(),
|
||||
end_label: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1114,8 +1170,8 @@ impl Parser {
|
||||
let has_parens = self.cur().is_sym("(");
|
||||
let args = self.parse_tf_ports()?;
|
||||
self.expect_sym(";")?;
|
||||
let (stmts, dangling) = self.parse_tf_body("endfunction")?;
|
||||
Ok(FunctionDecl { qualifiers, ret, name, has_parens, args, stmts, dangling })
|
||||
let (stmts, dangling, end_label) = self.parse_tf_body("endfunction")?;
|
||||
Ok(FunctionDecl { qualifiers, ret, name, has_parens, args, stmts, dangling, end_label })
|
||||
}
|
||||
|
||||
fn parse_task(&mut self) -> PResult<TaskDecl> {
|
||||
@@ -1128,8 +1184,8 @@ impl Parser {
|
||||
let has_parens = self.cur().is_sym("(");
|
||||
let args = self.parse_tf_ports()?;
|
||||
self.expect_sym(";")?;
|
||||
let (stmts, dangling) = self.parse_tf_body("endtask")?;
|
||||
Ok(TaskDecl { qualifiers, name, has_parens, args, stmts, dangling })
|
||||
let (stmts, dangling, end_label) = self.parse_tf_body("endtask")?;
|
||||
Ok(TaskDecl { qualifiers, name, has_parens, args, stmts, dangling, end_label })
|
||||
}
|
||||
|
||||
fn parse_tf_ports(&mut self) -> PResult<Vec<TfArg>> {
|
||||
@@ -1166,17 +1222,18 @@ impl Parser {
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
fn parse_tf_body(&mut self, end_kw: &str) -> PResult<(Vec<Stmt>, Vec<Comment>)> {
|
||||
fn parse_tf_body(
|
||||
&mut self,
|
||||
end_kw: &str,
|
||||
) -> PResult<(Vec<Stmt>, Vec<Comment>, Option<String>)> {
|
||||
let mut stmts = Vec::new();
|
||||
while !self.cur().is_kw(end_kw) && !self.at_eof() {
|
||||
stmts.push(self.parse_stmt()?);
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_kw(end_kw)?;
|
||||
if self.eat_sym(":") {
|
||||
self.expect_ident()?;
|
||||
}
|
||||
Ok((stmts, dangling))
|
||||
let end_label = self.parse_end_label()?;
|
||||
Ok((stmts, dangling, end_label))
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -1186,7 +1243,7 @@ impl Parser {
|
||||
fn parse_stmt(&mut self) -> PResult<Stmt> {
|
||||
let mut meta = self.take_meta();
|
||||
while self.cur().kind == TokenKind::Attribute {
|
||||
meta.attrs.push(self.bump().text);
|
||||
meta.attrs.push(self.take_raw_text());
|
||||
let tok = &mut self.tokens[self.pos];
|
||||
meta.leading.append(&mut tok.leading);
|
||||
}
|
||||
@@ -1200,7 +1257,7 @@ impl Parser {
|
||||
fn parse_stmt_kind(&mut self) -> PResult<StmtKind> {
|
||||
let t = self.cur();
|
||||
if t.kind == TokenKind::Directive {
|
||||
return Ok(StmtKind::Directive(self.bump().text));
|
||||
return Ok(StmtKind::Directive(self.take_raw_text()));
|
||||
}
|
||||
if t.is_sym(";") {
|
||||
self.bump();
|
||||
@@ -1243,10 +1300,8 @@ impl Parser {
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
self.expect_kw("end")?;
|
||||
if self.eat_sym(":") {
|
||||
self.expect_ident()?;
|
||||
}
|
||||
Ok(StmtKind::Block { label, stmts, dangling })
|
||||
let end_label = self.parse_end_label()?;
|
||||
Ok(StmtKind::Block { label, stmts, dangling, end_label })
|
||||
}
|
||||
"fork" => {
|
||||
self.bump();
|
||||
@@ -1261,10 +1316,8 @@ impl Parser {
|
||||
}
|
||||
let dangling = self.take_dangling();
|
||||
let join_kw = self.bump().text;
|
||||
if self.eat_sym(":") {
|
||||
self.expect_ident()?;
|
||||
}
|
||||
Ok(StmtKind::ForkJoin { label, join_kw, stmts, dangling })
|
||||
let end_label = self.parse_end_label()?;
|
||||
Ok(StmtKind::ForkJoin { label, join_kw, stmts, dangling, end_label })
|
||||
}
|
||||
"unique" | "unique0" | "priority" => {
|
||||
let qualifier = Some(self.bump().text);
|
||||
@@ -1557,19 +1610,30 @@ impl Parser {
|
||||
}
|
||||
|
||||
fn parse_sens_list(&mut self) -> PResult<SensList> {
|
||||
if self.eat_sym("*") {
|
||||
return Ok(SensList::Star);
|
||||
if self.cur().is_sym("*") {
|
||||
// `@*` without parens.
|
||||
let before = self.take_leading_here();
|
||||
self.bump();
|
||||
return Ok(SensList::Star { before, after: Vec::new() });
|
||||
}
|
||||
if self.cur().kind == TokenKind::Ident {
|
||||
// `@ident` without parens.
|
||||
let name = self.expect_ident()?;
|
||||
return Ok(SensList::List(vec![SensItem { edge: None, expr: Expr::Ident(name) }]));
|
||||
}
|
||||
self.expect_sym("(")?;
|
||||
if self.eat_sym("*") {
|
||||
if self.cur().is_sym("(") && self.nth(1).is_sym("*") {
|
||||
// `@( /* c */ * /* d */ )`: the comments belong to the star, not
|
||||
// to whatever node comes next.
|
||||
let mut before = self.take_trailing_here();
|
||||
self.bump(); // (
|
||||
before.append(&mut self.take_leading_here());
|
||||
let mut after = self.take_trailing_here();
|
||||
self.bump(); // *
|
||||
after.append(&mut self.take_leading_here());
|
||||
self.expect_sym(")")?;
|
||||
return Ok(SensList::Star);
|
||||
return Ok(SensList::Star { before, after });
|
||||
}
|
||||
self.expect_sym("(")?;
|
||||
let mut items = Vec::new();
|
||||
loop {
|
||||
let edge = {
|
||||
@@ -1638,6 +1702,7 @@ impl Parser {
|
||||
}
|
||||
|
||||
fn parse_binary(&mut self, min_prec: u8) -> PResult<Expr> {
|
||||
let mark = self.pending_trailing.len();
|
||||
let mut lhs = self.parse_unary()?;
|
||||
while let Some(prec) = self.binary_prec() {
|
||||
if prec < min_prec {
|
||||
@@ -1646,29 +1711,44 @@ impl Parser {
|
||||
if self.cur().is_kw("inside") {
|
||||
self.bump();
|
||||
self.expect_sym("{")?;
|
||||
let mut ranges = Vec::new();
|
||||
let mut ranges: Vec<ExprItem> = Vec::new();
|
||||
loop {
|
||||
if self.cur().is_sym("[") {
|
||||
let mut meta = self.take_meta();
|
||||
let expr = if self.cur().is_sym("[") {
|
||||
self.bump();
|
||||
let lo = self.parse_expr()?;
|
||||
self.expect_sym(":")?;
|
||||
let hi = self.parse_expr()?;
|
||||
self.expect_sym("]")?;
|
||||
ranges.push(Expr::ValueRange { lo: Box::new(lo), hi: Box::new(hi) });
|
||||
Expr::ValueRange { lo: Box::new(lo), hi: Box::new(hi) }
|
||||
} else {
|
||||
ranges.push(self.parse_expr()?);
|
||||
self.parse_expr()?
|
||||
};
|
||||
let more = self.eat_sym(",");
|
||||
if more {
|
||||
meta.trailing = self.take_trailing();
|
||||
}
|
||||
if !self.eat_sym(",") {
|
||||
ranges.push(ExprItem { meta, expr });
|
||||
if !more {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if let Some(last) = ranges.last_mut() {
|
||||
if last.meta.trailing.is_none() {
|
||||
last.meta.trailing = self.take_trailing();
|
||||
}
|
||||
}
|
||||
self.expect_sym("}")?;
|
||||
lhs = Expr::Inside { lhs: Box::new(lhs), ranges };
|
||||
continue;
|
||||
}
|
||||
// Comments between the operand and the operator belong to this
|
||||
// node; left where they are they would drift past the operator.
|
||||
let mut comments = self.pending_trailing.split_off(mark);
|
||||
comments.append(&mut self.take_leading_here());
|
||||
let op = self.bump().text;
|
||||
let rhs = self.parse_binary(prec + 1)?;
|
||||
lhs = Expr::Binary { lhs: Box::new(lhs), op, rhs: Box::new(rhs) };
|
||||
lhs = Expr::Binary { lhs: Box::new(lhs), op, rhs: Box::new(rhs), comments };
|
||||
}
|
||||
Ok(lhs)
|
||||
}
|
||||
@@ -1722,12 +1802,9 @@ impl Parser {
|
||||
self.bump();
|
||||
let mut args = Vec::new();
|
||||
if !self.cur().is_sym(")") {
|
||||
loop {
|
||||
args.push(self.parse_expr_or_type()?);
|
||||
if !self.eat_sym(",") {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let meta = self.take_meta();
|
||||
let first = ExprItem { meta, expr: self.parse_expr_or_type()? };
|
||||
args = self.parse_expr_list(first)?;
|
||||
}
|
||||
self.expect_sym(")")?;
|
||||
expr = Expr::Call { callee: Box::new(expr), args };
|
||||
@@ -1786,28 +1863,36 @@ impl Parser {
|
||||
let sym = t.text.clone();
|
||||
match sym.as_str() {
|
||||
"(" => {
|
||||
// Comments written just inside the parens stay there;
|
||||
// anything else would move them across a token.
|
||||
let mut before = self.take_trailing_here();
|
||||
self.bump();
|
||||
before.append(&mut self.take_leading_here());
|
||||
let mark = self.pending_trailing.len();
|
||||
let inner = self.parse_expr()?;
|
||||
if self.eat_sym(":") {
|
||||
let inner = if self.eat_sym(":") {
|
||||
let typ = self.parse_expr()?;
|
||||
self.expect_sym(":")?;
|
||||
let max = self.parse_expr()?;
|
||||
self.expect_sym(")")?;
|
||||
return Ok(Expr::Paren(Box::new(Expr::MinTypMax {
|
||||
Expr::MinTypMax {
|
||||
min: Box::new(inner),
|
||||
typ: Box::new(typ),
|
||||
max: Box::new(max),
|
||||
})));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
inner
|
||||
};
|
||||
let mut after = self.pending_trailing.split_off(mark);
|
||||
after.append(&mut self.take_leading_here());
|
||||
self.expect_sym(")")?;
|
||||
Ok(Expr::Paren(Box::new(inner)))
|
||||
Ok(Expr::Paren { inner: Box::new(inner), before, after })
|
||||
}
|
||||
"{" => {
|
||||
self.bump();
|
||||
if self.cur().is_sym("}") {
|
||||
return self.error("empty concatenation");
|
||||
}
|
||||
let first = self.parse_expr()?;
|
||||
let first = self.parse_expr_item()?;
|
||||
if self.cur().is_sym("{") {
|
||||
// Replication {N{a, b}}
|
||||
self.bump();
|
||||
@@ -1817,12 +1902,9 @@ impl Parser {
|
||||
}
|
||||
self.expect_sym("}")?;
|
||||
self.expect_sym("}")?;
|
||||
return Ok(Expr::Repl { count: Box::new(first), inner });
|
||||
}
|
||||
let mut items = vec![first];
|
||||
while self.eat_sym(",") {
|
||||
items.push(self.parse_expr()?);
|
||||
return Ok(Expr::Repl { count: Box::new(first.expr), inner });
|
||||
}
|
||||
let items = self.parse_expr_list(first)?;
|
||||
self.expect_sym("}")?;
|
||||
Ok(Expr::Concat(items))
|
||||
}
|
||||
@@ -1831,22 +1913,32 @@ impl Parser {
|
||||
let mut items = Vec::new();
|
||||
if !self.cur().is_sym("}") {
|
||||
loop {
|
||||
let mut meta = self.take_meta();
|
||||
let key_or_val = if self.cur().is_kw("default") {
|
||||
self.bump();
|
||||
Expr::Ident("default".to_string())
|
||||
} else {
|
||||
self.parse_expr_or_type()?
|
||||
};
|
||||
if self.eat_sym(":") {
|
||||
let value = self.parse_expr()?;
|
||||
items.push(PatternItem { key: Some(key_or_val), value });
|
||||
let (key, value) = if self.eat_sym(":") {
|
||||
(Some(key_or_val), self.parse_expr()?)
|
||||
} else {
|
||||
items.push(PatternItem { key: None, value: key_or_val });
|
||||
(None, key_or_val)
|
||||
};
|
||||
let more = self.eat_sym(",");
|
||||
if more {
|
||||
meta.trailing = self.take_trailing();
|
||||
}
|
||||
if !self.eat_sym(",") {
|
||||
items.push(PatternItem { meta, key, value });
|
||||
if !more {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if let Some(last) = items.last_mut() {
|
||||
if last.meta.trailing.is_none() {
|
||||
last.meta.trailing = self.take_trailing();
|
||||
}
|
||||
}
|
||||
}
|
||||
self.expect_sym("}")?;
|
||||
Ok(Expr::AssignPattern(items))
|
||||
|
||||
@@ -33,6 +33,13 @@ pub struct Comment {
|
||||
/// True if at least one blank line separated this comment from whatever
|
||||
/// preceded it.
|
||||
pub blank_before: bool,
|
||||
/// 1-based source line of the opening `//` or `/*`.
|
||||
pub line: u32,
|
||||
/// 1-based source column of the opening `//` or `/*`. The formatter
|
||||
/// dedents the continuation lines of a multi-line comment by this much
|
||||
/// before re-indenting them, which is what keeps re-formatting a fixed
|
||||
/// point.
|
||||
pub col: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -47,7 +54,8 @@ pub struct Token {
|
||||
/// earlier lines).
|
||||
pub leading: Vec<Comment>,
|
||||
/// A comment that appeared after this token on the same source line.
|
||||
pub trailing: Option<String>,
|
||||
/// Several such comments are merged into one, joined by a space.
|
||||
pub trailing: Option<Comment>,
|
||||
/// True if at least one blank line separated this token from the previous
|
||||
/// token or comment.
|
||||
pub blank_before: bool,
|
||||
|
||||
@@ -0,0 +1,521 @@
|
||||
# formatter-bug-fixes
|
||||
|
||||
## Goal
|
||||
|
||||
Fix the five confirmed formatter/parser bugs the case-tables and safety-net
|
||||
features found and parked. All five made `vfmt` refuse to write output (exit 2)
|
||||
because the runtime safety net caught them as token loss, comment motion or
|
||||
non-convergence — so every one of them was a file the formatter could not
|
||||
format at all. Each fix lands with its parked `#SKIP` case turned into a live
|
||||
regression case plus new cases around it.
|
||||
|
||||
The five:
|
||||
|
||||
1. Continuation lines of a multi-line block comment gain the current indent on
|
||||
every pass (unbounded; breaks hard invariant #2, idempotency).
|
||||
2. A comment inside an expression group is lifted out of the group instead of
|
||||
forcing it to break, contrary to `README.md`'s "a comment inside a group
|
||||
forces it to break".
|
||||
3. Closing block labels (`end : x`, `join* : x`, `endfunction : x`,
|
||||
`endtask : x`, `endpackage : x`, generate `end : x`) are dropped; only
|
||||
`endmodule : x` survived.
|
||||
4. A multi-instance declaration (`sub u0 (.a(x)), u1 (.a(y));`) always breaks
|
||||
and under-indents the continuation instances.
|
||||
5. `always @( /* c */ * )` loses the comment: `parse_sens_list` discarded
|
||||
comments written inside the parens of an implicit sensitivity list.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- The four `#SKIP` expected outputs are the spec. None of them was changed.
|
||||
- **Comment re-indentation is relative to the comment's original opening
|
||||
column.** A block comment's continuation lines are dedented by
|
||||
`original_column - 1` (spaces/tabs only, never past the first non-blank
|
||||
character) before the printer re-indents them. That is what makes the
|
||||
transform a fixed point: the second pass sees the column the first pass
|
||||
produced and dedents by exactly what it added. Continuation lines that
|
||||
started *left* of the opening column cannot be preserved as-is — the printer
|
||||
always prepends the current indent — so they land on the new indent; that is
|
||||
stable from the second pass on and is pinned by a case.
|
||||
- The same re-indent rule is applied to multi-line **directives**
|
||||
(`` `define X \``) and **attributes**, which had the identical unbounded
|
||||
drift for the identical reason. See the work log.
|
||||
- Comments are compared by text in stream order by `verify.rs`, so a comment
|
||||
kept on a construct must be printed lexically between the same two tokens it
|
||||
sat between in the input. For the sensitivity list that means comments
|
||||
written before the `*` are printed before it and comments after it are
|
||||
printed after it, rather than all being pushed to one side.
|
||||
- **`verify.rs` needed no new normalization and none was added.** With the
|
||||
comment printed inside the parens (`@(/* c */ *)`), input and output produce
|
||||
the same stream and the existing `@ ( * )` → `@ *` collapse simply does not
|
||||
fire on either side (it requires the four symbols to be adjacent). The only
|
||||
`verify.rs` edit is that comment items now report their *own* line/column
|
||||
instead of the owning token's, which is a diagnostics improvement — positions
|
||||
are never compared.
|
||||
- `(*` immediately followed by anything but `)` lexes as an attribute
|
||||
instance, so `@(*` may only be printed when `)` follows immediately. When
|
||||
there is a comment after the star the formatter prints `@( * /* c */)` with
|
||||
the star off the paren. This is a lexer constraint, not a style choice.
|
||||
- A closing label is always printed in the `endmodule : m` spelling already
|
||||
used for modules (space, colon, space). Labels are preserved verbatim; the
|
||||
formatter never invents or removes one, and never checks that a closing
|
||||
label matches its opening label (that is a linter's job).
|
||||
- A comment inside an expression makes the enclosing `=` **hug**: the value
|
||||
keeps its opening bracket on the assignment's line (`assign y = {`) instead
|
||||
of moving to the next line. Without that, the parked case's expected output
|
||||
is unreachable, because a hard line anywhere inside a group breaks every
|
||||
enclosing group in this printer. The hug only applies when the value already
|
||||
contains a forced break, so no case without comments changed.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **`vlog_parser::token::Comment` gained a position** (the handshake request
|
||||
filed by the safety-net feature): `Comment { text, blank_before, line, col }`,
|
||||
1-based, pointing at the opening `//` or `/*`. `col` is what makes bug 1
|
||||
fixable. **Consumers**: anything constructing a `Comment` must supply the two
|
||||
fields; in-tree that is only `lexer.rs`.
|
||||
- **`vlog_parser::token::Token::trailing` is now `Option<Comment>`** instead of
|
||||
`Option<String>`, so a trailing comment carries a position too (it can be
|
||||
re-attached as a leading comment by the parser, and then it is re-indented).
|
||||
`verify.rs` and one lexer unit test were the only readers.
|
||||
- **`ast::RawText { text, col }`** is new and replaces the bare `String` in
|
||||
`ItemKind::Directive`, `StmtKind::Directive` and `Meta::attrs`, for the same
|
||||
re-indent reason.
|
||||
- **AST: closing labels are new fields** — `ItemKind::Package.end_label`,
|
||||
`GenBlock.end_label`, `FunctionDecl.end_label`, `TaskDecl.end_label`,
|
||||
`StmtKind::Block.end_label`, `StmtKind::ForkJoin.end_label`.
|
||||
- **AST: `SensList::Star` is now a struct variant** `Star { before, after }`
|
||||
carrying the comments written inside `@( ... * ... )`.
|
||||
- **AST: expression lists carry comments.** `ast::ExprItem { meta, expr }` is
|
||||
new; `Expr::Concat`, `Expr::Call.args` and `Expr::Inside.ranges` hold
|
||||
`Vec<ExprItem>` instead of `Vec<Expr>`, `PatternItem` gained a `meta`,
|
||||
`Expr::Paren` became `Paren { inner, before, after }`, and `Expr::Binary`
|
||||
gained `comments` (written between the left operand and the operator).
|
||||
`Expr::Repl`'s inner list was left as `Vec<Expr>` — it is printed with a
|
||||
fixed `", "` join rather than through `delimited`, so it has no break to
|
||||
force; a comment inside a replication is still refused by the safety net.
|
||||
- **`printer::contains_hard_line` is now `pub(crate)`** so `format.rs` can ask
|
||||
"does this value break on its own?" for the `=` hug described above.
|
||||
- `Meta.trailing` is still a bare `String`: several trailing comments merge
|
||||
into one there, and it is printed verbatim on one line, so it needs no
|
||||
position.
|
||||
- Nothing outside `vlog_parser` / `vlog_formatter` was touched. `crates/vfmt`
|
||||
and the top-level `README.md` (another agent's scope) are untouched;
|
||||
`cargo fmt` was run and left those files byte-identical.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Bug 3 — closing block labels preserved (`end`, all `join` kinds,
|
||||
`endfunction`, `endtask`, `endpackage`, generate `end`).
|
||||
- [x] Bug 4 — multi-instance declarations stay on one line when they fit and
|
||||
indent their continuation when they do not.
|
||||
- [x] Bug 5 — comments inside `@( * )` are kept next to the `*`.
|
||||
- [x] Bug 1 — block-comment continuation lines are dedented to their original
|
||||
opening column before re-indenting; idempotent. Same fix applied to
|
||||
multi-line directives and attributes.
|
||||
- [x] Bug 2 — a comment inside an expression forces its group to break, for
|
||||
concatenations, call arguments, `inside` sets, assignment patterns,
|
||||
parenthesized expressions and between the operands of a binary chain.
|
||||
- [x] `#SKIP` markers removed from all four parked cases; 17 new cases added
|
||||
across `comments`, `statements`, `instantiation`, `functions_tasks`,
|
||||
`module_headers` and `generate`.
|
||||
- [x] `cargo test --workspace` green, `cargo clippy --all-targets` silent
|
||||
(including the four pre-existing warnings), `cargo fmt --check` clean.
|
||||
- [ ] Not fixed, still refused by the safety net (documented, not hacked
|
||||
around): a comment inside a **replication** (`{2{a, // c`), a comment
|
||||
inside a compactly-printed bracket expression (`x[a /* c */ + b]`, where
|
||||
`expr_compact` has no line to break), and a comment between a value and
|
||||
the `;` that follows it (`assign y = a /* c */ ;`), which the statement
|
||||
harvests and re-prints after the `;`. All three are pre-existing and
|
||||
each needs its own small design decision.
|
||||
- [x] TODO.md: nothing to check off — none of these bugs had a backlog item.
|
||||
The "re-enable the four `#SKIP` cases" item lives in the case-tables
|
||||
README's TODO and is now satisfied.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-18 — dev agent
|
||||
|
||||
**Bug 3 (closing block labels) — fixed.** The parser was parsing `: name`
|
||||
after every closing keyword and throwing the identifier away
|
||||
(`parse_package`, `parse_gen_block`, `parse_tf_body`, and the `begin` / `fork`
|
||||
arms of `parse_keyword_stmt`). Added `Parser::parse_end_label` — one helper,
|
||||
used by all six sites plus `parse_module`, which already kept its label by
|
||||
hand — and an `end_label` field on the six nodes. The formatter grew
|
||||
`Fmt::closing(kw, label)`, exactly the `endmodule : m` rendering generalized,
|
||||
and now uses it for `endmodule` too, so all seven closing keywords share one
|
||||
spelling. Un-skipped the parked `end : main` case and added five more: all
|
||||
three `join` kinds, nested `begin : inner`, `endfunction` + `endtask`,
|
||||
`endpackage`, and a generate-block `end : lane`.
|
||||
|
||||
**Bug 4 (multi-instance declarations) — fixed.** `Fmt::instantiation` emitted
|
||||
`text(",")` + `HardLine` between instances unconditionally, which both forced
|
||||
the break and left the continuation at the head's indent. Rewrote it in the
|
||||
shape `declarators` already uses: a single instance is emitted directly (no
|
||||
extra indent level, so its connection list still lines up under itself — the
|
||||
first attempt indented every instantiation's broken connection list by two
|
||||
extra columns and three existing cases caught it), several instances go into
|
||||
`group(indent(...))` with `Doc::Line` separators, so they fit on one line when
|
||||
they can and indent one level when they cannot. Per-instance leading and
|
||||
trailing comments are emitted in the multi-instance path, which also makes a
|
||||
comment between two instances break the list. Three cases: fits, does not fit,
|
||||
and comment-forces-break.
|
||||
|
||||
**Bug 5 (comments in an implicit sensitivity list) — fixed.**
|
||||
`parse_sens_list` now recognizes `@( * )` before consuming the `(` and keeps
|
||||
the comments the lexer attached around the star, in two buckets (`before`,
|
||||
`after`) so their order relative to the `*` survives the round trip. Two new
|
||||
parser helpers, `take_leading_here` / `take_trailing_here`, read the comments
|
||||
straight off the token instead of going through `pending_leading` /
|
||||
`pending_trailing`; that matters because the pending queues can hold older
|
||||
comments from before the `@`, and stealing one of those would move it across a
|
||||
token and trip the equivalence check. The formatter prints
|
||||
`@(/* c */ *)` / `@( * /* c */)`; a line comment inside gets a hard line so it
|
||||
cannot swallow the `*)`. **No `verify.rs` change was needed** — see
|
||||
Assumptions. One lexer constraint surfaced while testing: `@(*` followed by a
|
||||
space lexes as an attribute instance, so the `after` spelling keeps a space
|
||||
after the paren.
|
||||
|
||||
**Bug 1 (multi-line comment re-indent) — fixed**, using the handshake the
|
||||
safety-net agent asked for: `token::Comment` now carries `line`/`col`, filled
|
||||
in by the lexer (which already had both for every raw token). `Fmt::raw_text`
|
||||
became `raw_lines(text, col)`: continuation lines are dedented by `col - 1`
|
||||
before the printer prepends the current indent, so pass two removes exactly
|
||||
what pass one added and the text is a fixed point. `Token::trailing` had to
|
||||
become `Option<Comment>` for the same reason — an unharvested trailing comment
|
||||
is re-attached as a *leading* comment by `take_meta`, and from that moment it
|
||||
goes through the re-indenting path.
|
||||
|
||||
While testing this I found the **same unbounded drift on multi-line
|
||||
directives** (`` `define FOO(a) \`` continued onto the next line, inside a
|
||||
module) and on multi-line attributes: identical root cause, identical
|
||||
refusal from the convergence check. Since the fix was one field away I did it
|
||||
rather than leave a known non-convergent input behind: `ast::RawText` pairs the
|
||||
verbatim text with its starting column, and `Directive` / `Meta::attrs` use it.
|
||||
This is beyond the five bugs as briefed; it is called out here and covered by a
|
||||
case (`a continued \`define inside a module keeps its continuation indent`).
|
||||
|
||||
**Bug 2 (comment inside an expression group) — fixed**, in three steps.
|
||||
|
||||
1. *List-shaped groups.* `ast::ExprItem { meta, expr }` gives concatenation
|
||||
elements, call arguments and `inside` set members the same `Meta` that port
|
||||
and connection lists already had, and `PatternItem` gained one; the parser
|
||||
harvests around the commas exactly the way `parse_declarators` does, and the
|
||||
formatter feeds them to the existing `delimited`, which already emits a hard
|
||||
line per comment and therefore already forces the break. So the fix was
|
||||
plumbing, not new layout code.
|
||||
2. *Parenthesized expressions.* `Expr::Paren` carries the comments written
|
||||
just inside its parens (`( // why` … / … `// sum )`), mirroring
|
||||
`SensList::Star`.
|
||||
3. *Between operands.* `Expr::Binary` carries the comments written between the
|
||||
left operand and the operator. When present, `binary_chain` puts the
|
||||
comment last on its line and starts the next line with the operator
|
||||
(`a // hi` ⏎ `+ b`) instead of the usual trailing-operator layout, which
|
||||
would produce `a // hi +` — i.e. an operator swallowed by a comment.
|
||||
|
||||
The parked case then still failed, on layout: `assign y =` broke before the
|
||||
`{` because a hard line anywhere inside a group breaks every enclosing group in
|
||||
this printer. Rather than redesign the IR, added `Fmt::assign_rhs`: if the
|
||||
right-hand side already contains a forced break, `= {` stays on the head line
|
||||
(the same shape as a broken port list keeping `module m (` on its line);
|
||||
otherwise the previous `Line`-and-indent behavior is unchanged. This is why
|
||||
`printer::contains_hard_line` became `pub(crate)`. Un-skipped the parked
|
||||
concatenation case and added five more (call args, assignment pattern,
|
||||
paren-adjacent, between binary operands, comment before an operator in a
|
||||
chain).
|
||||
|
||||
**Pre-existing clippy warnings.** All four are in files this change already
|
||||
touches, and all four fixes were trivial, so they are gone:
|
||||
`printer.rs`'s `manual_repeat_n` (`repeat_n`), `parser.rs`'s two
|
||||
`if_same_then_else` (the net-or-`var` test in `parse_ansi_port` /
|
||||
`parse_port_decl`, merged into one condition), and `format.rs`'s dead
|
||||
`ListItem::blank_before` (removed — `delimited` documents that blank lines
|
||||
inside bracketed lists are dropped deliberately, so the field had no future
|
||||
reader). `cargo clippy --all-targets` is now completely silent.
|
||||
|
||||
**Verification.** Beyond the suite: a hand-written stress file combining all
|
||||
five constructs (labeled package/function/task/fork, a starred sensitivity
|
||||
list with a comment, a commented concatenation, a multi-instance declaration,
|
||||
an indented banner comment) formats cleanly, and `vfmt` on its own output is
|
||||
byte-identical. Every bug's original repro from the two feature READMEs was
|
||||
re-run through the built CLI and now exits 0.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-19 — QA agent
|
||||
|
||||
**Scope**: ran the full tool chain, read every line of the diff (`token.rs`,
|
||||
`lexer.rs`, `parser.rs`, `ast.rs`, `format.rs`, `printer.rs`, `verify.rs`)
|
||||
against the seven claims in the assignment, then went well beyond the
|
||||
committed cases with a hand-built stress corpus (15 constructive `.sv` files
|
||||
plus the 3 known-refusal reproductions) run through a 3-pass fixed-point
|
||||
script, and a second script that re-ran every one of the 200 committed cases
|
||||
and all 4 `tests/fixtures/*.sv` files through 3 passes independently of
|
||||
`cargo test` (which only checks 2). No regression found. Full corpus and
|
||||
scripts left at `/private/tmp/claude-501/-Users-guoliangchen-repo-verilogrustformatter/9ecac3b9-8a0e-4065-85de-23cc2a396bad/scratchpad/{stress,stress3.py,regress3.py}` for reference (outside the repo).
|
||||
|
||||
**Tool chain** (workspace root):
|
||||
- `cargo test --workspace`: **70/70 pass**, 0 failed (18 `vfmt` unit + 12
|
||||
`cli.rs` + 3 `vlog_formatter` unit + 1 `cases.rs` (covering all 200 cases
|
||||
internally) + 2 `fixtures.rs` + 19 `verification.rs` + 15 `vlog_parser`
|
||||
unit). Confirmed 200 cases / 0 `#SKIP` two ways: `grep -c '^====' ` per
|
||||
file (14+32+18+26+16+13+20+18+28+15 = 200) and `grep -rn '#SKIP'` across
|
||||
`tests/cases/*.cases` (zero hits).
|
||||
- `cargo clippy --all-targets`: silent — `Finished` with no warning lines at
|
||||
all. Grepped the diff for `#[allow]`: none added anywhere. Independently
|
||||
confirmed the four previously-documented warnings are actually gone at
|
||||
their old sites: `printer.rs:91` now uses `repeat_n` (not
|
||||
`repeat().take()`), `parser.rs`'s `parse_ansi_port` (line 599-607) and
|
||||
`parse_port_decl` (line 741-749) both use the merged `net = { ... }` block
|
||||
instead of the old duplicated if/else-if, and `ListItem.blank_before` is
|
||||
gone from `format.rs` entirely (`grep` for the field name: no hits).
|
||||
- `cargo fmt --check`: exit 0, no output.
|
||||
|
||||
**Claim verdicts**
|
||||
|
||||
1. **Block-comment continuation drift — PASS.** Confirmed via 3 independent
|
||||
probes beyond `comments.cases`: a column-0 banner
|
||||
(`stress/01_comment_col0.sv`), a comment nested four `begin` levels deep
|
||||
(`02_comment_deep_nested.sv`), a comment inside a `case` item
|
||||
(`03_comment_in_case_item.sv`), a tab-indented comment
|
||||
(`05_tab_indented_comment.sv`), and — the sharpest probe —
|
||||
`04_ragged_continuation.sv`, a comment whose five continuation lines have
|
||||
five *different* indents (7, 3, 0, 8, 5 spaces), one of them starting
|
||||
left of the opening column. All five are stable across 3 passes. Hand
|
||||
-verified the ragged case's exact output against the dedent-then-reindent
|
||||
formula in the Assumptions (dedent by `col-1`, reindent by current
|
||||
indent = 2): input indents 7/3/0/8/5 → output indents 7/3/2/8/5, i.e.
|
||||
every line kept its *relative* raggedness except the one that started
|
||||
left of the opening column, which landed on the new indent exactly as
|
||||
the Assumptions predict. This is a materially stronger check than what's
|
||||
in `comments.cases` (whose ragged-indent case only has two continuation
|
||||
lines, both indented the same way).
|
||||
- **Tab/column consistency, audited as requested**: `lexer.rs`'s
|
||||
`RawLexer::bump` (line 72-82) increments `col` by exactly 1 per byte
|
||||
regardless of character, i.e. a tab counts as 1 column, not 8. The
|
||||
dedent side, `format.rs::strip_blanks` (line 1607-1616), strips up to
|
||||
`n` *characters* (space-or-tab, one per iteration), also byte-count
|
||||
based. The two are consistently unit-for-unit. Verified concretely: a
|
||||
comment opening after one leading tab (`col` = 2, so dedent = 1) whose
|
||||
continuation lines are themselves tab-indented dedents by exactly one
|
||||
leading tab per line, confirmed by hand-tracing
|
||||
`05_tab_indented_comment.sv`'s output.
|
||||
2. **Comment inside expression groups forces a break — PASS.** Built
|
||||
`stress/07_expr_comments_everywhere.sv` stacking every position at once:
|
||||
nested concat-inside-concat, nested call-inside-call, both ternary
|
||||
branches (parenthesized), an assignment pattern, an `inside` set, a
|
||||
binary-chain comment before the operator, and a standalone
|
||||
leading-and-trailing-commented paren. All eight comments survived in
|
||||
their original stream position, all eight groups broke open, 3-pass
|
||||
stable. One layout observation, not a defect (see Findings #3 below).
|
||||
3. **Closing block labels — PASS.** `stress/08_closing_labels.sv` exercises
|
||||
all three `join` kinds (`join`, `join_any`, `join_none`) plus nested
|
||||
labeled blocks (`begin : outer` › `begin : inner` › `end : inner` ›
|
||||
`end : outer`, checking the labels come back in the correct nesting
|
||||
order, not swapped) plus a labeled `function`/`task` inside a labeled
|
||||
`package`. `08c_generate_labeled.sv` adds a labeled generate `if`/`else`
|
||||
and a labeled generate `for`. `08b_end_label_trailing_comment.sv` (a case
|
||||
from the assignment's specific ask: "trailing comment AFTER an end
|
||||
label") — `end : blk // trailing after end label` — round-trips
|
||||
correctly with the comment staying trailing on the label line. All
|
||||
stable across 3 passes; all closing-label cases in the committed
|
||||
`.cases` diff (`statements.cases`, `functions_tasks.cases`,
|
||||
`generate.cases`, `module_headers.cases`) independently re-verified by
|
||||
hand-reading the diff, all four look correct against their stated
|
||||
construct.
|
||||
4. **Multi-instance declarations — PASS**, including the boundary the
|
||||
assignment specifically asked for. Built a generator
|
||||
(inline, not left in the corpus) that produces a two-instance
|
||||
declaration whose one-line rendering is *exactly* 100 and 101 columns:
|
||||
at 100 it stays on one line, at 101 it breaks with the continuation
|
||||
indented one level (4 spaces) under the 2-space head — distinguishable
|
||||
from a new statement, matching the bug-4 fix description exactly. Also
|
||||
checked instance arrays (`arr0 [3:0] (...)`) and parameter overrides
|
||||
together in one declaration (`09_multi_instance_params_arrays.sv`); all
|
||||
four sub-cases (fits / breaks / arrays / short) render as expected and
|
||||
are 3-pass stable.
|
||||
5. **`@( /* c */ * )` — PASS**, and more spellings than documented.
|
||||
`10_sens_list_spellings.sv` mixes `@( /* a */ * )`, `@(*)`, `@*`,
|
||||
`@( * /* trailing */ )`, and — not in any existing case —
|
||||
**both a before- and an after-comment on the same sensitivity list**:
|
||||
`@( /* before */ * /* after */ )` → `@(/* before */ * /* after */)`.
|
||||
Comment order relative to `*` preserved on both sides simultaneously,
|
||||
3-pass stable. Confirmed by direct code read that `verify.rs`'s only
|
||||
change is the two `comment_item(...)` call sites at lines 174 and 187
|
||||
now reading `comment.line`/`comment.col` (or `trailing.line`/
|
||||
`trailing.col`) instead of the owning token's — no comparison logic
|
||||
touched, no normalization added or removed. `git diff
|
||||
crates/vlog_formatter/src/verify.rs` is exactly those two one-line
|
||||
changes plus a doc-comment wording update; confirmed line-by-line.
|
||||
6. **Multi-line directives/attributes — PASS.** `06_define_ifdef.sv` (a
|
||||
3-continuation-line `` `define`` inside an `` `ifdef``, at top level) and
|
||||
`06b_define_inside_module.sv` (the same, nested inside a module — the
|
||||
specific case the work log calls out) both stable across 3 passes.
|
||||
`11_attribute_multiline.sv` (a 3-line `(* foo = 1, bar = 2, baz = 3 *)`
|
||||
attribute) also stable. Audited `RawText` usage for consistency across
|
||||
the three call sites the Handshakes promise (`ItemKind::Directive`,
|
||||
`StmtKind::Directive`, `Meta::attrs`): all three are populated via the
|
||||
same `Parser::take_raw_text()` (`parser.rs:215-218`, captures `col`
|
||||
before `bump()`) and all three are read via the same
|
||||
`Fmt::raw_text()` → `raw_lines(text, col)` (`format.rs:112-114`). No
|
||||
third code path exists for either type.
|
||||
7. **200 cases / 0 `#SKIP` / green workspace / silent clippy / clean
|
||||
fmt / self-format-stable — PASS**, all independently reproduced above.
|
||||
Additionally ran vfmt-on-its-own-output beyond the work log's one
|
||||
hand-written file: **every one of the 200 committed cases' expected
|
||||
outputs plus all 4 real fixture files** (204 total) through 3 passes via
|
||||
`regress3.py` — 0 failures, 0 cases where pass1's output differs from
|
||||
the `.cases` file's recorded expected output (an independent
|
||||
cross-check of the harness itself), 0 cases of 3rd-pass drift anywhere
|
||||
in the corpus.
|
||||
|
||||
**Handshake audit**
|
||||
|
||||
- `token::Comment{line,col}`: confirmed 1-based, confirmed populated only by
|
||||
`lexer.rs` (`tokenize`, lines 564-580) from `RawTok.line`/`.col`, which
|
||||
come from the raw lexer's running position at the *start* of the comment
|
||||
(`RawLexer::bump`, byte-granular column counting, tab = 1 column,
|
||||
consistent with the dedent side — see claim 1 above).
|
||||
- `Token::trailing: Option<Comment>`: grepped every `.trailing` site in both
|
||||
crates (`grep -rn '\.trailing'`). No caller still assumes `String`; the
|
||||
one remaining `Option<String>` is the unrelated `Meta.trailing` (several
|
||||
merged trailing comments, printed verbatim, no position needed — matches
|
||||
the Handshakes note that it "needs no position"). The lexer unit test
|
||||
(`lexer.rs:638`) uses `.expect("trailing comment")`, which is fine per
|
||||
CLAUDE.md's test exemption.
|
||||
- `RawText.col`: confirmed all three consumers (`ItemKind::Directive`,
|
||||
`StmtKind::Directive`, `Meta::attrs`) go through one producer
|
||||
(`take_raw_text`) and one consumer (`raw_text`/`raw_lines`) — see claim 6.
|
||||
- `printer::contains_hard_line` now `pub(crate)`: two call sites, both sane
|
||||
— the pre-existing two internal to `printer.rs` (group-fits and
|
||||
hard-line-forces-break checks) plus the one new external use in
|
||||
`format.rs::assign_rhs` (`format.rs:240`), which is exactly the "does
|
||||
this value already break?" check the Assumptions describe. No other new
|
||||
callers.
|
||||
- `CLAUDE.md` no-`unwrap`/`expect`/`panic!`-in-library-paths: grepped the
|
||||
diff's added (`+`) lines for `.unwrap()`/`.expect(`/`panic!`; the only
|
||||
three hits are all inside `#[cfg(test)] mod tests` in `lexer.rs`
|
||||
(`lexer.rs:638,644,653` in the new file), which CLAUDE.md exempts.
|
||||
`format.rs:532`'s pre-existing `unreachable!()` in `binary_chain` is
|
||||
unchanged context, not new.
|
||||
- No new dependencies (`git diff` on all three `Cargo.toml` + `Cargo.lock`:
|
||||
empty). No `#[allow]` added anywhere. `TODO.md`, top-level `README.md`,
|
||||
and `crates/vfmt/` are all byte-identical to `HEAD` (`git diff --stat`
|
||||
empty for all three) — matches the Handshakes claim that nothing outside
|
||||
`vlog_parser`/`vlog_formatter` was touched.
|
||||
|
||||
**Regression hunting**
|
||||
|
||||
Specifically tried to break something that used to work. Constructed and
|
||||
fixed (after finding my own test-file bugs, not formatter bugs — `initial`
|
||||
inside a function, `always` inside a function, `fork` at package scope are
|
||||
all illegal Verilog, not vfmt defects) a combined-stress file
|
||||
(`12_combo_stress.sv`: banner comment + labeled package/function/nested
|
||||
begin + `@( /* c */ * )` + commented concatenation + multi-instance, all in
|
||||
one file) — 3-pass stable, matches the work log's own combined-stress claim.
|
||||
Ran the entire `tests/cases/` corpus (all 200 inputs) and all 4
|
||||
`tests/fixtures/*.sv` through 3 passes independently of `cargo test`
|
||||
(`regress3.py`): **zero regressions, zero drift, zero unexpected refusals.**
|
||||
This is the strongest evidence available that nothing which used to format
|
||||
correctly now breaks.
|
||||
|
||||
**Findings**
|
||||
|
||||
*Should-fix*
|
||||
|
||||
None. No blocking or correctness issue found in the diff itself.
|
||||
|
||||
*Nit / informational*
|
||||
|
||||
1. **A comment in a ternary branch with no enclosing group still refuses
|
||||
cleanly** (exit 2, file untouched) — verified with
|
||||
`assign w = cond ? a : // c\n b;` → `verification failed: token stream
|
||||
diverges at index 10: ...`. This is *not* a broken claim (ternary
|
||||
branches were never listed among the covered constructs — Handshakes
|
||||
names only concat/call-args/`inside`/assignment-pattern/paren/binary),
|
||||
and it is not a regression (ternary carries no comment field before or
|
||||
after this diff). It is simply a fourth refusal location beyond the
|
||||
three the README's "Not fixed" list names. Worth a one-line addition to
|
||||
that list for completeness next time someone touches this area, but not
|
||||
blocking — filed here rather than fixed, since expanding comment support
|
||||
to ternaries is a design decision (does the ternary need to hug like
|
||||
`assign_rhs` does?), not a small unambiguous fix.
|
||||
2. **Pre-existing lexer limitation, not caused by this diff**: `@(* )` —
|
||||
parens with a bare space between `*` and `)`, *no comment involved* —
|
||||
fails to lex at all (`lex error: unterminated attribute (* ... *)`),
|
||||
because `(*` immediately followed by anything other than `)` is always
|
||||
treated as the start of an attribute instance
|
||||
(`vlog_parser/src/lexer.rs:223`, `peek_at(2) != b')'`), and that line is
|
||||
untouched by this diff (confirmed via `git diff` showing no hunk
|
||||
touching it). So legal input with incidental whitespace inside `@( * )`
|
||||
was already unparseable before this change and still is. Flagging
|
||||
because this feature's Assumptions specifically discuss this exact `(*`
|
||||
ambiguity for the *output* spelling of `after`-comments, so it's a
|
||||
natural thing for whoever reads that section next to wonder about; it's
|
||||
out of scope for a bug-fix feature that (correctly) didn't touch
|
||||
`lexer.rs`'s core tokenizing logic.
|
||||
3. **Style observation, not a bug**: a comment on its own source line
|
||||
immediately before a closing construct — the closing `)` of a `Paren`,
|
||||
or before a binary operator — gets glued onto the end of the preceding
|
||||
line in the output rather than kept on its own line. Example: input
|
||||
```
|
||||
assign s = (
|
||||
// paren leading comment
|
||||
a + b
|
||||
// paren trailing comment
|
||||
);
|
||||
```
|
||||
formats to `a + b // paren trailing comment` on one line. This is
|
||||
deliberate and consistent — it's the exact same mechanism the committed
|
||||
`comments.cases` case "comment before the operator of a long operator
|
||||
chain" already pins down (`first // wait for the second one too` ⏎
|
||||
` && second;`), and it mirrors `SensList::Star`'s `after` handling. Not
|
||||
a correctness issue (order and content both preserved, 3-pass stable),
|
||||
just a readability wrinkle worth knowing about if a future case author
|
||||
is surprised by it.
|
||||
|
||||
**Overall verdict**: all 7 claims **PASS**. No regression found anywhere in
|
||||
204 pre-existing inputs re-run through 3 passes, nor in 15 hand-built
|
||||
adversarial stress files targeting the specific corners the assignment
|
||||
named (ragged/tab/column-0 comments, every expression-comment position,
|
||||
every closing-label kind including nested and trailing-comment-after-label,
|
||||
the exact 100/101-column multi-instance boundary, and mixed sensitivity-list
|
||||
spellings). The three documented remaining refusals all still refuse
|
||||
cleanly with an accurate error and leave the file byte-identical. CLAUDE.md
|
||||
compliance (no unwrap/expect/panic in library paths, no new deps, no
|
||||
un-explained `#[allow]`, TODO.md/README.md/`vfmt` untouched) all confirmed
|
||||
by direct inspection, not just by trusting the work log's claims.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-19 — lead. Verdict: accepted and committed as-is; no lead fixes
|
||||
needed.**
|
||||
|
||||
The strongest round so far. All five briefed bugs fixed with the parked
|
||||
expected outputs hit verbatim, a sixth (directive/attribute drift) found
|
||||
and fixed with the same root-cause discipline, and — the part I care most
|
||||
about — verify.rs untouched except for diagnostic positions. The safety
|
||||
net was never weakened to make a fix pass, and QA independently confirmed
|
||||
that with a diff audit. The dedent-by-`col-1` design for comment
|
||||
re-indentation is the faithful fix the safety-net work log asked for, and
|
||||
preserving *relative* raggedness inside comments (rather than
|
||||
normalizing it away) is the right reading of "comments are never
|
||||
dropped": we don't own the inside of a comment.
|
||||
|
||||
Also noteworthy: triple-pass stability over all 204 inputs, the
|
||||
100/101-column boundary probes, and honest documentation of the three
|
||||
remaining comment-placement refusals instead of hacks. Clearing the four
|
||||
pre-existing clippy warnings in files already being touched was within
|
||||
the letter of the brief and leaves clippy fully silent — worth keeping
|
||||
that way.
|
||||
|
||||
Dispositions on QA findings (all nit-level):
|
||||
|
||||
- **Ternary-branch comment refusal** (a 4th refusal location): added to
|
||||
this README's open items alongside the documented three. All four are
|
||||
refusals, not corruption — safe to leave until a comments-in-
|
||||
expressions round.
|
||||
- **`@(* )` fails to lex** (bare space before `)`; `(*` greedily starts
|
||||
an attribute): pre-existing lexer limitation, now recorded in TODO.md.
|
||||
- **Comment glued before a closing `)` / binary operator**: consistent
|
||||
with committed cases; goes on the style-rulings list from the
|
||||
case-tables review.
|
||||
Reference in new issue
Block a user