Files
lucisv/crates/vlog_formatter/src/verify.rs
T
lucioandClaude Fable 5 9f1a6cf1d2 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]>
2026-08-19 00:15:50 -07:00

263 lines
9.8 KiB
Rust

//! Runtime safety net: token-stream equivalence and convergence checks.
//!
//! These are the two checks Verible runs before it writes a formatted file
//! (`verilog_equivalence.cc` plus its convergence loop), and they are what
//! turns "the formatter can never corrupt code" from a test-suite property
//! into a guarantee of every `format_source` call:
//!
//! * *equivalence* — re-lex input and output and compare the resulting
//! streams of tokens **and comments**, ignoring whitespace;
//! * *convergence* — formatting the output again must reproduce it exactly.
//!
//! Comments live in the token stream as leading/trailing trivia (see
//! `vlog_parser::lexer`), so the comparison stream simply flattens them back
//! out in source order. Multi-line comments, attributes and directives are
//! compared line-by-line with each line trimmed, because the formatter
//! re-indents their continuation lines; every other token is compared
//! byte-for-byte.
use std::fmt;
use vlog_parser::token::TokenKind;
use vlog_parser::{tokenize, LexError};
/// Which of the two texts a problem was found in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Side {
Input,
Output,
}
impl fmt::Display for Side {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Side::Input => write!(f, "input"),
Side::Output => write!(f, "output"),
}
}
}
/// What a stream entry is: a real token, or a comment recovered from trivia.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ItemKind {
Token(TokenKind),
Comment,
}
impl fmt::Display for ItemKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ItemKind::Comment => write!(f, "comment"),
ItemKind::Token(kind) => match kind {
TokenKind::Ident => write!(f, "identifier"),
TokenKind::SystemIdent => write!(f, "system identifier"),
TokenKind::Keyword => write!(f, "keyword"),
TokenKind::Number => write!(f, "number"),
TokenKind::String => write!(f, "string"),
TokenKind::Directive => write!(f, "directive"),
TokenKind::Attribute => write!(f, "attribute"),
TokenKind::Symbol => write!(f, "symbol"),
TokenKind::Eof => write!(f, "end of file"),
},
}
}
}
/// One entry of the whitespace-free comparison stream.
#[derive(Debug, Clone)]
pub struct Item {
/// Whether this entry is a real token or a comment recovered from trivia.
pub kind: ItemKind,
/// Token or comment text, normalized as described in the module docs.
pub text: String,
/// 1-based line the token or comment starts on.
pub line: u32,
/// 1-based column the token or comment starts on.
pub col: u32,
}
impl Item {
/// Equivalent for verification purposes: same kind and text. Positions
/// are reported in diagnostics but never compared.
fn matches(&self, other: &Item) -> bool {
self.kind == other.kind && self.text == other.text
}
}
impl fmt::Display for Item {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} `{}` at {}:{}", self.kind, self.text, self.line, self.col)
}
}
/// A failed safety check. The formatter discards its output when it sees one.
#[derive(Debug)]
pub enum VerificationError {
/// One of the two texts could not be lexed.
Lex { side: Side, error: LexError },
/// The formatter's own output no longer parses.
Reparse(vlog_parser::Error),
/// The two token streams differ at position `index`.
Divergence { index: usize, expected: Option<Item>, got: Option<Item> },
/// Formatting the output a second time changed it.
NotConverged { line: usize, first: String, second: String },
}
impl fmt::Display for VerificationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
VerificationError::Lex { side, error } => {
write!(f, "verification failed: cannot re-lex the {side}: {error}")
}
VerificationError::Reparse(error) => {
write!(f, "verification failed: the formatted output no longer parses: {error}")
}
VerificationError::Divergence { index, expected, got } => {
write!(f, "verification failed: token stream diverges at index {index}: ")?;
match (expected, got) {
(Some(expected), Some(got)) => {
write!(f, "input has {expected}, output has {got}")
}
(Some(expected), None) => {
write!(f, "output ended early, input still has {expected}")
}
(None, Some(got)) => write!(f, "output has an extra {got}"),
(None, None) => write!(f, "streams are equal (internal error)"),
}
}
VerificationError::NotConverged { line, first, second } => write!(
f,
"verification failed: formatting is not idempotent; \
line {line} changed from {first:?} to {second:?}"
),
}
}
}
impl std::error::Error for VerificationError {}
/// Verify that `output` is lexically equivalent to `input`: the same tokens
/// and the same comments, in the same order, ignoring whitespace.
pub fn verify_equivalence(input: &str, output: &str) -> Result<(), VerificationError> {
let before = lex_stream(input, Side::Input)?;
let after = lex_stream(output, Side::Output)?;
for index in 0..before.len().max(after.len()) {
let expected = before.get(index);
let got = after.get(index);
let equal = matches!((expected, got), (Some(a), Some(b)) if a.matches(b));
if !equal {
return Err(VerificationError::Divergence {
index,
expected: expected.cloned(),
got: got.cloned(),
});
}
}
Ok(())
}
/// Verify that a second formatting pass reached a fixed point.
pub fn verify_convergence(first: &str, second: &str) -> Result<(), VerificationError> {
if first == second {
return Ok(());
}
let (line, first, second) = first_line_difference(first, second);
Err(VerificationError::NotConverged { line, first, second })
}
/// Flatten `source` into tokens and comments, dropping all whitespace.
fn lex_stream(source: &str, side: Side) -> Result<Vec<Item>, VerificationError> {
let tokens = tokenize(source).map_err(|error| VerificationError::Lex { side, error })?;
let mut items = Vec::new();
for token in &tokens {
for comment in &token.leading {
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.
if token.kind != TokenKind::Eof {
items.push(Item {
kind: ItemKind::Token(token.kind),
text: normalize(token.kind, &token.text),
line: token.line,
col: token.col,
});
}
if let Some(trailing) = &token.trailing {
items.push(comment_item(&trailing.text, trailing.line, trailing.col));
}
}
collapse_implicit_sensitivity(&mut items);
Ok(items)
}
/// Rewrite `@ ( * )` to `@ *` so the two spellings of an implicit sensitivity
/// list compare equal. The parser folds both into `SensList::Star` and the
/// formatter always prints `@(*)`, which is a deliberate canonicalization, not
/// corruption. `(*` followed by anything other than `)` lexes as an attribute
/// token, so this sequence has no other meaning.
fn collapse_implicit_sensitivity(items: &mut Vec<Item>) {
let is_sym = |item: &Item, sym: &str| {
item.kind == ItemKind::Token(TokenKind::Symbol) && item.text == sym
};
let mut i = 0;
while i + 3 < items.len() {
if is_sym(&items[i], "@")
&& is_sym(&items[i + 1], "(")
&& is_sym(&items[i + 2], "*")
&& is_sym(&items[i + 3], ")")
{
items.remove(i + 3);
items.remove(i + 1);
}
i += 1;
}
}
fn comment_item(text: &str, line: u32, col: u32) -> Item {
Item { kind: ItemKind::Comment, text: trim_lines(text), line, col }
}
/// Token text as compared. Only the kinds the formatter re-indents are
/// normalized; everything else must survive byte-for-byte.
fn normalize(kind: TokenKind, text: &str) -> String {
match kind {
TokenKind::Directive | TokenKind::Attribute => trim_lines(text),
_ => text.to_string(),
}
}
/// Trim every line of a multi-line item. Re-indenting a block comment or a
/// continued `` `define`` changes the whitespace around its continuation
/// lines and nothing else, so that difference must not count as corruption.
fn trim_lines(text: &str) -> String {
if !text.contains('\n') {
return text.to_string();
}
text.lines().map(str::trim).collect::<Vec<_>>().join("\n")
}
/// 1-based number of the first differing line, with both versions of it.
fn first_line_difference(a: &str, b: &str) -> (usize, String, String) {
let mut a_lines = a.lines();
let mut b_lines = b.lines();
let mut line = 0usize;
loop {
line += 1;
let (a_line, b_line) = (a_lines.next(), b_lines.next());
if a_line == b_line {
if a_line.is_none() {
// Texts compared unequal, so this cannot be reached with
// both iterators exhausted — report something sane anyway.
return (line, String::new(), String::new());
}
continue;
}
return (
line,
a_line.unwrap_or("<end of file>").to_string(),
b_line.unwrap_or("<end of file>").to_string(),
);
}
}