Files
lucisv/crates/vlog_formatter/src/align.rs
T
lucioandClaude Fable 5 f1db1e5746 Add dv-statements: with clauses, foreach targets, randcase, let, labels
randomize()/std::randomize() with { ... } (block verbatim), array-method
with (expr), foreach over scoped/hierarchical/indexed arrays, randcase,
wait fork, import as a statement, let declarations, empty call arguments,
general statement labels, and endtask: name; (stray semicolon kept).
Also fixes a pre-existing verification failure for a comment between a
then-branch and its else.

Coverage loop round 1, cluster 8: 772 -> 796 / 820 (94.1% -> 97.1%).
Feature README: docs/features/dv-statements/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-21 01:19:49 -07:00

276 lines
11 KiB
Rust

//! Alignment inference: read the author's intent out of the original spacing
//! and decide, per group of similar lines, whether a construct is laid out
//! aligned (padded to a common column) or flush-left (one separator).
//!
//! This is Verible's most-loved formatter feature minus the configuration: a
//! group whose author padded any of its lines by four or more excess spaces —
//! or that already sits at one common column — keeps its columns; everything
//! else formats flush, which is what vfmt has always done. The two states are
//! fixed points of each other, which is what lets the convergence check in
//! `verify.rs` stay untouched; the argument is written out in
//! `docs/features/alignment/README.md`.
//!
//! Every decision here is made while the document is built, from facts that
//! depend only on the source text and the AST's nesting — never on anything
//! the printer discovers later. That is deliberate: a decision the printer
//! made would not be visible to the next formatting pass, and the two passes
//! would disagree.
use crate::doc::{concat, text, Doc};
/// Excess spaces before a column's token that read as "the author aligned
/// this". Verible's threshold, and the one number this module hard-codes.
const HINT_EXCESS: usize = 4;
/// The spacing of one alignment column.
#[derive(Debug, Clone, Copy)]
pub struct ColSpec {
/// Spaces the flush layout writes before the column's token. This is the
/// baseline excess is measured against: one space before a declaration's
/// name, none before a connection's `(`.
pub flush: usize,
/// Least the aligned layout writes before it, i.e. what the widest row of
/// the group gets. It only differs from `flush` where the flush spelling
/// is tight: `.clk(clk)` flush, `.clk (clk)` aligned.
pub min: usize,
}
/// One candidate row of an alignment group, already measured.
///
/// The row's document is a list of cells split at the alignment columns:
/// `cells[k + 1]` starts with the token that opens column `k`. Only the widths
/// are kept here — planning never looks at the documents themselves.
pub struct Row {
/// Flat width of each cell; always `columns + 1` entries.
pub widths: Vec<usize>,
/// Source byte offset of the token opening each column.
pub anchors: Vec<u32>,
/// Width printed after the last cell on the same line: the `,` a list
/// element takes, or the `;` a declaration ends with.
pub tail: usize,
}
/// Where an aligned group's columns land, measured from the first cell's own
/// column. Every row of the group shares one plan.
#[derive(Debug, Clone)]
pub struct Align {
targets: Vec<usize>,
}
/// Decide whether `rows` want alignment, and if so where their columns land.
///
/// `budget` is how many columns the rows have to play with: the line limit
/// less the indentation they will be printed at. A group whose widest aligned
/// line would not fit in it is laid out flush *as a whole* — never some rows
/// aligned and some not.
///
/// `None` means flush-left — today's layout — and is also the answer for
/// anything the rule is not sure about: a group of one, a group with nothing
/// to pad, a row whose column token starts its own line.
pub fn plan(src: &str, rows: &[&Row], specs: &[ColSpec], budget: usize) -> Option<Align> {
if rows.len() < 2 {
return None;
}
let cols = specs.len();
if rows.iter().any(|r| r.widths.len() != cols + 1 || r.anchors.len() != cols) {
return None;
}
// A row with an empty first cell has no prefix to pad against.
if rows.iter().any(|r| r.widths[0] == 0) {
return None;
}
// Nothing to align: every row's cells are the same width, so the aligned
// and the flush layouts are the same bytes. Answering "flush" is what
// keeps the two from taking turns — see the README's fixed-point
// argument.
if (0..cols).all(|k| rows.iter().all(|r| r.widths[k] == rows[0].widths[k])) {
return None;
}
if !wants_alignment(src, rows, specs) {
return None;
}
let mut targets = Vec::with_capacity(cols);
let mut offset = 0usize;
for (k, spec) in specs.iter().enumerate() {
offset += rows.iter().map(|r| r.widths[k]).max().unwrap_or(0) + spec.min;
targets.push(offset);
}
let extent = offset + rows.iter().map(|r| r.widths[cols] + r.tail).max().unwrap_or(0);
if extent > budget {
return None;
}
Some(Align { targets })
}
/// Does the original spacing ask for alignment? Either some row was padded by
/// [`HINT_EXCESS`] spaces past what the flush layout writes, or every column
/// already sits at one source column and at least one row was padded at all.
///
/// The second clause is what makes an aligned group stay aligned: the
/// formatter's own output has exactly that shape.
fn wants_alignment(src: &str, rows: &[&Row], specs: &[ColSpec]) -> bool {
let mut max_excess = 0usize;
let mut one_column = true;
for (k, spec) in specs.iter().enumerate() {
let mut first: Option<usize> = None;
for row in rows {
let offset = row.anchors[k] as usize;
let Some(gap) = gap_before(src, offset) else { return false };
max_excess = max_excess.max(gap.saturating_sub(spec.flush));
let column = column_of(src, offset);
match first {
None => first = Some(column),
Some(c) => one_column &= c == column,
}
}
}
max_excess >= HINT_EXCESS || (one_column && max_excess >= 1)
}
/// Join one row's cells: flush (a fixed separator per column) when `plan` is
/// `None`, padded out to the group's columns when it is not.
pub fn render(cells: &[Doc], specs: &[ColSpec], plan: Option<&Align>) -> Doc {
let plan = plan.filter(|p| p.targets.len() + 1 == cells.len());
let mut docs = Vec::with_capacity(cells.len() * 2);
let mut width = 0usize;
for (k, cell) in cells.iter().enumerate() {
if k > 0 {
let spec = specs.get(k - 1).copied().unwrap_or(ColSpec { flush: 1, min: 1 });
// `saturating_sub` and the `min` floor are belt and braces: a
// target is computed from these very widths, so it always leaves
// room. Two tokens must never end up glued together.
let pad = match plan {
Some(p) => p.targets[k - 1].saturating_sub(width).max(spec.min),
None => spec.flush,
};
docs.push(text(" ".repeat(pad)));
width += pad;
}
docs.push(cell.clone());
width += flat_width(cell).unwrap_or(0);
}
concat(docs)
}
/// Flat width of a document in characters, or `None` when it holds a forced
/// break — a comment inside a row makes that row unalignable rather than
/// guessing at a width it does not have.
pub fn flat_width(d: &Doc) -> Option<usize> {
match d {
Doc::Text(s) => Some(s.chars().count()),
Doc::Line => Some(1),
Doc::SoftLine | Doc::IfBreak(_) => Some(0),
Doc::Concat(items) | Doc::Indent(items) | Doc::Group(items) => {
items.iter().try_fold(0, |acc, d| Some(acc + flat_width(d)?))
}
// `Inline` carries its own line breaks, so a row holding one has no
// flat width either.
Doc::HardLine | Doc::BlankLine | Doc::Verbatim(_) | Doc::Inline(_) => None,
}
}
/// Horizontal whitespace written immediately before `offset`, or `None` when
/// the token starts its line — a row laid out that way says nothing about the
/// author's column intent, so its group formats flush.
fn gap_before(src: &str, offset: usize) -> Option<usize> {
let before = src.get(..offset)?;
let gap = before.len() - before.trim_end_matches([' ', '\t']).len();
match before[..before.len() - gap].chars().next_back() {
Some('\n') | None => None,
_ => Some(gap),
}
}
/// 1-based character column of `offset`.
fn column_of(src: &str, offset: usize) -> usize {
let before = src.get(..offset).unwrap_or("");
let line = match before.rfind('\n') {
Some(nl) => &before[nl + 1..],
None => before,
};
line.chars().count() + 1
}
#[cfg(test)]
mod tests {
use super::*;
fn row(widths: &[usize], anchors: &[u32], tail: usize) -> Row {
Row { widths: widths.to_vec(), anchors: anchors.to_vec(), tail }
}
const NAME: &[ColSpec] = &[ColSpec { flush: 1, min: 1 }];
const WIDE: usize = 100;
#[test]
fn gaps_and_columns() {
let src = "ab cd\nef";
assert_eq!(gap_before(src, 5), Some(3));
assert_eq!(column_of(src, 5), 6);
// `ef` starts its line.
assert_eq!(gap_before(src, 8), None);
assert_eq!(column_of(src, 8), 1);
}
#[test]
fn four_excess_spaces_align_a_group() {
// Five spaces where flush writes one: four excess, the threshold.
let src = "aa x\nbbbb y\n";
let rows = [row(&[2, 1], &[7], 0), row(&[4, 1], &[14], 0)];
let plan = plan(src, &[&rows[0], &rows[1]], NAME, WIDE).expect("aligned");
assert_eq!(plan.targets, vec![5]);
}
#[test]
fn three_excess_spaces_are_not_a_hint() {
let src = "aa x\nbbbb y\n";
let rows = [row(&[2, 1], &[6], 0), row(&[4, 1], &[13], 0)];
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE).is_none());
}
#[test]
fn single_spaces_stay_flush() {
let src = "aa x\nbbbb y\n";
let rows = [row(&[2, 1], &[3], 0), row(&[4, 1], &[10], 0)];
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE).is_none());
}
#[test]
fn one_common_column_stays_aligned() {
let src = "aa x\nbbbb x\n";
let rows = [row(&[2, 1], &[5], 0), row(&[4, 1], &[12], 0)];
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE).is_some());
}
#[test]
fn equal_widths_have_nothing_to_align() {
let src = "aa x\naa y\n";
let rows = [row(&[2, 1], &[6], 0), row(&[2, 1], &[14], 0)];
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE).is_none());
}
#[test]
fn a_group_of_one_is_never_aligned() {
let src = "aa x\n";
let rows = [row(&[2, 1], &[6], 0)];
assert!(plan(src, &[&rows[0]], NAME, WIDE).is_none());
}
#[test]
fn a_group_that_would_overflow_the_line_is_flush() {
let src = "aa x\nbbbb y\n";
let rows = [row(&[2, 1], &[7], 0), row(&[4, 1], &[14], 0)];
// Widest aligned line is 5 + 1 = 6 columns.
assert!(plan(src, &[&rows[0], &rows[1]], NAME, 6).is_some());
assert!(plan(src, &[&rows[0], &rows[1]], NAME, 5).is_none());
}
#[test]
fn rendering_flush_writes_the_flush_separator() {
let cells = [text("input wire"), text("clk")];
let doc = render(&cells, NAME, None);
assert_eq!(flat_width(&doc), Some(14));
}
}