Add safety-net: runtime equivalence + convergence verification
format_source now verifies every result before returning it, per Verible's practice: the output must re-lex to the same token stream as the input (comments included, whitespace ignored) and formatting it a second time must be a fixed point. Any failure returns FormatError::Verification and the caller keeps the original text — "never corrupt code" and idempotency are now runtime guarantees. Normalizations (documented in the feature README): multi-line comments/directives/attributes compare line-trimmed since the formatter re-indents them; @(*)/@* is a whitelisted canonicalization. The net already catches three real pre-existing bugs (closing-label drop, block-comment re-indent drift, sens-list comment drop), which now refuse output with exit 2 instead of corrupting files. Fixes queued as the next feature. Checks off TODO.md §1 items 1-3. Dev: Opus agent; QA: Sonnet agent (17 adversarial pairs, all caught); review in docs/features/safety-net/README.md. Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
6b95d772f1
commit
8effef9b6b
7 files changed
+913
-9
No files matched your search
@@ -11,7 +11,7 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
|
||||
|
||||
## 1. Correctness safety net (highest priority)
|
||||
|
||||
- [ ] **[V] Token-stream equivalence verification.** Verible's formatter
|
||||
- [x] **[V] Token-stream equivalence verification.** Verible's formatter
|
||||
re-lexes its output and asserts it is lexically equivalent to the input
|
||||
(`verilog_equivalence.cc`); on mismatch it emits the *original* text.
|
||||
Add `verify_equivalence(input, output)` to `vlog_formatter`: re-lex both
|
||||
@@ -19,11 +19,11 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
|
||||
excluded, comments included). Run it inside `format_source()` on every
|
||||
call — not just in tests. This turns "the formatter can never corrupt
|
||||
code" from a test-suite property into a runtime guarantee.
|
||||
- [ ] **[V] Convergence (idempotency) verification at runtime.** Verible
|
||||
- [x] **[V] Convergence (idempotency) verification at runtime.** Verible
|
||||
formats twice and checks a fixed point before writing. Do the same in
|
||||
`format_source()` (optionally behind `--no-verify` for speed later).
|
||||
Today idempotency is only asserted in `tests/fixtures.rs`.
|
||||
- [ ] **[V] Failsafe fallback semantics.** On any internal verification
|
||||
- [x] **[V] Failsafe fallback semantics.** On any internal verification
|
||||
failure, return the input unchanged *with a diagnostic and nonzero exit*,
|
||||
never partially formatted output. Parse errors already behave this way
|
||||
(README notes it); extend the same contract to the two checks above.
|
||||
@@ -119,7 +119,7 @@ Verible's formatter confidence comes from a few complementary layers
|
||||
(`formatter_test.cc`, component tests, equivalence/convergence checks).
|
||||
Adapt each:
|
||||
|
||||
- [ ] **[V] Massive text-in/text-out table tests.** Verible's
|
||||
- [x] **[V] Massive text-in/text-out table tests.** Verible's
|
||||
`formatter_test.cc` is thousands of small `{input, expected}` pairs — the
|
||||
backbone of the formatter. `small_cases` in
|
||||
`crates/vlog_formatter/tests/fixtures.rs` is the seed; grow it into a
|
||||
|
||||
@@ -129,7 +129,7 @@ fn main() -> ExitCode {
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("error: <stdin>:{e}");
|
||||
eprintln!("error: <stdin>: {e}");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
}
|
||||
@@ -165,7 +165,7 @@ fn main() -> ExitCode {
|
||||
let out = match format_source(&src, &opts.config) {
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
eprintln!("error: {}:{e}", file.display());
|
||||
eprintln!("error: {}: {e}", file.display());
|
||||
errors += 1;
|
||||
continue;
|
||||
}
|
||||
@@ -197,7 +197,9 @@ fn main() -> ExitCode {
|
||||
summary.push(format!("{unchanged} file{} left unchanged", plural(unchanged)));
|
||||
}
|
||||
if errors > 0 {
|
||||
summary.push(format!("{errors} file{} failed to parse", plural(errors)));
|
||||
// Parse errors, I/O errors and failed safety checks all land
|
||||
// here; in every case the file was left untouched.
|
||||
summary.push(format!("{errors} file{} failed to format", plural(errors)));
|
||||
}
|
||||
if !summary.is_empty() {
|
||||
eprintln!("{}", summary.join(", "));
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
use crate::doc::*;
|
||||
use crate::printer::Printer;
|
||||
use crate::verify::{verify_convergence, verify_equivalence, VerificationError};
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::token::Comment;
|
||||
|
||||
@@ -21,7 +22,53 @@ impl Default for Config {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn format_source(source: &str, config: &Config) -> Result<String, vlog_parser::Error> {
|
||||
/// Everything that can stop the formatter from producing output.
|
||||
#[derive(Debug)]
|
||||
pub enum FormatError {
|
||||
/// The input could not be lexed or parsed.
|
||||
Source(vlog_parser::Error),
|
||||
/// A safety check failed; the formatted text was discarded.
|
||||
Verification(VerificationError),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for FormatError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
FormatError::Source(e) => write!(f, "{e}"),
|
||||
FormatError::Verification(e) => write!(f, "{e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for FormatError {}
|
||||
|
||||
impl From<vlog_parser::Error> for FormatError {
|
||||
fn from(e: vlog_parser::Error) -> Self {
|
||||
FormatError::Source(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<VerificationError> for FormatError {
|
||||
fn from(e: VerificationError) -> Self {
|
||||
FormatError::Verification(e)
|
||||
}
|
||||
}
|
||||
|
||||
/// Format `source`, verifying the result before handing it back.
|
||||
///
|
||||
/// The output is only returned if it re-lexes to the same token stream as the
|
||||
/// input (comments included) and formatting it again is a fixed point;
|
||||
/// otherwise the caller gets an error and must leave the original text alone.
|
||||
pub fn format_source(source: &str, config: &Config) -> Result<String, FormatError> {
|
||||
let output = format_once(source, config).map_err(FormatError::Source)?;
|
||||
verify_equivalence(source, &output)?;
|
||||
let again = format_once(&output, config).map_err(VerificationError::Reparse)?;
|
||||
verify_convergence(&output, &again)?;
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// A single unverified formatting pass: parse, lay out, print.
|
||||
fn format_once(source: &str, config: &Config) -> Result<String, vlog_parser::Error> {
|
||||
let file = vlog_parser::parse_source(source)?;
|
||||
let fmt = Fmt { _cfg: config };
|
||||
let doc = fmt.file(&file);
|
||||
|
||||
@@ -3,5 +3,7 @@
|
||||
pub mod doc;
|
||||
pub mod format;
|
||||
pub mod printer;
|
||||
pub mod verify;
|
||||
|
||||
pub use format::{format_source, Config};
|
||||
pub use format::{format_source, Config, FormatError};
|
||||
pub use verify::{verify_convergence, verify_equivalence, VerificationError};
|
||||
@@ -0,0 +1,262 @@
|
||||
//! 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 of the token (of the owning token, for comments).
|
||||
pub line: u32,
|
||||
/// 1-based column of the token (of the owning token, for comments).
|
||||
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, token.line, token.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, token.line, token.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(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
//! Tests for the runtime safety net: token-stream equivalence, convergence,
|
||||
//! and the failsafe behavior of `format_source`.
|
||||
|
||||
use vlog_formatter::{
|
||||
format_source, verify_convergence, verify_equivalence, Config, FormatError, VerificationError,
|
||||
};
|
||||
|
||||
fn expect_divergence(input: &str, output: &str) -> VerificationError {
|
||||
match verify_equivalence(input, output) {
|
||||
Ok(()) => panic!("expected a divergence between\n{input}\n---\n{output}"),
|
||||
Err(e) => e,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identical_streams_are_equivalent() {
|
||||
let src = "module m;\n assign x = a & b;\nendmodule\n";
|
||||
verify_equivalence(src, src).expect("a text is equivalent to itself");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whitespace_only_differences_are_equivalent() {
|
||||
let input = "module m(input a,output b);assign b=~a;endmodule";
|
||||
let output = "module m (input a, output b);\n assign b = ~a;\nendmodule\n";
|
||||
verify_equivalence(input, output).expect("whitespace is not part of the token stream");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_are_part_of_the_stream_but_may_be_reindented() {
|
||||
let input = "module m;\n// note\nwire x;/* block */\nendmodule\n";
|
||||
let output = "module m;\n // note\n wire x; /* block */\nendmodule\n";
|
||||
verify_equivalence(input, output).expect("comment text survived");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiline_block_comment_may_be_reindented() {
|
||||
let input = "module m;\n/* one\n two\n three */\nwire x;\nendmodule\n";
|
||||
let output = "module m;\n /* one\n two\n three */\n wire x;\nendmodule\n";
|
||||
verify_equivalence(input, output).expect("only per-line indentation changed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn differing_token_is_rejected() {
|
||||
let err = expect_divergence("assign x = a;\n", "assign x = b;\n");
|
||||
match err {
|
||||
VerificationError::Divergence { index, ref expected, ref got } => {
|
||||
assert_eq!(index, 3);
|
||||
assert_eq!(expected.as_ref().expect("expected item").text, "a");
|
||||
assert_eq!(got.as_ref().expect("got item").text, "b");
|
||||
}
|
||||
other => panic!("wrong error: {other}"),
|
||||
}
|
||||
let rendered = err.to_string();
|
||||
assert!(rendered.contains("index 3"), "{rendered}");
|
||||
assert!(rendered.contains('a') && rendered.contains('b'), "{rendered}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropped_comment_is_rejected() {
|
||||
let input = "module m;\n // keep me\n wire x;\nendmodule\n";
|
||||
let output = "module m;\n wire x;\nendmodule\n";
|
||||
match expect_divergence(input, output) {
|
||||
VerificationError::Divergence { expected, got, .. } => {
|
||||
let expected = expected.expect("expected item");
|
||||
assert_eq!(expected.text, "// keep me");
|
||||
assert_eq!(got.expect("got item").text, "wire");
|
||||
}
|
||||
other => panic!("wrong error: {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropped_trailing_comment_is_rejected() {
|
||||
let input = "module m;\n wire x; // trailing\nendmodule\n";
|
||||
let output = "module m;\n wire x;\nendmodule\n";
|
||||
assert!(matches!(expect_divergence(input, output), VerificationError::Divergence { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comment_at_end_of_file_is_rejected_if_dropped() {
|
||||
let input = "module m;\nendmodule\n// last word\n";
|
||||
let output = "module m;\nendmodule\n";
|
||||
assert!(matches!(expect_divergence(input, output), VerificationError::Divergence { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_output_is_rejected() {
|
||||
let input = "module m;\n wire x;\nendmodule\n";
|
||||
let output = "module m;\n wire x;\n";
|
||||
match expect_divergence(input, output) {
|
||||
VerificationError::Divergence { expected, got, .. } => {
|
||||
assert_eq!(expected.expect("expected item").text, "endmodule");
|
||||
assert!(got.is_none());
|
||||
}
|
||||
other => panic!("wrong error: {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extra_token_in_output_is_rejected() {
|
||||
let input = "module m;\nendmodule\n";
|
||||
let output = "module m;\nendmodule\nmodule n;\nendmodule\n";
|
||||
match expect_divergence(input, output) {
|
||||
VerificationError::Divergence { expected, got, .. } => {
|
||||
assert!(expected.is_none());
|
||||
assert_eq!(got.expect("got item").text, "module");
|
||||
}
|
||||
other => panic!("wrong error: {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_text_different_kind_is_rejected() {
|
||||
// `x` as an identifier vs. `"x"` as a string literal.
|
||||
assert!(matches!(
|
||||
expect_divergence("assign a = x;\n", "assign a = \"x\";\n"),
|
||||
VerificationError::Divergence { .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unlexable_output_is_reported() {
|
||||
match verify_equivalence("module m;\nendmodule\n", "module m;\n\"unterminated\n") {
|
||||
Err(VerificationError::Lex { side, .. }) => {
|
||||
assert_eq!(side.to_string(), "output");
|
||||
}
|
||||
other => panic!("expected a lex error, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn implicit_sensitivity_spellings_are_equivalent() {
|
||||
let input = "module m;\n always @* y = a;\nendmodule\n";
|
||||
let output = "module m;\n always @(*) y = a;\nendmodule\n";
|
||||
verify_equivalence(input, output).expect("`@*` and `@(*)` are the same construct");
|
||||
verify_equivalence(output, input).expect("the canonicalization is symmetric");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convergence_accepts_a_fixed_point() {
|
||||
verify_convergence("module m;\nendmodule\n", "module m;\nendmodule\n").expect("fixed point");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convergence_reports_the_first_differing_line() {
|
||||
match verify_convergence(
|
||||
"module m;\n wire x;\nendmodule\n",
|
||||
"module m;\n wire x;\nendmodule\n",
|
||||
) {
|
||||
Err(VerificationError::NotConverged { line, first, second }) => {
|
||||
assert_eq!(line, 2);
|
||||
assert_eq!(first, " wire x;");
|
||||
assert_eq!(second, " wire x;");
|
||||
}
|
||||
other => panic!("expected a convergence failure, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convergence_reports_a_truncated_second_pass() {
|
||||
match verify_convergence("module m;\nendmodule\n", "module m;\n") {
|
||||
Err(VerificationError::NotConverged { line, second, .. }) => {
|
||||
assert_eq!(line, 2);
|
||||
assert_eq!(second, "<end of file>");
|
||||
}
|
||||
other => panic!("expected a convergence failure, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_source_runs_both_checks_and_succeeds_on_real_input() {
|
||||
let src = "// header\n\
|
||||
module m #(parameter W = 8) (input clk, output reg [W-1:0] q);\n\
|
||||
always @(posedge clk) q <= q + 1; // count\n\
|
||||
endmodule\n";
|
||||
let out = format_source(src, &Config::default()).expect("formats cleanly");
|
||||
verify_equivalence(src, &out).expect("equivalent");
|
||||
verify_convergence(&out, &format_source(&out, &Config::default()).expect("second pass"))
|
||||
.expect("converged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_source_reports_source_errors_as_source_errors() {
|
||||
match format_source("module m;\n", &Config::default()) {
|
||||
Err(FormatError::Source(_)) => {}
|
||||
other => panic!("expected a parse error, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_source_would_reject_a_non_equivalent_output() {
|
||||
// The real formatter is expected never to produce such output, so the
|
||||
// failsafe path is exercised through the checker with a crafted pair:
|
||||
// this is exactly the call `format_source` makes before returning.
|
||||
let src = "module m;\n wire x; // dropped by a hypothetical bug\nendmodule\n";
|
||||
let bad_output = "module m;\n wire x;\nendmodule\n";
|
||||
let err = FormatError::Verification(expect_divergence(src, bad_output));
|
||||
assert!(err.to_string().starts_with("verification failed:"), "{err}");
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
# safety-net
|
||||
|
||||
## Goal
|
||||
|
||||
Make "vfmt can never corrupt code" a *runtime* guarantee instead of a
|
||||
test-suite property. Every call to `format_source()` re-lexes its own
|
||||
output and compares the token stream (comments included) against the
|
||||
input, then formats the output a second time and checks for a fixed
|
||||
point. If either check fails the formatted text is thrown away and an
|
||||
error is returned, so the CLI leaves the file untouched and exits 2.
|
||||
This is TODO.md §1's first three items, and mirrors what Verible does in
|
||||
`verilog_equivalence.cc` / its convergence loop.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Comment/attribute/directive re-indentation is not corruption.** The
|
||||
formatter re-indents the continuation lines of multi-line tokens
|
||||
(`format.rs::raw_text` emits each line after a `HardLine`, trimming
|
||||
its trailing whitespace, and the printer prepends the current indent).
|
||||
The checker therefore normalizes multi-line *comments*, *attributes*
|
||||
and *directives* by trimming each line at both ends before comparing.
|
||||
Single-line items and all other token kinds (identifiers, numbers,
|
||||
string literals, …) are compared byte-for-byte.
|
||||
- **Comment ordering is part of equivalence.** Comments are flattened
|
||||
into the stream in source order (leading comments, then the token,
|
||||
then its trailing comment). A comment that changes attachment from
|
||||
"trailing of token N" to "leading of token N+1" keeps its position in
|
||||
the flattened stream and is accepted; a comment that moves across a
|
||||
token is a divergence.
|
||||
- **The lexer normalizes some text identically on both sides.** Sized
|
||||
based literals lose internal whitespace (`8 'hFF` → `8'hFF`), line
|
||||
comments and directives are `trim_end`ed. Both input and output go
|
||||
through the same lexer, so this is neutral.
|
||||
- **Multiple comments trailing the same token are one item.** The lexer
|
||||
merges them into a single `trailing` string joined by a space; the
|
||||
comparison sees one merged comment on each side.
|
||||
- Comment items are reported with the line/col of the token they are
|
||||
attached to (the `Comment` struct carries no position of its own).
|
||||
- **`@*` and `@(*)` are the same construct.** The parser folds both into
|
||||
`SensList::Star` and the formatter always prints `@(*)`; that is a
|
||||
deliberate canonicalization, so both streams rewrite `@ ( * )` to
|
||||
`@ *` before comparing. `(*` followed by anything but `)` lexes as an
|
||||
attribute token, so the sequence has no other meaning.
|
||||
- Cost: verification makes `format_source` parse+print twice and lex
|
||||
three more times. Accepted for now; TODO.md already anticipates a
|
||||
`--no-verify` escape hatch if it ever matters.
|
||||
|
||||
## Consequence: known formatter bugs now refuse to produce output
|
||||
|
||||
The safety net does not fix formatting bugs, it *stops* them. Three
|
||||
already-known bugs (all marked `#SKIP` in `tests/cases/`) now make vfmt
|
||||
report an error and leave the file untouched instead of writing bad
|
||||
output:
|
||||
|
||||
- **Continuation lines of an indented multi-line block comment gain two
|
||||
spaces per pass** (`format.rs::raw_text` keeps a continuation line's
|
||||
original leading whitespace and the printer adds the current indent on
|
||||
top). Caught by the convergence check:
|
||||
`formatting is not idempotent; line 3 changed from " two */" to
|
||||
" two */"`. A faithful fix needs the comment's original column so
|
||||
`raw_text` can dedent before re-indenting — see Handshakes.
|
||||
- **A closing `end : label` is dropped.** Caught by the equivalence
|
||||
check: `token stream diverges at index 12: input has symbol ':' at
|
||||
4:7, output has keyword 'endmodule' at 5:1`. This one would have
|
||||
silently deleted source tokens.
|
||||
- Comments lifted out of a concatenation change position within the
|
||||
token stream and are caught the same way if they cross a token.
|
||||
|
||||
This is the intended contract (hard invariant 1: no partial output), but
|
||||
it is a visible behavior change: files that vfmt used to rewrite badly
|
||||
are now refused with exit code 2.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes** `vlog_parser::tokenize` (already re-exported from
|
||||
`vlog_parser/src/lib.rs`), `vlog_parser::LexError`,
|
||||
`vlog_parser::token::{Token, TokenKind, Comment}`. **No change to
|
||||
`vlog_parser` was needed.**
|
||||
- **Provides / changed contract:** `vlog_formatter::format_source` now
|
||||
returns `Result<String, FormatError>` instead of
|
||||
`Result<String, vlog_parser::Error>`. `FormatError` is
|
||||
`Source(vlog_parser::Error)` | `Verification(VerificationError)` and
|
||||
implements `Display` + `std::error::Error`, so every existing
|
||||
`{e}`-style error rendering keeps working. Callers that matched on
|
||||
`vlog_parser::Error` must now match `FormatError::Source`.
|
||||
- **Provides:** `vlog_formatter::verify::{verify_equivalence,
|
||||
verify_convergence, VerificationError, Item, ItemKind, Side}` for
|
||||
other features (the fixture harness in §5 of TODO.md can call
|
||||
`verify_equivalence` per case).
|
||||
- **Request to `vlog_parser` (not made, out of scope):**
|
||||
`token::Comment` (and the attribute/directive text kept in `Meta`)
|
||||
carries no source position, so `format.rs` cannot dedent a multi-line
|
||||
comment before re-indenting it. Recording the original column — or the
|
||||
byte span TODO.md §6 wants anyway — would let the comment-formatting
|
||||
bug above be fixed properly.
|
||||
- **`crates/vfmt/src/main.rs`** needed no structural change: it already
|
||||
treats a `format_source` error as "report, skip the file, exit 2".
|
||||
Two cosmetic edits only — a space after the filename in the error
|
||||
line, and the summary now says "failed to format" instead of "failed
|
||||
to parse", since a verification failure is not a parse failure.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `verify.rs` module: flatten source → (tokens + comments) stream.
|
||||
- [x] `verify_equivalence(input, output)` with a first-divergence
|
||||
description (index, kind, text, positions on both sides).
|
||||
- [x] `verify_convergence(first, second)` reporting the first differing
|
||||
line.
|
||||
- [x] Wire both into `format_source`; new `FormatError` type.
|
||||
- [x] Confirm the CLI still leaves files untouched and exits 2.
|
||||
- [x] Tests: `crates/vlog_formatter/tests/verification.rs`.
|
||||
- [x] `cargo clippy --all-targets` and `cargo test` clean (no new
|
||||
warnings; the pre-existing ones in `parser.rs`, `printer.rs` and
|
||||
`format.rs::ListItem` were left alone).
|
||||
- [x] Formatting: the repo has no `rustfmt.toml` and is *not* clean
|
||||
under default `cargo fmt` at baseline (hundreds of diffs in
|
||||
untouched files); it is hand-written in rustfmt's
|
||||
`use_small_heuristics = "Max"` style. New/edited code is clean
|
||||
under that style — `cargo fmt --check -- --config
|
||||
use_small_heuristics=Max` reports nothing in `verify.rs`,
|
||||
`lib.rs` or `tests/verification.rs`. Running a bare `cargo fmt`
|
||||
would have rewritten nine unrelated files, several of them owned
|
||||
by another agent, so it was not run. Adding a `rustfmt.toml` is a
|
||||
one-line call the lead should make.
|
||||
- [x] TODO.md §1 items 1–3 checked off (item 4, panic containment, is
|
||||
out of this feature's scope).
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-18 — dev agent
|
||||
|
||||
- Read CLAUDE.md / README.md / TODO.md §1, then the lexer, printer and
|
||||
`format_source` to find where output text can legitimately differ
|
||||
from input text.
|
||||
- Added `crates/vlog_formatter/src/verify.rs`. The comparison stream is
|
||||
built from `vlog_parser::tokenize`, which already attaches comments to
|
||||
tokens as leading/trailing trivia — flattening them back out in source
|
||||
order gives exactly Verible's "whitespace excluded, comments included"
|
||||
stream. The `Eof` token is skipped but its leading comments (comments
|
||||
at the end of a file) are kept.
|
||||
- Decided *against* comparing comment text byte-for-byte: the formatter
|
||||
legitimately re-indents continuation lines of block comments,
|
||||
attributes and `` `define`` continuations. Normalization is limited to
|
||||
those three item kinds and only trims per-line whitespace, so no
|
||||
comment content can be lost silently. Recorded under Assumptions.
|
||||
- `format_source` split into `format_once` (parse + print, the old body)
|
||||
and a verifying wrapper. Order: format once → equivalence → format
|
||||
again → convergence. A second pass that fails to *parse* is reported
|
||||
as `VerificationError::Reparse`, not as a source parse error, because
|
||||
the user's input did parse.
|
||||
- Error type change from `vlog_parser::Error` to `FormatError` is the
|
||||
one contract change; see Handshakes.
|
||||
- Two token-stream divergences showed up immediately in the concurrent
|
||||
`tests/cases/` suite: `always @*` formatted as `always @(*)`. The
|
||||
parser cannot tell the two spellings apart (`SensList::Star`), so the
|
||||
checker canonicalizes them on both sides rather than forcing a
|
||||
formatter change. Recorded under Assumptions.
|
||||
- Verified the failsafe end-to-end by building a *sabotaged* copy of the
|
||||
workspace in a scratch directory (`Fmt::trailing` stubbed out to drop
|
||||
trailing comments) and running the real CLI against it: it printed
|
||||
`error: drop.sv: verification failed: token stream diverges at index
|
||||
6: input has comment '// must survive' ...`, left the file byte-identical
|
||||
and exited 2. The repo tree was not modified for this experiment.
|
||||
- The checks immediately caught two pre-existing formatter bugs on real
|
||||
input (dropped `end : label`, non-convergent block-comment indent).
|
||||
Both are already tracked as `#SKIP` cases by the case-tables agent;
|
||||
see "Consequence" above. Not fixed here — the safety net's job is to
|
||||
detect, and both fixes belong to the formatting rules, one of them
|
||||
behind a `vlog_parser` change.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-18 — QA agent
|
||||
|
||||
**Scope**: verified claims 1–3 in the assignment (runs-on-every-call +
|
||||
fail-closed, documented normalizations, the two claimed bug-catches),
|
||||
tried to break `verify_equivalence`'s normalization logic with crafted
|
||||
(input, output) pairs, checked CLAUDE.md compliance, and ran the full
|
||||
tool chain. No blocking issues found; one third latent bug (beyond the
|
||||
two documented ones) confirmed caught end-to-end; one small doc-comment
|
||||
gap fixed directly.
|
||||
|
||||
**Tool chain** (workspace root, `cargo build` first):
|
||||
- `cargo test` (workspace): **39/39 pass** — 3 `vlog_formatter` unit
|
||||
tests, 1 `tests/cases.rs`, 2 `tests/fixtures.rs`, 19
|
||||
`tests/verification.rs`, 14 `vlog_parser` unit tests. 0 failed.
|
||||
- `cargo clippy --all-targets --workspace`: **0 errors.** Only
|
||||
pre-existing warnings, none in `verify.rs`: an `if_same_then_else` x2
|
||||
and a `manual_repeat_n` in `vlog_parser`/`vlog_formatter`, plus a
|
||||
`dead_code` warning on `ListItem.blank_before` in `format.rs`. None of
|
||||
these are in the safety-net diff.
|
||||
- `cargo fmt --check -- --config use_small_heuristics=Max`: reports
|
||||
diffs in `main.rs`, `format.rs`, `printer.rs`, `ast.rs`, `lexer.rs`,
|
||||
`parser.rs`, `tests/cases.rs`, `tests/fixtures.rs` — all pre-existing
|
||||
and outside this feature (confirmed the specific edited lines in
|
||||
`main.rs`, e.g. `error: {}: {e}` at line 168 and the `"failed to
|
||||
format"` summary at line 202, are not among the reported diffs).
|
||||
`verify.rs`, `lib.rs`, `tests/verification.rs`: **0 diffs**, both
|
||||
before and after the fix below. Matches the README's claim exactly.
|
||||
Ran in check mode only, as instructed.
|
||||
|
||||
**Claim 1 (runs on every call, fail-closed, exit 2, file untouched)** —
|
||||
**PASS**. Read `format_source` (`crates/vlog_formatter/src/format.rs:62-68`):
|
||||
unconditionally calls `verify_equivalence` then `verify_convergence`
|
||||
after every `format_once`; both are `?`-propagated, no bypass path, no
|
||||
config flag to skip it. `crates/vfmt/src/main.rs:165-187`: `fs::write`
|
||||
is only reached after a successful `format_source`, so any
|
||||
`FormatError` (source or verification) leaves the file alone; error
|
||||
path increments `errors` and hits `ExitCode::from(2)` at line 210.
|
||||
Confirmed live with the real CLI (`target/debug/vfmt`, built from this
|
||||
tree) — see the two bug repros below, both exit 2 with byte-identical
|
||||
files (`cmp` confirms).
|
||||
|
||||
**Claim 2 (documented normalizations)** — **PASS**, verified two ways:
|
||||
1. Read `verify.rs` line-by-line. `normalize()` (line 222) only trims
|
||||
multi-line `Directive`/`Attribute` text; `comment_item()` (line 216)
|
||||
always runs comments through `trim_lines`; every other `TokenKind`
|
||||
(Ident, Number, String, Symbol, SystemIdent, Keyword) is byte-for-byte.
|
||||
`collapse_implicit_sensitivity` (line 198) matches the documented
|
||||
`@ ( * )` → `@ *` rewrite exactly, applied symmetrically to both
|
||||
streams. Comment position is reported as the owning token's
|
||||
line/col (`comment_item`, line 216-218) — matches the Assumptions.
|
||||
2. Empirically: built a standalone scratch crate
|
||||
(`/private/tmp/.../scratchpad/adversarial`, path-dependency on this
|
||||
workspace's `vlog_formatter`/`vlog_parser`, no repo files touched)
|
||||
and ran 17 crafted (input, output) pairs directly through
|
||||
`vlog_formatter::verify::verify_equivalence`, specifically targeting
|
||||
the questions in the assignment:
|
||||
- deleted blank line inside a multi-line comment — **caught**
|
||||
(line count changes, so the trimmed-and-joined comparison string
|
||||
differs)
|
||||
- deleted non-blank continuation line — **caught**, same reason
|
||||
- reordered continuation lines with distinct content — **caught**
|
||||
(order is baked into the joined string)
|
||||
- content reflowed across a line boundary (word moved from end of
|
||||
line 1 to start of line 2, line count preserved) — **caught**
|
||||
(trim only touches leading/trailing whitespace per line, not
|
||||
content, so the joined strings differ)
|
||||
- `` `define`` with `\` continuation, one continuation line dropped
|
||||
— **caught** (`Directive` normalization is the same trim-and-join,
|
||||
same argument as above)
|
||||
- one of two same-token merged trailing comments dropped — **caught**
|
||||
(the merged/joined text literally differs)
|
||||
- a comment skipping over an intervening token (trailing of N →
|
||||
trailing of N+2, not just the adjacent leading-of-N+1 slot the
|
||||
Assumptions call out as accepted) — **caught**, diverges at the
|
||||
token that should have been there instead
|
||||
- multi-line attribute `(* ... *)` with a continuation line dropped
|
||||
— **caught**, same mechanism as directives
|
||||
- number literal case change (`8'hff` → `8'hFF`) — **caught**
|
||||
(`Number` is not in the `normalize` allowlist, byte-for-byte)
|
||||
- a pathological "deletion masked by a duplicate suffix" case
|
||||
(`wire a; wire b; wire a; wire b;` → `wire a; wire b;`) — **caught**
|
||||
(the index-lockstep comparison isn't a real diff/LCS, so in
|
||||
principle a deletion could hide behind a coincidentally-matching
|
||||
duplicate; empirically even this adversarial case still diverges,
|
||||
just later in the stream, because the tail lengths differ) — worth
|
||||
recording as a *theoretical* limitation even though it isn't
|
||||
practically exploitable in real Verilog (see Findings)
|
||||
- CRLF line endings inside a multi-line comment, legitimate reindent
|
||||
only — **accepted** (no false positive; `str::lines()` handles
|
||||
`\r\n` correctly)
|
||||
- two block comments on the same physical source line, reprinted by
|
||||
the formatter on separate lines — **accepted** (no false positive)
|
||||
All 17 behaved as expected: no hole found, no false positive found.
|
||||
Full harness left at
|
||||
`/private/tmp/claude-501/.../scratchpad/adversarial/src/main.rs` for
|
||||
reference (outside the repo, per instructions; not part of this
|
||||
change).
|
||||
|
||||
**Claim 3 (catches the two pre-existing bugs)** — **PASS**, confirmed
|
||||
end-to-end with the real CLI, not just unit tests:
|
||||
- `end : label` drop: `module m; initial begin : blk x = 1; end : blk
|
||||
endmodule` → `vfmt` prints `verification failed: token stream
|
||||
diverges at index 12: input has symbol ':' at 4:7, output has keyword
|
||||
'endmodule' at 5:1`, exit code 2, `cmp` confirms the file is
|
||||
byte-identical to the original afterward.
|
||||
- Block comment reindent non-convergence: a 3-line indented `/* one /
|
||||
two / three */` comment → `vfmt` prints `verification failed:
|
||||
formatting is not idempotent; line 3 changed from " two" to
|
||||
" two"`, exit code 2, file byte-identical afterward.
|
||||
|
||||
**Finding (should-fix, informational): a third latent bug the safety
|
||||
net also catches.** `always @( /* comment */ * ) ...` — a comment
|
||||
between the `(` and the `*` of an explicit-parens implicit-sensitivity
|
||||
list — makes the real formatter drop the comment. Root cause:
|
||||
`vlog_parser::parser::parse_sens_list`
|
||||
(`crates/vlog_parser/src/parser.rs:1546-1558`) calls `eat_sym("*")` /
|
||||
`expect_sym(")")` directly when building `SensList::Star`, which
|
||||
discards whatever leading comments were attached to those tokens (the
|
||||
AST variant carries no comment field), and
|
||||
`crates/vlog_formatter/src/format.rs:1111` always prints `SensList::Star`
|
||||
as the canonical `@(*)`. Reproduced live: `target/debug/vfmt` on a file
|
||||
containing `always @( /* comment inside sensitivity list */ * ) y = a;`
|
||||
exits 2 with `token stream diverges at index 5: input has symbol '(' at
|
||||
2:11, output has symbol '*' at 2:12`, file left untouched. This is not
|
||||
a verify.rs bug — the safety net is doing exactly its job here, the
|
||||
same as the two documented cases — but it's a real, previously
|
||||
unrecorded gap in `parse_sens_list`/`SensList::Star`, worth a line in
|
||||
the "Consequence" section or a TODO.md entry for whoever picks up
|
||||
comment-preservation in sensitivity lists. Not fixed here (parser
|
||||
change, out of this feature's scope).
|
||||
|
||||
**CLAUDE.md compliance**:
|
||||
- No `unwrap()`/`expect()`/`panic!` in `verify.rs` (only two
|
||||
`unwrap_or` calls in `first_line_difference`, which are non-panicking
|
||||
combinators, not the banned forms) or in `lib.rs`. `format.rs` has
|
||||
two pre-existing bare `.unwrap()` calls (lines 545, 728,
|
||||
`items.into_iter().next().unwrap()`, both immediately guarded by
|
||||
`if items.len() == 1`) — these predate this feature (unrelated
|
||||
`declarators`/`cont_assign` code, not part of the verify/FormatError
|
||||
diff) and are out of this feature's stated scope, so left as a
|
||||
finding rather than fixed.
|
||||
- Public items documented: all of `verify.rs`'s public items had doc
|
||||
comments except one field — **fixed directly** (small, unambiguous,
|
||||
per the QA-agent allowance): `Item.kind` (`crates/vlog_formatter/src/verify.rs`,
|
||||
now line 69-70) was missing a doc comment while its sibling fields
|
||||
`text`/`line`/`col` had one; added `/// Whether this entry is a real
|
||||
token or a comment recovered from trivia.`. Re-ran `cargo fmt --check`
|
||||
and `cargo test -p vlog_formatter --test verification` after the
|
||||
change: still 0 diffs, still 19/19 passing.
|
||||
- No new dependencies: confirmed by reading all three `Cargo.toml`
|
||||
files (`vlog_parser`, `vlog_formatter`, `vfmt`) — `vlog_parser` has
|
||||
zero dependencies, `vlog_formatter` depends only on `vlog_parser` via
|
||||
a path dependency, `vfmt` depends only on both via path. Matches the
|
||||
"no new deps" implicit claim.
|
||||
- README sections: all six required sections present (Goal,
|
||||
Assumptions, Handshakes, Status/TODO, Work log, QA log); Assumptions
|
||||
and Handshakes checked line-by-line against the code as part of Claim
|
||||
2 above and found accurate, including the specific `(*` vs `@(*)`
|
||||
lexer-ambiguity aside (verified the `peek_at(2) != b')'` guard in
|
||||
`crates/vlog_parser/src/lexer.rs:223` really does make `@(*)` with no
|
||||
internal spaces fall through to four separate symbol tokens rather
|
||||
than being swallowed as an attribute).
|
||||
|
||||
**Performance** — sane, not pathological. `tests/fixtures/` is 4 files,
|
||||
215 lines total. 200 sequential `target/release/vfmt --check` process
|
||||
invocations over all 4 files completed in 0.71s wall time (~3.5ms per
|
||||
invocation, including process startup, parsing+printing+re-lexing the
|
||||
input twice and re-parsing+printing once more per file). No fixture
|
||||
triggered a verification failure (`cargo test`'s
|
||||
`fixtures_match_snapshots_and_are_idempotent` also confirms this — it
|
||||
now goes through the safety net on every run and stays green). Did not
|
||||
attempt to construct a pathologically large input; not needed to answer
|
||||
"is the ~3x parse cost sane" for files of the size this formatter
|
||||
targets.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-18 — lead. Verdict: accepted and committed as-is.**
|
||||
|
||||
This is the most important change the project will ever take: the two hard
|
||||
invariants are now runtime guarantees, not test-suite hopes. The
|
||||
implementation is admirably small (one module, a thin wrapper, no new
|
||||
dependencies), the failure messages carry enough position detail to debug
|
||||
from, and the sabotaged-formatter end-to-end proof in the work log is
|
||||
exactly the level of evidence I want for a claim like "fail-closed".
|
||||
|
||||
Points I reviewed specifically and accept:
|
||||
|
||||
1. **The normalizations are sound.** Line-by-line trimmed comparison of
|
||||
multi-line comments/directives/attributes cannot hide a deleted,
|
||||
reordered, or edited line (line count and content still compare); it
|
||||
only forgives re-indentation, which is the formatter's job. The
|
||||
`@ ( * )` → `@ *` collapse is a whitelisted canonicalization with no
|
||||
alternative lexical meaning. Both are documented as Assumptions.
|
||||
2. **Index-lockstep comparison instead of a real diff** (QA's theoretical
|
||||
finding): correct trade-off. A masked deletion needs a coincidentally
|
||||
matching suffix of equal length, which the differing tail length then
|
||||
catches; the simpler code wins per CLAUDE.md. Not worth an LCS.
|
||||
3. **The contract change** (`format_source` → `Result<String, FormatError>`)
|
||||
was propagated cleanly and the CLI's existing error path was reused
|
||||
rather than rebuilt — good restraint.
|
||||
4. QA's 17 adversarial pairs and the byte-identical `cmp` checks on the two
|
||||
bug repros are convincing; the one QA edit (a missing field doc) was
|
||||
appropriate under the small-fix rule.
|
||||
|
||||
Follow-ups spun out of this review (not blockers):
|
||||
|
||||
- The **third latent bug** QA found (`@( /* c */ * )` drops the comment in
|
||||
`parse_sens_list`, `parser.rs:1546-1558`) joins the four case-tables bugs
|
||||
in the bug-fix round. Note the safety net converts all five from silent
|
||||
corruption into refusals — working as designed.
|
||||
- The dev agent's handshake request stands: `token::Comment` needs a source
|
||||
position to fix the block-comment re-indent bug faithfully. That lands in
|
||||
the bug-fix feature's scope.
|
||||
- `--no-verify` (TODO §1 mentions it) stays unimplemented until someone
|
||||
demonstrates a real performance need; the double-format cost is
|
||||
negligible at current file sizes.
|
||||
- rustfmt.toml has since been added at the repo root (case-tables review),
|
||||
resolving this feature's fmt caveat; the repo-wide normalization commit
|
||||
follows this one.
|
||||
Reference in new issue
Block a user