Files
lucisv/crates/vlog_formatter/src/verify.rs
T

376 lines
15 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 {
// `{:?}` escapes embedded tabs/newlines (comment text can contain
// both), keeping every diagnostic a single physical line — CLI
// consumers treat one stderr line as one diagnostic.
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. An adjacent `(*` followed by anything but whitespace-then-`)`
/// lexes as an attribute token (lexer-cleanup's `starts_attribute` backoff),
/// so this token sequence still 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.
///
/// A macro usage lexes as an identifier whose text is the whole invocation,
/// argument list included, so a call spread over several lines is one token
/// with newlines in it — and the formatter re-indents its continuation lines
/// exactly like a continued `` `define ``. All three kinds can also carry a
/// *string literal* that spans a line break, whose leading whitespace is part
/// of its value, so they use the string-aware trim. Single-line tokens are
/// unaffected either way.
fn normalize(kind: TokenKind, text: &str) -> String {
match kind {
TokenKind::Directive | TokenKind::Attribute => trim_lines_outside_strings(text),
TokenKind::Ident if text.starts_with('`') => trim_lines_outside_strings(text),
_ => text.to_string(),
}
}
/// Trim every line of a multi-line item. Re-indenting a block comment changes
/// the whitespace around its continuation lines and nothing else, so that
/// difference must not count as corruption.
///
/// Used for comments only. A comment has no lexical structure inside it, so
/// every line boundary in one is pure layout — unlike the token kinds handled
/// by [`trim_lines_outside_strings`].
fn trim_lines(text: &str) -> String {
if !text.contains('\n') {
return text.to_string();
}
text.lines().map(str::trim).collect::<Vec<_>>().join("\n")
}
/// Trim every line of a multi-line token, *except* at line boundaries that
/// fall inside a string literal.
///
/// Whitespace next to a line break is normally pure layout, which is why
/// [`trim_lines`] can drop it. Inside a string literal it is not: it is part
/// of the value. A blind per-line trim there would let the formatter silently
/// re-indent the *contents of a string* and still pass this check — masked
/// corruption, and the reason this function exists (QA finding, 2026-08-19:
/// `` `uvm_info("id", "line one\n line two", UVM_LOW) `` had its string
/// rewritten with lucisv exiting 0). Leaving those lines untrimmed makes the
/// comparison byte-exact exactly where bytes are meaningful.
fn trim_lines_outside_strings(text: &str) -> String {
if !text.contains('\n') {
return text.to_string();
}
let inside = line_starts_inside_string(text);
let lines: Vec<&str> = text.split('\n').collect();
let mut out = Vec::with_capacity(lines.len());
for (i, line) in lines.iter().enumerate() {
// `inside[i]` is the state entering this line, `inside[i + 1]` the
// state entering the next one — i.e. whether the newline that ends
// this line sits inside a string.
let start_trimmed = if inside[i] { line } else { line.trim_start() };
out.push(if inside[i + 1] { start_trimmed } else { start_trimmed.trim_end() });
}
out.join("\n")
}
/// For each line of `text` split on `\n`, whether that line *begins* inside a
/// string literal. The returned vector has one more entry than there are
/// lines: the last is the state at the end of the text.
///
/// Mirrors the lexer's own reading of a macro argument list
/// (`vlog_parser::lexer::scan_macro_args`): a `"` opens a string unless it is
/// inside a comment, `\` escapes the next character, and `//` / `/* */`
/// comments are skipped so a quote written inside one cannot open a string.
/// Shared with the formatter so both sides agree on which line breaks are
/// layout and which are data.
pub(crate) fn line_starts_inside_string(text: &str) -> Vec<bool> {
#[derive(PartialEq, Eq, Clone, Copy)]
enum State {
Code,
Str,
LineComment,
BlockComment,
}
let bytes = text.as_bytes();
let mut state = State::Code;
let mut out = vec![false];
let mut i = 0usize;
while i < bytes.len() {
let c = bytes[i];
match state {
State::Code => match c {
b'"' => state = State::Str,
b'/' if bytes.get(i + 1) == Some(&b'/') => {
state = State::LineComment;
i += 1;
}
b'/' if bytes.get(i + 1) == Some(&b'*') => {
state = State::BlockComment;
i += 1;
}
_ => {}
},
State::Str => match c {
// An escape consumes the next byte, a line continuation
// inside a string included.
b'\\' => i += 1,
b'"' => state = State::Code,
_ => {}
},
State::LineComment => {
if c == b'\n' {
state = State::Code;
}
}
State::BlockComment => {
if c == b'*' && bytes.get(i + 1) == Some(&b'/') {
state = State::Code;
i += 1;
}
}
}
// Record the state entering the next line. The newline itself never
// changes it (the line-comment case above already closed).
if bytes.get(i) == Some(&b'\n') {
out.push(state == State::Str);
}
i += 1;
}
out.push(state == State::Str);
out
}
/// 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(),
);
}
}