Files
lucisv/crates/vlog_formatter/src/range.rs
T
lucioandClaude Fable 5 a0ae5e5fa8 Format fences at statement level and inside class bodies
TODO section 31 (coverage_gaps M9, docs/topo.md 2.9-3).
fence::collect enters class bodies, functions, tasks and always/
initial/final blocks, and statement lists - begin/end, fork/join and
every compound body - through scan_stmt_scope/scan_nested_stmt on the
one scan_units both scope kinds share; stmt_docs/stmt_seq obey the two
swallowed-unit rules item_docs/item_seq had; fence regions merge into
range.rs's plan, which was load-bearing (a fenced statement has no
verbatim run behind it; proved by disabling it). A region opens only at
a line start (opens_line) - the rule the format-fences README has
stated since round 1 - so a fence after code on the same line is an
ordinary comment everywhere, which narrows one accidental item-level
shape (module m; // lucisv: off) and is ruled a drift fix. Deferred
with reasons: port lists, case-item label lists, same-line fences, a
property's locals. verify.rs, lucisv/src/lint.rs and
lucisv_server/src/lint.rs untouched.
Proof: 3 244 tests / 48 binaries, fences.cases 25 -> 38 with the
statement-level entry inverted, corpus 814/820 and 860 files byte-
identical to 0.34.0, opentitan: 4 of its 9 fenced files now keep their
fenced bytes and are fixed points, --check counts identical; 3 348
fence-injection trials with no new refusals.

docs/features/statement-fences/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-03 03:40:12 -07:00

539 lines
21 KiB
Rust

//! `--lines M-N` range formatting: lay out only what the caller selected.
//!
//! A range is morally an inverted fence. The unit of formatting is an *item*:
//! one whose lines intersect a requested range is laid out exactly as a
//! whole-file run would lay it out, and every other item is emitted as the
//! source bytes it was written with — the splice `fence.rs` already does, over
//! ranges the caller chose instead of ranges a comment marked.
//!
//! Two things make that more than a byte filter:
//!
//! 1. **Runs.** Consecutive unselected items are merged into *one* verbatim
//! slice, so the blank lines between them survive untouched. Emitting them
//! one at a time would let the item separator normalize the gaps.
//! 2. **Splits.** A module whose body is 2000 lines long must not reformat
//! whole because three of them were edited, so a scope-bearing item is
//! descended into: its header and its `endmodule` stay verbatim unless they
//! intersect, and only the body items that intersect are laid out.
//!
//! Full spec: `docs/features/range-formatting/README.md`.
use crate::fence::{self, Region};
use vlog_parser::ast::{Item, ItemKind, SourceFile};
use vlog_parser::token::Comment;
use vlog_parser::LineIndex;
/// The lines a caller asked to format: 1-based, inclusive, sorted, disjoint.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct LineRanges {
spans: Vec<(u32, u32)>,
}
impl LineRanges {
/// Build from `(first, last)` pairs, merging what overlaps or touches.
///
/// A reversed range is a typo, not an intent, so it is refused; a range
/// running past the end of the file is not, because a wrapper deriving
/// ranges from a diff cannot know where the file ends.
pub fn new(spans: impl IntoIterator<Item = (u32, u32)>) -> Result<LineRanges, String> {
let mut spans: Vec<(u32, u32)> = spans.into_iter().collect();
for &(first, last) in &spans {
if first == 0 || last == 0 {
return Err("line numbers start at 1".to_string());
}
if first > last {
return Err(format!("reversed line range: {first}-{last}"));
}
}
if spans.is_empty() {
return Err("no line ranges given".to_string());
}
spans.sort_unstable();
let mut merged: Vec<(u32, u32)> = Vec::with_capacity(spans.len());
for (first, last) in spans {
match merged.last_mut() {
// `first == prev.1 + 1` is adjacent, not overlapping, and
// merging it changes no answer while shortening the list.
Some(prev) if first <= prev.1.saturating_add(1) => prev.1 = prev.1.max(last),
_ => merged.push((first, last)),
}
}
Ok(LineRanges { spans: merged })
}
/// Parse a `--lines` value: `M-N`, a single `M`, or a comma-separated list
/// of either.
pub fn parse(spec: &str) -> Result<LineRanges, String> {
let mut spans = Vec::new();
for piece in spec.split(',') {
let piece = piece.trim();
if piece.is_empty() {
return Err(format!("empty line range in `{spec}`"));
}
let (first, last) = match piece.split_once('-') {
Some((a, b)) => (number(a, spec)?, number(b, spec)?),
None => {
let n = number(piece, spec)?;
(n, n)
}
};
spans.push((first, last));
}
LineRanges::new(spans)
}
/// The ranges, as sorted disjoint 1-based inclusive pairs.
pub fn spans(&self) -> &[(u32, u32)] {
&self.spans
}
/// Does any requested range meet the inclusive line span `first..=last`?
fn hits(&self, first: u32, last: u32) -> bool {
self.spans.iter().any(|&(a, b)| a <= last && first <= b)
}
}
fn number(text: &str, spec: &str) -> Result<u32, String> {
text.trim().parse().map_err(|_| format!("invalid line number `{text}` in `{spec}`"))
}
/// What range formatting does with one item.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pick {
/// Emit the item's own bytes, exactly as written.
Verbatim,
/// Lay the item out, as a whole-file run would.
Format,
/// Lay out the item's *body* item by item. `head`/`tail` say whether the
/// item's own header and closing keyword are laid out too.
Split { head: bool, tail: bool },
}
/// The per-unit decisions of one range run.
///
/// Recorded once against the input and replayed against the formatted output.
/// That is what makes the convergence check meaningful when only part of a
/// file was formatted: the output has the same token stream as the input
/// (equivalence says so), hence the same item tree, hence the same walk order
/// — so the second pass reformats exactly the units the first one did, and any
/// drift shows up as a failed fixed point rather than as silent damage.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Selection {
picks: Vec<Pick>,
}
/// A scope-bearing item formatted from the inside out.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Split {
/// `Item::span.start` of the item this describes — its identity.
pub item: usize,
/// Source bytes of the header, leading comments included; `None` when the
/// header is laid out instead.
pub head: Option<(usize, usize)>,
/// Source bytes of the closing keyword, its trailing comment included;
/// `None` when it is laid out instead.
pub tail: Option<(usize, usize)>,
}
/// Everything the formatter needs to lay out part of a file.
#[derive(Debug, Clone, Default)]
pub struct Plan {
/// Byte ranges emitted exactly as written, sorted and non-overlapping.
pub regions: Vec<Region>,
/// Items descended into, sorted by [`Split::item`].
pub splits: Vec<Split>,
}
/// Decide what each unit of `file` gets, from the lines the caller asked for.
pub fn select(src: &str, file: &SourceFile, lines: &LineRanges) -> Selection {
let mut planner = Planner::new(src, file, Mode::Lines(lines));
planner.scope(&file.items, &file.dangling);
Selection { picks: planner.picks }
}
/// Turn a [`Selection`] into the byte plan for `src`.
///
/// `src` must be the text `file` was parsed from; it need not be the text the
/// selection was made against.
pub fn plan(src: &str, file: &SourceFile, selection: &Selection) -> Plan {
let mut planner = Planner::new(src, file, Mode::Picks(&selection.picks));
planner.scope(&file.items, &file.dangling);
// The fenced regions go in alongside the runs the picks made. An *item* a
// fence covers is already `Pick::Verbatim`, so its bytes are in a run
// either way; a fenced **statement** inside a laid-out item has no such
// run behind it, and without this the caller's `--lines` would reformat
// bytes the author fenced off. `normalize` folds the two into their union.
let mut regions = planner.regions;
regions.extend(planner.fences.iter().copied());
Plan { regions: normalize(regions), splits: planner.splits }
}
/// Sort the collected regions and fold everything that overlaps into one.
///
/// Fenced regions and verbatim runs can overlap — a run swallows the fence
/// that made its items unformattable, and a fence closing inside the next
/// item's leading comments reaches past a run's end — and the formatter's
/// lookup wants a list sorted by both ends. The union is the right answer for
/// both: every byte in either region is source text either way, and the
/// earliest opener is where it gets emitted.
fn normalize(mut regions: Vec<Region>) -> Vec<Region> {
regions.sort_by_key(|r| (r.start, std::cmp::Reverse(r.end)));
let mut out: Vec<Region> = Vec::with_capacity(regions.len());
for region in regions {
match out.last_mut() {
Some(prev) if region.start < prev.end => {
prev.end = prev.end.max(region.end);
prev.fence = prev.fence.min(region.fence);
}
_ => out.push(region),
}
}
out
}
/// Where a decision comes from: the caller's lines, or an earlier run's.
#[derive(Clone, Copy)]
enum Mode<'a> {
Lines(&'a LineRanges),
Picks(&'a [Pick]),
}
/// The byte extents a split item is cut at.
#[derive(Debug, Clone, Copy)]
struct Extents {
head: (usize, usize),
tail: (usize, usize),
}
struct Planner<'a> {
src: &'a str,
index: LineIndex,
/// The fenced regions of `src`. A fenced item is never formatted, whatever
/// the caller's lines say: `// verilog_format: off` outranks `--lines`.
fences: Vec<Region>,
mode: Mode<'a>,
picks: Vec<Pick>,
cursor: usize,
regions: Vec<Region>,
splits: Vec<Split>,
}
impl<'a> Planner<'a> {
fn new(src: &'a str, file: &SourceFile, mode: Mode<'a>) -> Planner<'a> {
Planner {
src,
index: LineIndex::new(src),
fences: fence::collect(src, file),
mode,
picks: Vec::new(),
cursor: 0,
regions: Vec::new(),
splits: Vec::new(),
}
}
/// Walk one item-list scope. Returns whether anything in it is laid out,
/// which is what tells an enclosing item that it has to be descended into.
fn scope(&mut self, items: &[Item], dangling: &[Comment]) -> bool {
let mut touched = false;
// A run of consecutive verbatim units, as `(first byte, last byte)`.
let mut run: Option<(usize, usize, usize)> = None;
for item in items {
let pick = self.item(item);
touched |= pick != Pick::Verbatim;
let (start, end) = self.unit_extent(item);
match pick {
Pick::Verbatim => self.extend(&mut run, start, end),
_ => self.flush(&mut run),
}
}
for comment in dangling {
let (start, end) = (comment.span.start as usize, comment.span.end as usize);
match self.comment(comment) {
Pick::Verbatim => self.extend(&mut run, start, end),
_ => {
touched = true;
self.flush(&mut run);
}
}
}
self.flush(&mut run);
touched
}
/// Add one unit's bytes to the open run, opening it if there is none.
fn extend(&self, run: &mut Option<(usize, usize, usize)>, start: usize, end: usize) {
match run {
Some((_, _, last)) => *last = end,
None => *run = Some((fence::line_start(self.src, start), start, end)),
}
}
/// Close the open run, if any, and record it as a verbatim region.
fn flush(&mut self, run: &mut Option<(usize, usize, usize)>) {
if let Some((start, open, end)) = run.take() {
self.regions.push(Region { fence: open, start, end });
}
}
/// Decide one item, having first decided everything nested inside it.
fn item(&mut self, item: &Item) -> Pick {
let slot = self.reserve();
let extents = self.extents(item);
let touched = match scope_of(item) {
// The body is always walked, splittable or not, so the shape of
// the pick list depends on the item tree alone — which is what
// lets a selection be replayed against reformatted text.
Some((items, dangling)) => self.scope(items, dangling),
None => false,
};
let pick = self.decide(slot, item, extents, touched);
if let (Pick::Split { head, tail }, Some(e)) = (pick, extents) {
self.splits.push(Split {
item: item.span.start as usize,
head: (!head).then_some(e.head),
tail: (!tail).then_some(e.tail),
});
}
pick
}
/// Decide one dangling comment. It has no body and no header, so it is
/// laid out or emitted as written, nothing else.
fn comment(&mut self, comment: &Comment) -> Pick {
let slot = self.reserve();
let pick = match self.mode {
Mode::Picks(picks) => picks.get(slot).copied().unwrap_or(Pick::Verbatim),
Mode::Lines(lines) => {
let start = comment.span.start as usize;
if fence::region_at(&self.fences, start).is_some()
|| !self.hits(lines, start, comment.span.end as usize)
{
Pick::Verbatim
} else {
Pick::Format
}
}
};
self.record(slot, pick);
pick
}
fn decide(
&mut self,
slot: usize,
item: &Item,
extents: Option<Extents>,
touched: bool,
) -> Pick {
let pick = match self.mode {
Mode::Picks(picks) => picks.get(slot).copied().unwrap_or(Pick::Verbatim),
Mode::Lines(lines) => self.pick_from_lines(lines, item, extents, touched),
};
// A pick that asks for a split the text cannot be cut at would emit
// nothing for the header; fall back to laying the whole item out.
let pick = match pick {
Pick::Split { .. } if extents.is_none() => Pick::Format,
other => other,
};
self.record(slot, pick);
pick
}
fn pick_from_lines(
&self,
lines: &LineRanges,
item: &Item,
extents: Option<Extents>,
touched: bool,
) -> Pick {
// `// verilog_format: off` wins: the bytes stay whatever the caller
// selected, and the fence machinery is already emitting them.
if fence::region_at(&self.fences, item.span.start as usize).is_some() {
return Pick::Verbatim;
}
let Some(e) = extents else {
let (start, end) = self.unit_extent(item);
return if self.hits(lines, start, end) { Pick::Format } else { Pick::Verbatim };
};
let head = self.hits(lines, e.head.0, e.head.1);
let tail = self.hits(lines, e.tail.0, e.tail.1);
if head || tail || touched {
Pick::Split { head, tail }
} else {
Pick::Verbatim
}
}
/// The index this unit's pick lives at, advancing the cursor.
fn reserve(&mut self) -> usize {
let slot = self.cursor;
self.cursor += 1;
if matches!(self.mode, Mode::Lines(_)) {
self.picks.push(Pick::Verbatim);
}
slot
}
fn record(&mut self, slot: usize, pick: Pick) {
if let Some(entry) = self.picks.get_mut(slot) {
*entry = pick;
}
}
/// Does any requested range meet the lines the byte range `start..end`
/// occupies?
fn hits(&self, lines: &LineRanges, start: usize, end: usize) -> bool {
let first = self.index.line_col(start as u32).0;
let last = self.index.line_col(end.saturating_sub(1).max(start) as u32).0;
lines.hits(first, last)
}
/// An item's whole unit: its leading comments through the comment written
/// after it on the same line.
fn unit_extent(&self, item: &Item) -> (usize, usize) {
let start = item
.meta
.leading
.first()
.map_or(item.span.start, |c| c.span.start.min(item.span.start));
(start as usize, fence::with_trailing_comments(self.src, item.span.end as usize))
}
/// Where a scope-bearing item can be cut into header, body and footer, or
/// `None` when it cannot be cut at all.
///
/// Every boundary has to fall on a line of its own, because a verbatim
/// slice is emitted at column zero and carries its own indentation. A
/// module written as `module m; wire a; endmodule` has no such line, so it
/// is laid out whole or not at all.
fn extents(&self, item: &Item) -> Option<Extents> {
let (items, dangling) = scope_of(item)?;
let head_start = own_line_start(self.src, self.unit_extent(item).0)?;
let first = items
.first()
.map(|i| self.unit_extent(i).0)
.or_else(|| dangling.first().map(|c| c.span.start as usize))?;
let head_end = trim_back(self.src, own_line_start(self.src, first)?);
if head_end <= head_start {
return None;
}
// The scope's dangling comments come after its last item, so they —
// not the item — are where the body ends when there are any.
let last = dangling
.last()
.map(|c| c.span.end as usize)
.or_else(|| items.last().map(|i| self.unit_extent(i).1))?;
let close = next_code(self.src, last)?;
if close >= item.span.end as usize {
return None;
}
let tail_start = own_line_start(self.src, close)?;
if tail_start < last {
return None;
}
let tail_end = fence::with_trailing_comments(self.src, item.span.end as usize);
Some(Extents { head: (head_start, head_end), tail: (tail_start, tail_end) })
}
}
/// The item scope an item carries, if it is one this feature descends into.
///
/// Modules and packages only. A `generate` region, a class or a `begin`…`end`
/// is an item scope too, but it has no header worth keeping apart from its
/// body, and the point of descending is to spare a 2000-line module body —
/// which is exactly the shape these two have. Everything else is one unit.
fn scope_of(item: &Item) -> Option<(&[Item], &[Comment])> {
match &item.kind {
ItemKind::Module(m) => Some((&m.items, &m.dangling)),
ItemKind::Package { items, dangling, .. } => Some((items, dangling)),
_ => None,
}
}
/// The start of `at`'s line, or `None` when anything but whitespace precedes
/// it there.
fn own_line_start(src: &str, at: usize) -> Option<usize> {
let bol = src.get(..at).and_then(|s| s.rfind('\n')).map_or(0, |i| i + 1);
src.get(bol..at).filter(|before| before.chars().all(char::is_whitespace)).map(|_| bol)
}
/// Walk `end` back over whitespace, so a slice never ends in the blank lines
/// that follow it.
fn trim_back(src: &str, end: usize) -> usize {
src.get(..end).map_or(end, |s| s.trim_end().len())
}
/// The first non-whitespace byte at or after `at`.
fn next_code(src: &str, at: usize) -> Option<usize> {
let rest = src.get(at..)?;
let trimmed = rest.trim_start();
if trimmed.is_empty() {
return None;
}
Some(at + rest.len() - trimmed.len())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ranges_are_sorted_and_merged() {
let r = LineRanges::parse("10-12,1-3,2-5").expect("parses");
assert_eq!(r.spans(), [(1, 5), (10, 12)]);
// Adjacent ranges fold together; a bare number is one line.
assert_eq!(LineRanges::parse("1-2,3-4").expect("parses").spans(), [(1, 4)]);
assert_eq!(LineRanges::parse("7").expect("parses").spans(), [(7, 7)]);
assert_eq!(LineRanges::parse(" 4 - 6 ").expect("parses").spans(), [(4, 6)]);
}
#[test]
fn a_reversed_or_zero_range_is_refused() {
assert!(LineRanges::parse("5-1").is_err(), "reversed");
assert!(LineRanges::parse("0-3").is_err(), "lines are 1-based");
assert!(LineRanges::parse("1,,2").is_err(), "empty piece");
assert!(LineRanges::parse("").is_err());
assert!(LineRanges::parse("a-b").is_err());
assert!(LineRanges::parse("1-2-3").is_err());
assert!(LineRanges::new([]).is_err(), "no ranges at all");
}
#[test]
fn a_range_past_the_end_of_the_file_is_kept() {
// A wrapper deriving ranges from a diff cannot know where the file
// ends, so this clamps by simply matching no line.
let r = LineRanges::parse("900-1000").expect("parses");
assert!(!r.hits(1, 20));
assert!(r.hits(950, 960));
}
#[test]
fn overlapping_regions_fold_into_their_union() {
let regions = normalize(vec![
Region { fence: 30, start: 30, end: 40 },
Region { fence: 12, start: 10, end: 35 },
Region { fence: 0, start: 0, end: 5 },
]);
assert_eq!(
regions,
vec![Region { fence: 0, start: 0, end: 5 }, Region { fence: 12, start: 10, end: 40 }]
);
}
#[test]
fn a_line_start_is_only_its_own_when_nothing_but_space_precedes() {
assert_eq!(own_line_start("module m;\n wire a;\n", 12), Some(10));
assert_eq!(own_line_start("module m;\n wire a;\n", 10), Some(10));
assert_eq!(own_line_start("wire a; wire b;\n", 8), None);
assert_eq!(own_line_start("wire a;\n", 0), Some(0));
}
#[test]
fn the_helpers_walk_over_whitespace_in_both_directions() {
assert_eq!(trim_back("a;\n\n\n", 5), 2);
assert_eq!(next_code("a;\n\n endmodule\n", 2), Some(6));
assert_eq!(next_code("a;\n\n ", 2), None, "nothing but whitespace left");
}
}