diff --git a/crates/vlog_formatter/src/format/mod.rs b/crates/vlog_formatter/src/format/mod.rs index 98a22be..778b47a 100644 --- a/crates/vlog_formatter/src/format/mod.rs +++ b/crates/vlog_formatter/src/format/mod.rs @@ -28,7 +28,7 @@ mod stmt; mod sva; mod verbatim; -use crate::doc::{text, Doc}; +use crate::doc::{concat, text, Doc}; use crate::fence::{self, Region}; use crate::printer::Printer; use crate::range::{self, Split}; @@ -62,6 +62,10 @@ pub enum FormatError { Source(vlog_parser::Error), /// A safety check failed; the formatted text was discarded. Verification(VerificationError), + /// A selection could not be laid out on its own — it reaches a parse + /// error, or its target could not be found again in the output. Nothing + /// was changed. + Selection(String), } impl std::fmt::Display for FormatError { @@ -69,6 +73,7 @@ impl std::fmt::Display for FormatError { match self { FormatError::Source(e) => write!(f, "{e}"), FormatError::Verification(e) => write!(f, "{e}"), + FormatError::Selection(e) => write!(f, "{e}"), } } } @@ -130,6 +135,41 @@ pub fn format_range( Ok(output) } +/// A sibling run a selection lays out on its own: items at their AST depth, +/// or statements. +pub(crate) enum Run<'t> { + Items(&'t [Item], usize), + Stmts(&'t [Stmt]), +} + +/// Lay out one run of `file` (parsed from `source`) exactly as the +/// whole-file printers would, every line starting with `base`. +/// +/// No final-newline normalization and no trailing whitespace: the result +/// replaces the run's own bytes and nothing else. Fenced regions inside the +/// run are emitted as written, as in a whole-file run. +pub(crate) fn print_run( + source: &str, + file: &SourceFile, + config: &Config, + run: Run<'_>, + base: &str, +) -> String { + let regions = fence::collect(source, file); + let fmt = Fmt { cfg: config, src: source, regions, splits: Vec::new() }; + let docs = match run { + Run::Items(items, depth) => fmt.item_seq(items, depth), + Run::Stmts(stmts) => fmt.stmt_seq(stmts), + }; + let printer = Printer { max_width: config.max_width, indent_width: config.indent_width }; + let mut out = printer.print_at(&concat(docs), base); + // Spaces and newlines only, exactly what `render` trims. + while out.ends_with('\n') || out.ends_with(' ') { + out.pop(); + } + out +} + /// A single unverified formatting pass: parse, lay out, print. fn format_once(source: &str, config: &Config) -> Result { let file = vlog_parser::parse_source(source)?; diff --git a/crates/vlog_formatter/src/lib.rs b/crates/vlog_formatter/src/lib.rs index 28c54fd..6dc7114 100644 --- a/crates/vlog_formatter/src/lib.rs +++ b/crates/vlog_formatter/src/lib.rs @@ -6,8 +6,10 @@ pub mod fence; pub mod format; pub mod printer; pub mod range; +mod selection; pub mod verify; pub use format::{format_range, format_source, Config, FormatError}; pub use range::LineRanges; +pub use selection::format_selection; pub use verify::{verify_convergence, verify_equivalence, VerificationError}; diff --git a/crates/vlog_formatter/src/printer.rs b/crates/vlog_formatter/src/printer.rs index accfefd..1935e11 100644 --- a/crates/vlog_formatter/src/printer.rs +++ b/crates/vlog_formatter/src/printer.rs @@ -18,9 +18,22 @@ pub struct Printer { } impl Printer { + /// Render `doc` starting at column 0. pub fn print(&self, doc: &Doc) -> String { - let mut out = String::new(); - let mut col = 0usize; + self.print_at(doc, "") + } + + /// Render `doc` as if every line began with `base`: the text starts with + /// `base`, every line break the printer writes repeats it before the + /// indentation, and the width budget shrinks by it. + /// + /// `base` is copied as written, tabs included, which is what lets a + /// selection keep the indentation it was written at. Text that carries + /// its own absolute indentation (`Doc::Verbatim`, `Doc::Inline`) is not + /// shifted. With an empty `base` this is exactly [`Printer::print`]. + pub fn print_at(&self, doc: &Doc, base: &str) -> String { + let mut out = base.to_string(); + let mut col = self.base_width(base); // Stack of (indent_level, mode, doc). let mut stack: Vec<(usize, Mode, &Doc)> = vec![(0, Mode::Break, doc)]; @@ -61,24 +74,22 @@ impl Printer { out.push(' '); col += 1; } else { - self.newline(&mut out, &mut col, ind); + self.newline(&mut out, &mut col, ind, base); } } Doc::SoftLine => { if mode == Mode::Break { - self.newline(&mut out, &mut col, ind); + self.newline(&mut out, &mut col, ind, base); } } Doc::HardLine => { - self.newline(&mut out, &mut col, ind); + self.newline(&mut out, &mut col, ind, base); } Doc::BlankLine => { // Trim trailing spaces from the current line, add a blank. - while out.ends_with(' ') { - out.pop(); - } + trim_line_end(&mut out, base); out.push('\n'); - self.newline(&mut out, &mut col, ind); + self.newline(&mut out, &mut col, ind, base); } Doc::IfBreak(s) => { if mode == Mode::Break { @@ -89,9 +100,7 @@ impl Printer { Doc::Verbatim(s) => { // Undo the indent the preceding line break wrote: these // bytes carry their own. - while out.ends_with(' ') { - out.pop(); - } + trim_line_end(&mut out, base); out.push_str(s); col = s.rsplit('\n').next().map_or(0, |last| last.chars().count()); } @@ -100,14 +109,20 @@ impl Printer { out } - fn newline(&self, out: &mut String, col: &mut usize, ind: usize) { - while out.ends_with(' ') { - out.pop(); - } + fn newline(&self, out: &mut String, col: &mut usize, ind: usize, base: &str) { + trim_line_end(out, base); out.push('\n'); + out.push_str(base); let spaces = ind * self.indent_width; out.extend(std::iter::repeat_n(' ', spaces)); - *col = spaces; + *col = self.base_width(base) + spaces; + } + + /// The columns `base` occupies. A tab counts as one indent level: the + /// printer cannot know the reader's tab stop, and the width only steers + /// which groups break. + fn base_width(&self, base: &str) -> usize { + base.chars().map(|c| if c == '\t' { self.indent_width } else { 1 }).sum() } /// Would `items` (flat) followed by the rest of the work stack fit on @@ -194,6 +209,23 @@ impl Printer { } } +/// Drop the trailing spaces of the line being written. Under a non-empty +/// `base` a line holding nothing but indentation is emptied entirely, so a +/// blank line never keeps the base's tabs; with no base this is exactly the +/// space trim the printer always did. +fn trim_line_end(out: &mut String, base: &str) { + while out.ends_with(' ') { + out.pop(); + } + if base.is_empty() { + return; + } + let bol = out.rfind('\n').map_or(0, |i| i + 1); + if out[bol..].chars().all(|c| c == ' ' || c == '\t') { + out.truncate(bol); + } +} + pub(crate) fn contains_hard_line(items: &[Doc]) -> bool { items.iter().any(|d| match d { Doc::HardLine | Doc::BlankLine | Doc::Verbatim(_) => true, diff --git a/crates/vlog_formatter/src/selection/locate.rs b/crates/vlog_formatter/src/selection/locate.rs new file mode 100644 index 0000000..ccee056 --- /dev/null +++ b/crates/vlog_formatter/src/selection/locate.rs @@ -0,0 +1,262 @@ +//! Finding the run of sibling units one selected line span names. +//! +//! The walk starts at the file scope and goes down while the selection sits +//! inside a single unit below its first line and reaches into exactly one of +//! its nested scopes; it then settles on the units met there. A run that cannot be cut +//! out of its lines cleanly, or whose ends a fenced region covers, is trimmed +//! or given up one level at a time. The result is a [`Target`]: a path of +//! child indices plus a run, which is what lets the same units be found again +//! in the formatted output. + +use crate::fence::Region; +use vlog_parser::LineIndex; + +use super::scope::{Scope, Unit}; + +/// The units a selection lays out, by position in the tree. +/// +/// `path` holds one `(unit index, child scope index)` step per scope the walk +/// descended into; the run is `start..start + count` of the scope it ends in. +/// Positions, not bytes, so the target can be replayed on a reformatted text +/// whose tree is the same. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct Target { + pub path: Vec<(usize, usize)>, + pub start: usize, + pub count: usize, +} + +/// What one selected line span comes to. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) enum Found { + /// No unit to lay out: blank lines, or everything met is fenced. + Nothing, + /// The run holds a module or package, or no run is line-clean: the + /// request goes to `format_range` whole. + Defer, + Target(Target), +} + +/// The finder over one text and the tree parsed from it. +pub(super) struct Locator<'s> { + src: &'s str, + index: LineIndex, + regions: Vec, +} + +impl<'s> Locator<'s> { + pub(super) fn new(src: &'s str, regions: Vec) -> Locator<'s> { + Locator { src, index: LineIndex::new(src), regions } + } + + /// Locate the run the 1-based inclusive lines `first..=last` select. + pub(super) fn locate(&self, root: Scope<'_>, (first, last): (u32, u32)) -> Found { + let mut trail = vec![root]; + let mut path = Vec::new(); + let mut scope = root; + let Some((mut a, mut b)) = self.met(scope, first, last) else { return Found::Nothing }; + while a == b { + let Some((k, child)) = self.descend(scope, a, first, last) else { break }; + let Some(run) = self.met(child, first, last) else { break }; + path.push((a, k)); + trail.push(child); + scope = child; + (a, b) = run; + } + loop { + let Some((a2, b2)) = self.trim_fences(scope, a, b) else { return Found::Nothing }; + if self.clean(scope, a2, b2) { + return self.target(scope, path, a2, b2); + } + // Not cut cleanly at its lines: the enclosing unit is. + trail.pop(); + let (Some((i, _)), Some(&parent)) = (path.pop(), trail.last()) else { + return Found::Defer; + }; + (scope, a, b) = (parent, i, i); + } + } + + fn target(&self, scope: Scope<'_>, path: Vec<(usize, usize)>, a: usize, b: usize) -> Found { + let contains_container = + (a..=b).filter_map(|i| scope.unit(i)).any(|unit| unit.is_container()); + if contains_container { + return Found::Defer; + } + Found::Target(Target { path, start: a, count: b - a + 1 }) + } + + /// The first and last units of `scope` whose lines meet `first..=last`. + fn met(&self, scope: Scope<'_>, first: u32, last: u32) -> Option<(usize, usize)> { + let mut hit: Option<(usize, usize)> = None; + for i in 0..scope.len() { + let Some(unit) = scope.unit(i) else { continue }; + let (l0, l1) = self.lines(unit); + if l0 <= last && first <= l1 { + hit = Some(hit.map_or((i, i), |(a, _)| (a, i))); + } + } + hit + } + + /// The nested scope to descend into from unit `i`: only when the + /// selection does not touch the unit's first line, and reaches into + /// exactly one of its scopes. + /// + /// The last line is deliberately not asked about. A selection dragged + /// over the final statements of a block and its closing `end` means those + /// statements; taking the whole enclosing unit for it re-laid hundreds of + /// unselected lines (QA note 2, lead ruling 2026-11-09). The closing line + /// alone meets no nested unit, so it still names the unit it closes. + fn descend<'t>( + &self, + scope: Scope<'t>, + i: usize, + first: u32, + last: u32, + ) -> Option<(usize, Scope<'t>)> { + let unit = scope.unit(i)?; + let (l0, _) = self.lines(unit); + if first <= l0 { + return None; + } + let mut reached = unit + .children() + .into_iter() + .enumerate() + .filter(|(_, child)| self.met(*child, first, last).is_some()); + let only = reached.next()?; + reached.next().is_none().then_some(only) + } + + /// The 1-based first and last lines of a unit's extent. + fn lines(&self, unit: Unit<'_>) -> (u32, u32) { + let (start, end) = unit.extent(self.src); + 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; + (first, last) + } + + /// Drop units a fenced region of this scope reaches from both ends of the + /// run, so no region is ever half inside the splice. `None` when nothing + /// is left. + fn trim_fences(&self, scope: Scope<'_>, mut a: usize, mut b: usize) -> Option<(usize, usize)> { + while a <= b && self.fenced(scope, a) { + a += 1; + } + while b > a && self.fenced(scope, b) { + b -= 1; + } + (a <= b).then_some((a, b)) + } + + /// Whether a region opened in this scope — not one nested inside the + /// unit's own code — overlaps unit `i`'s extent. + fn fenced(&self, scope: Scope<'_>, i: usize) -> bool { + let Some(unit) = scope.unit(i) else { return true }; + let (start, end) = unit.extent(self.src); + let span = unit.span(); + let (code_start, code_end) = (span.start as usize, span.end as usize); + self.regions.iter().any(|r| { + let overlaps = r.start < end && start < r.end; + let nested = r.start >= code_start && r.end <= code_end; + overlaps && !nested + }) + } + + /// Whether units `a..=b` can be replaced by whole lines: only indentation + /// before the first, nothing after the last on its line, and no sibling + /// or dangling comment of the scope inside the bytes between. + fn clean(&self, scope: Scope<'_>, a: usize, b: usize) -> bool { + let (Some(first), Some(last)) = (scope.unit(a), scope.unit(b)) else { return false }; + let (start, _) = first.extent(self.src); + let (_, end) = last.extent(self.src); + let bol = line_start(self.src, start); + let indent_only = self.src.get(bol..start).is_some_and(|s| s.chars().all(is_indent)); + let eol = + self.src.get(end..).map_or(end, |rest| end + rest.find('\n').unwrap_or(rest.len())); + let rest_blank = self.src.get(end..eol).is_some_and(|s| s.chars().all(char::is_whitespace)); + let prev_clear = a == 0 || scope.unit(a - 1).is_some_and(|u| u.extent(self.src).1 <= start); + let next_clear = scope.unit(b + 1).is_none_or(|u| u.extent(self.src).0 >= end); + let dangling_clear = scope + .dangling() + .iter() + .all(|c| c.span.end as usize <= start || c.span.start as usize >= end); + indent_only && rest_blank && prev_clear && next_clear && dangling_clear + } +} + +/// The bytes a resolved target replaces, and the run that replaces them. +pub(super) struct Placed<'t> { + pub run: crate::format::Run<'t>, + /// Start of the first unit's line: where the splice begins. + pub bol: usize, + /// The base indentation every line of the layout starts with, as a byte + /// range of the source: the leading whitespace of the run's first unit + /// that is not a directive (see [`base_indent`]). + pub base: (usize, usize), + /// One past the last unit's last byte. + pub end: usize, +} + +/// Find `target` again in a tree, and the bytes of `src` it occupies. +pub(super) fn resolve<'t>(src: &str, root: Scope<'t>, target: &Target) -> Option> { + let mut scope = root; + for &(i, k) in &target.path { + scope = scope.unit(i)?.children().into_iter().nth(k)?; + } + let first = scope.unit(target.start)?; + let last = scope.unit(target.start + target.count.checked_sub(1)?)?; + let start = first.extent(src).0; + let end = last.extent(src).1; + let run = scope.run(target.start, target.count)?; + let base = base_indent(src, scope, target, start); + Some(Placed { run, bol: line_start(src, start), base, end }) +} + +/// The indentation the run is laid out at: that of its first unit, unless +/// that unit is a compiler directive and a later one is not. Directives are +/// commonly written at column 0 while the code they guard is indented, and +/// the code is what says where the block stands; the directive is then +/// indented with it, as a whole-file run would. +fn base_indent(src: &str, scope: Scope<'_>, target: &Target, start: usize) -> (usize, usize) { + let code = (target.start..target.start + target.count) + .filter_map(|i| scope.unit(i)) + .find(|u| !u.is_directive()) + .map(|u| u.extent(src).0); + let own_line = |at: usize| { + let bol = line_start(src, at); + src.get(bol..at).is_some_and(|s| s.chars().all(is_indent)).then_some((bol, at)) + }; + code.and_then(own_line).unwrap_or((line_start(src, start), start)) +} + +/// Every unit of a resolved target and everything nested in it, for the +/// error-node check of a tolerant parse. +pub(super) fn any_error(root: Scope<'_>, target: &Target) -> bool { + let mut scope = root; + for &(i, k) in &target.path { + let Some(next) = scope.unit(i).and_then(|u| u.children().into_iter().nth(k)) else { + return true; + }; + scope = next; + } + (target.start..target.start + target.count).any(|i| scope.unit(i).is_none_or(unit_has_error)) +} + +fn unit_has_error(unit: Unit<'_>) -> bool { + unit.is_error() + || unit + .children() + .into_iter() + .any(|s| (0..s.len()).any(|i| s.unit(i).is_none_or(unit_has_error))) +} + +/// The start of the line `at` is on. +pub(super) fn line_start(src: &str, at: usize) -> usize { + src.get(..at).and_then(|s| s.rfind('\n')).map_or(0, |i| i + 1) +} + +fn is_indent(c: char) -> bool { + c == ' ' || c == '\t' +} diff --git a/crates/vlog_formatter/src/selection/mod.rs b/crates/vlog_formatter/src/selection/mod.rs new file mode 100644 index 0000000..4032b55 --- /dev/null +++ b/crates/vlog_formatter/src/selection/mod.rs @@ -0,0 +1,238 @@ +//! Selection formatting: lay out the smallest run of sibling items or +//! statements the selected lines cover, at the indentation it was written +//! at, and splice it into otherwise untouched bytes. +//! +//! This is what an editor's "Format Selection" wants. `format_range` (the +//! CLI's `--lines`) re-lays whole module-level items at formatter depth; +//! here the unit is whatever sibling list the selection lands in — a `case` +//! inside an `always`, two statements of a function — and the parent is not +//! touched at all. The run keeps the leading whitespace of its first line, +//! tabs and off-grid indentation included. Every other byte of the file stays +//! as written, the file tail included. +//! +//! The safety net is the usual one over the whole file: equivalence of the +//! token streams, then convergence by replaying the located *target* (a path +//! in the tree, not line numbers) on the output. Full spec: +//! `docs/features/selection-formatting/README.md`. + +mod locate; +mod scope; + +use crate::fence; +use crate::format::{format_range, print_run, Config, FormatError}; +use crate::range::LineRanges; +use crate::verify::{verify_convergence, verify_equivalence, VerificationError}; +use locate::{any_error, resolve, Found, Locator, Target}; +use scope::Scope; +use vlog_parser::ast::SourceFile; +use vlog_parser::ParseDiagnostic; + +/// Format the smallest runs of sibling items or statements `lines` covers, +/// each at the indentation its first line was written at, leaving every other +/// byte of `source` as it is. +/// +/// A selection reaching a module or package item as a whole is handed to +/// [`format_range`] unchanged. A file that does not parse is formatted only +/// where the selection is clear of every parse error; otherwise, as on any +/// failed check, the caller gets an error and must keep the original text. +/// +/// Same stack requirement as [`crate::format_source`]. +pub fn format_selection( + source: &str, + config: &Config, + lines: &LineRanges, +) -> Result { + let tree = Tree::parse(source).map_err(FormatError::Source)?; + let Some(root) = Scope::root(&tree.file) else { + return format_range(source, config, lines); + }; + let locator = Locator::new(source, fence::collect(source, &tree.file)); + let Ok(targets) = select(&locator, root, source, lines) else { + return format_range(source, config, lines); + }; + if targets.is_empty() { + return Ok(source.to_string()); + } + tree.check_clear(source, root, &targets)?; + let output = splice(source, &tree.file, root, config, &targets) + .ok_or_else(|| lost("the selection could not be cut out of its lines"))?; + verify_equivalence(source, &output)?; + let again = replay(&output, config, &targets)?; + verify_convergence(&output, &again)?; + Ok(output) +} + +/// Format the output a second time with the same targets, found again by +/// their position in its tree. +fn replay(output: &str, config: &Config, targets: &[Target]) -> Result { + let tree = Tree::parse(output).map_err(VerificationError::Reparse)?; + let root = Scope::root(&tree.file).ok_or_else(|| lost("the output is not the same kind"))?; + tree.check_clear(output, root, targets)?; + splice(output, &tree.file, root, config, targets) + .ok_or_else(|| lost("the selection could not be found again in the output")) +} + +fn lost(why: &str) -> FormatError { + FormatError::Selection(format!("cannot format the selection: {why}")) +} + +/// A parsed text: strictly when it parses, tolerantly when it does not. +struct Tree { + file: SourceFile, + /// The tolerant parse's diagnostics; empty for a strict parse. + diagnostics: Vec, +} + +impl Tree { + fn parse(src: &str) -> Result { + match vlog_parser::parse_source(src) { + Ok(file) => Ok(Tree { file, diagnostics: Vec::new() }), + Err(e) => { + let (file, diagnostics) = vlog_parser::parse_source_tolerant(src); + // A tolerant parse that finds nothing wrong where the strict + // one failed is not a tree to trust. + if diagnostics.is_empty() { + return Err(e); + } + Ok(Tree { file, diagnostics }) + } + } + } + + /// Refuse when a parse error lies inside any target: its layout would + /// rest on error recovery's guess. + fn check_clear( + &self, + src: &str, + root: Scope<'_>, + targets: &[Target], + ) -> Result<(), FormatError> { + if self.diagnostics.is_empty() { + return Ok(()); + } + for target in targets { + let placed = resolve(src, root, target).ok_or_else(|| lost("internal: lost target"))?; + let (lo, hi) = (placed.bol, placed.end); + let hit = self + .diagnostics + .iter() + .find(|d| (d.span.start as usize) <= hi && lo <= d.span.end as usize); + if let Some(d) = hit { + return Err(FormatError::Selection(format!( + "cannot format the selection: it contains a syntax error at {}:{}: {}", + d.line, d.col, d.message + ))); + } + if any_error(root, target) { + return Err(lost("it contains text that does not parse")); + } + } + Ok(()) + } +} + +/// The request goes to `format_range` whole. +struct Defer; + +/// Locate one target per selected span; targets whose bytes overlap are +/// re-selected from the hull of their spans. +fn select( + locator: &Locator<'_>, + root: Scope<'_>, + src: &str, + lines: &LineRanges, +) -> Result, Defer> { + let mut picked: Vec = Vec::new(); + for &span in lines.spans() { + picked.extend(pick(locator, root, src, span)?); + } + loop { + picked.sort_by_key(|p| p.bytes.0); + let Some(i) = (1..picked.len()).find(|&i| picked[i].bytes.0 < picked[i - 1].bytes.1) else { + break; + }; + let (a, b) = (picked.remove(i), picked.remove(i - 1)); + let hull = (a.span.0.min(b.span.0), a.span.1.max(b.span.1)); + picked.extend(pick(locator, root, src, hull)?); + } + Ok(picked.into_iter().map(|p| p.target).collect()) +} + +/// One located target, with the line span that chose it and the bytes it +/// replaces. +struct Picked { + span: (u32, u32), + target: Target, + bytes: (usize, usize), +} + +/// The target one span selects, if any. +fn pick( + locator: &Locator<'_>, + root: Scope<'_>, + src: &str, + span: (u32, u32), +) -> Result, Defer> { + match locator.locate(root, span) { + Found::Nothing => Ok(None), + Found::Defer => Err(Defer), + Found::Target(target) => { + // Resolving a target in the tree it was found in cannot fail; if + // it ever did, the conservative answer is the old engine. + let placed = resolve(src, root, &target).ok_or(Defer)?; + Ok(Some(Picked { span, target, bytes: (placed.bol, placed.end) })) + } + } +} + +/// Replace every target's bytes with its layout, bottom-up so the earlier +/// offsets stay valid. `None` when a target cannot be found or cut. +fn splice( + src: &str, + file: &SourceFile, + root: Scope<'_>, + config: &Config, + targets: &[Target], +) -> Option { + let mut placed = targets.iter().map(|t| resolve(src, root, t)).collect::>>()?; + placed.sort_by_key(|p| std::cmp::Reverse(p.bol)); + let mut out = src.to_string(); + let mut floor = src.len(); + for p in placed { + let base = src.get(p.base.0..p.base.1)?; + if p.end > floor || !base.chars().all(|c| c == ' ' || c == '\t') { + return None; + } + let mut text = print_run(src, file, config, p.run, base); + if uses_crlf(src, p.bol, p.end) { + text = to_crlf(&text); + } + out = format!("{}{}{}", out.get(..p.bol)?, text, out.get(p.end..)?); + floor = p.bol; + } + Some(out) +} + +/// Whether the lines around a target end in `\r\n`: the line ending after +/// it, or before it when it ends the file. +fn uses_crlf(src: &str, bol: usize, end: usize) -> bool { + match src.get(end..).and_then(|rest| rest.find('\n')) { + Some(i) => src.get(..end + i).is_some_and(|s| s.ends_with('\r')), + None => src.get(..bol).is_some_and(|s| s.ends_with("\r\n")), + } +} + +/// Turn every bare `\n` into `\r\n`; text copied from the source keeps the +/// `\r\n` it already had. +fn to_crlf(text: &str) -> String { + let mut out = String::with_capacity(text.len() + text.len() / 16); + let mut prev = '\0'; + for c in text.chars() { + if c == '\n' && prev != '\r' { + out.push('\r'); + } + out.push(c); + prev = c; + } + out +} diff --git a/crates/vlog_formatter/src/selection/scope.rs b/crates/vlog_formatter/src/selection/scope.rs new file mode 100644 index 0000000..1cefd21 --- /dev/null +++ b/crates/vlog_formatter/src/selection/scope.rs @@ -0,0 +1,234 @@ +//! The sibling lists a selection can land in, and the units they hold. +//! +//! A *scope* is a sibling list exactly as `fence.rs` defines one — an item +//! list (file, module, package, generate region, generate `begin`…`end`, +//! class) or a statement list (`begin`…`end`, `fork`…`join`, a function or +//! task body). A *unit* is one item or statement of such a list. The match +//! arms below mirror `fence::scan_nested` / `scan_nested_stmt` / +//! `scan_gen_block`: a single-statement body or a block-less generate item is +//! not a scope, so it is walked *through* to the scopes it reaches. An arm +//! missing here only makes a selection coarser, never wrong. + +use crate::fence; +use crate::format::Run; +use vlog_parser::ast::{ + GenBlock, GenElse, GenIf, Item, ItemKind, Meta, SourceFile, Stmt, StmtKind, +}; +use vlog_parser::span::TextRange; +use vlog_parser::token::Comment; + +/// One sibling list. Items carry the AST depth `item_seq` lays them out at. +#[derive(Clone, Copy)] +pub(super) enum Scope<'t> { + Items(&'t [Item], &'t [Comment], usize), + Stmts(&'t [Stmt], &'t [Comment]), +} + +/// One member of a scope. +#[derive(Clone, Copy)] +pub(super) enum Unit<'t> { + Item(&'t Item, usize), + Stmt(&'t Stmt), +} + +impl<'t> Scope<'t> { + /// The scope a whole file is, or `None` for a fragment whose elements + /// are not items or statements (enum members, cover items). + pub(super) fn root(file: &'t SourceFile) -> Option> { + match &file.fragment { + None => Some(Scope::Items(&file.items, &file.dangling, 0)), + Some(vlog_parser::ast::Fragment::Statements(stmts)) => { + Some(Scope::Stmts(stmts, &file.dangling)) + } + Some(_) => None, + } + } + + pub(super) fn len(&self) -> usize { + match self { + Scope::Items(items, ..) => items.len(), + Scope::Stmts(stmts, _) => stmts.len(), + } + } + + pub(super) fn unit(&self, i: usize) -> Option> { + match *self { + Scope::Items(items, _, depth) => items.get(i).map(|item| Unit::Item(item, depth)), + Scope::Stmts(stmts, _) => stmts.get(i).map(Unit::Stmt), + } + } + + pub(super) fn dangling(&self) -> &'t [Comment] { + match *self { + Scope::Items(_, dangling, _) | Scope::Stmts(_, dangling) => dangling, + } + } + + /// The units `start..start + count` as something the printers take. + pub(super) fn run(&self, start: usize, count: usize) -> Option> { + let end = start.checked_add(count)?; + match *self { + Scope::Items(items, _, depth) => items.get(start..end).map(|s| Run::Items(s, depth)), + Scope::Stmts(stmts, _) => stmts.get(start..end).map(Run::Stmts), + } + } +} + +impl<'t> Unit<'t> { + fn meta(&self) -> &'t Meta { + match self { + Unit::Item(item, _) => &item.meta, + Unit::Stmt(stmt) => &stmt.meta, + } + } + + pub(super) fn span(&self) -> TextRange { + match self { + Unit::Item(item, _) => item.span, + Unit::Stmt(stmt) => stmt.span, + } + } + + /// The unit's bytes: its first leading comment or attribute through the + /// comments written after it on the same line. + pub(super) fn extent(&self, src: &str) -> (usize, usize) { + let meta = self.meta(); + let span = self.span(); + let mut start = span.start; + if let Some(c) = meta.leading.first() { + start = start.min(c.span.start); + } + if let Some(a) = meta.attrs.first() { + start = start.min(a.span.start); + } + // In a CRLF file a trailing `//` comment's line ends `\r\n`, and the + // scan above stops at the `\n`. The `\r` is the line ending, not the + // unit: the layout does not write it, so the splice must not eat it. + let mut end = fence::with_trailing_comments(src, span.end as usize); + while end > span.end as usize && src.as_bytes().get(end - 1) == Some(&b'\r') { + end -= 1; + } + (start as usize, end) + } + + /// Whether the unit is a construct `format_range` splits (a module or a + /// package), which a selection defers to it. + pub(super) fn is_container(&self) -> bool { + matches!( + self, + Unit::Item(Item { kind: ItemKind::Module(_) | ItemKind::Package { .. }, .. }, _) + ) + } + + /// Whether the unit is a compiler directive (`` `ifdef `` and kin), + /// which is often written at column 0 whatever the code around it does. + pub(super) fn is_directive(&self) -> bool { + match self { + Unit::Item(item, _) => matches!(item.kind, ItemKind::Directive(_)), + Unit::Stmt(stmt) => matches!(stmt.kind, StmtKind::Directive(_)), + } + } + + /// Whether the unit is a node error recovery made of unparsable text. + pub(super) fn is_error(&self) -> bool { + match self { + Unit::Item(item, _) => matches!(item.kind, ItemKind::Error(_)), + Unit::Stmt(stmt) => matches!(stmt.kind, StmtKind::Error(_)), + } + } + + /// The scopes directly nested in this unit, in source order. + pub(super) fn children(&self) -> Vec> { + let mut out = Vec::new(); + match *self { + Unit::Item(item, depth) => item_scopes(item, depth, &mut out), + Unit::Stmt(stmt) => stmt_scopes(stmt, &mut out), + } + out + } +} + +/// The scopes nested in one item at `depth`, at the depth `item_kind` lays +/// their items out at. +fn item_scopes<'t>(item: &'t Item, depth: usize, out: &mut Vec>) { + match &item.kind { + ItemKind::Module(m) => out.push(Scope::Items(&m.items, &m.dangling, depth + 1)), + ItemKind::Package { items, dangling, .. } + | ItemKind::GenerateRegion { items, dangling } => { + out.push(Scope::Items(items, dangling, depth + 1)) + } + ItemKind::GenBlock(b) => gen_block_scopes(b, depth, out), + ItemKind::GenIf(g) => gen_if_scopes(g, depth, out), + ItemKind::GenFor(g) => gen_block_scopes(&g.body, depth, out), + ItemKind::GenCase(g) => { + for i in &g.items { + gen_block_scopes(&i.body, depth + 1, out); + } + } + ItemKind::Class(c) => out.push(Scope::Items(&c.items, &c.dangling, depth + 1)), + ItemKind::Function(f) => out.push(Scope::Stmts(&f.stmts, &f.dangling)), + ItemKind::Task(t) => out.push(Scope::Stmts(&t.stmts, &t.dangling)), + ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => { + stmt_scopes(stmt, out) + } + _ => {} + } +} + +fn gen_if_scopes<'t>(g: &'t GenIf, depth: usize, out: &mut Vec>) { + gen_block_scopes(&g.then, depth, out); + match g.els.as_deref() { + Some(GenElse::If(_, inner)) => gen_if_scopes(inner, depth, out), + Some(GenElse::Block(b)) => gen_block_scopes(b, depth, out), + None => {} + } +} + +/// A generate `begin`…`end` is a scope one level in; a block-less body's +/// one item is laid out one level in too, and walked through. +fn gen_block_scopes<'t>(b: &'t GenBlock, depth: usize, out: &mut Vec>) { + if b.is_block { + out.push(Scope::Items(&b.items, &b.dangling, depth + 1)); + } else { + for item in &b.items { + item_scopes(item, depth + 1, out); + } + } +} + +/// The statement lists one statement holds, walking through every +/// single-statement body. +fn stmt_scopes<'t>(stmt: &'t Stmt, out: &mut Vec>) { + match &stmt.kind { + StmtKind::Block { stmts, dangling, .. } | StmtKind::ForkJoin { stmts, dangling, .. } => { + out.push(Scope::Stmts(stmts, dangling)) + } + StmtKind::If { then, els, .. } => { + stmt_scopes(then, out); + if let Some(e) = els { + stmt_scopes(e, out); + } + } + StmtKind::Assert { then, els, .. } => { + for s in then.iter().chain(els.iter()) { + stmt_scopes(s, out); + } + } + StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => { + for i in items { + stmt_scopes(&i.stmt, out); + } + } + StmtKind::For { body, .. } + | StmtKind::While { body, .. } + | StmtKind::DoWhile { body, .. } + | StmtKind::Repeat { body, .. } + | StmtKind::Forever { body } + | StmtKind::Foreach { body, .. } + | StmtKind::Labeled { stmt: body, .. } => stmt_scopes(body, out), + StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => { + stmt_scopes(inner, out) + } + _ => {} + } +} diff --git a/crates/vlog_formatter/tests/selection.rs b/crates/vlog_formatter/tests/selection.rs new file mode 100644 index 0000000..22f4ed1 --- /dev/null +++ b/crates/vlog_formatter/tests/selection.rs @@ -0,0 +1,451 @@ +//! Selection formatting (`format_selection`): the smallest run of sibling +//! items or statements a selection covers is laid out at the indentation it +//! was written at, and every other byte of the file stays as written. +//! +//! Spec: `docs/features/selection-formatting/README.md`. + +use vlog_formatter::{format_range, format_selection, verify_equivalence, Config, LineRanges}; + +fn select_with(src: &str, spec: &str, config: &Config) -> Result { + let lines = LineRanges::parse(spec).expect("line spec"); + format_selection(src, config, &lines).map_err(|e| e.to_string()) +} + +fn select(src: &str, spec: &str) -> String { + select_with(src, spec, &Config::default()).expect("formats") +} + +/// Format, then format the result again with the same lines: the second run +/// must change nothing. +fn fixed(src: &str, spec: &str) -> String { + let out = select(src, spec); + assert_eq!(select(&out, spec), out, "a second run must change nothing"); + out +} + +/// Lines `first..=last` (1-based) of `src` are the target: everything before +/// and after must come back byte for byte, and the returned middle is what +/// replaced them. +fn middle<'a>(src: &str, out: &'a str, first: usize, last: usize) -> &'a str { + let lines: Vec<&str> = src.split_inclusive('\n').collect(); + let head: String = lines[..first - 1].concat(); + let tail: String = lines[last..].concat(); + assert!(out.starts_with(&head), "bytes before the target changed:\n{out}"); + assert!(out.ends_with(&tail), "bytes after the target changed:\n{out}"); + assert!(out.len() >= head.len() + tail.len(), "target overlaps the kept bytes:\n{out}"); + &out[head.len()..out.len() - tail.len()] +} + +// ------------------------------------------------------------------ +// The owner's shapes +// ------------------------------------------------------------------ + +/// A file indented four spaces, as many hand-written files are. +const FOUR: &str = "\ +module m; + reg [3:0] q; + always @(posedge clk) begin + if (rst) q<=0; + else begin + case (sel) + 2'b00: q<=a; + 2'b01 : q <= b; + default:q<=c; + endcase + end + end + assign y=q; +endmodule +"; + +#[test] +fn a_whole_always_keeps_its_indentation_in_a_four_space_file() { + let out = fixed(FOUR, "3-12"); + let mid = middle(FOUR, &out, 3, 12); + assert_eq!( + mid, + " always @(posedge clk) begin + if (rst) q <= 0; + else begin + case (sel) + 2'b00: q <= a; + 2'b01: q <= b; + default: q <= c; + endcase + end + end +" + ); +} + +#[test] +fn a_whole_case_inside_an_always_is_the_only_thing_laid_out() { + let out = fixed(FOUR, "6-10"); + let mid = middle(FOUR, &out, 6, 10); + assert_eq!( + mid, + " case (sel) + 2'b00: q <= a; + 2'b01: q <= b; + default: q <= c; + endcase +" + ); +} + +#[test] +fn an_always_inside_a_generate_for_is_laid_out_alone() { + let src = "\ +module m; + generate + for (genvar i=0;i<4;i++) begin : g + always @(posedge clk) q[i]<=d[i]; + assign w[i]=q[i]; + end + endgenerate +endmodule +"; + let out = fixed(src, "4"); + let mid = middle(src, &out, 4, 4); + assert_eq!(mid, " always @(posedge clk) q[i] <= d[i];\n"); +} + +#[test] +fn statements_inside_a_function_are_laid_out_without_the_function() { + let src = "\ +module m; + function automatic int f(input int a); + int r; + r=a+1; + return r; + endfunction +endmodule +"; + let out = fixed(src, "4-5"); + let mid = middle(src, &out, 4, 5); + assert_eq!(mid, " r = a + 1;\n return r;\n"); + assert!(out.contains(" int r;\n"), "the unselected statement stays: {out}"); +} + +#[test] +fn a_block_inside_an_else_branch_is_laid_out_alone() { + let src = "\ +module m; + always @* begin + if (a) x = 1; + else begin + y=2; + z = 3; + end + end +endmodule +"; + let out = fixed(src, "5-6"); + let mid = middle(src, &out, 5, 6); + assert_eq!(mid, " y = 2;\n z = 3;\n"); +} + +// ------------------------------------------------------------------ +// Indentation +// ------------------------------------------------------------------ + +#[test] +fn tab_indentation_is_reproduced_as_written() { + let src = "module m;\n\talways @* begin\n\t\tx=1;\n\t\tif (a) begin\n\t\t\ty=2;\n\t\tend\n\tend\nendmodule\n"; + let out = fixed(src, "2-7"); + let mid = middle(src, &out, 2, 7); + assert_eq!( + mid, + "\talways @(*) begin\n\t x = 1;\n\t if (a) begin\n\t y = 2;\n\t end\n\tend\n" + ); +} + +#[test] +fn off_grid_indentation_is_kept() { + let src = "module m;\n always @* begin\n x=1;\n end\nendmodule\n"; + let out = fixed(src, "2-4"); + assert_eq!(middle(src, &out, 2, 4), " always @(*) begin\n x = 1;\n end\n"); +} + +#[test] +fn a_misindented_parent_does_not_move_the_selection() { + let src = "module m;\nalways @* begin\n x=1;\n y = 2;\n end\nendmodule\n"; + let out = fixed(src, "3"); + assert_eq!(middle(src, &out, 3, 3), " x = 1;\n"); + assert!(out.contains("\n y = 2;\n"), "the sibling is untouched: {out}"); +} + +// ------------------------------------------------------------------ +// Partial selections +// ------------------------------------------------------------------ + +#[test] +fn one_line_inside_a_case_lays_out_the_case() { + let out = fixed(FOUR, "8"); + let mid = middle(FOUR, &out, 6, 10); + assert!(mid.starts_with(" case (sel)\n"), "{mid}"); + assert!(mid.contains(" 2'b01: q <= b;\n"), "{mid}"); +} + +#[test] +fn a_cursor_only_range_formats_the_statement_under_it() { + let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\nendmodule\n"; + let out = fixed(src, "4"); + assert_eq!(out, "module m;\n always @* begin\n x=1;\n y = 2;\n end\nendmodule\n"); +} + +#[test] +fn a_selection_ending_on_the_end_line_takes_only_the_statements_it_covers() { + let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\n assign a=b;\nendmodule\n"; + let out = fixed(src, "4-5"); + assert_eq!(middle(src, &out, 4, 4), " y = 2;\n"); +} + +#[test] +fn the_end_line_alone_takes_the_unit_it_closes() { + let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\n assign a=b;\nendmodule\n"; + let out = fixed(src, "5"); + assert_eq!(middle(src, &out, 2, 5), " always @(*) begin\n x = 1;\n y = 2;\n end\n"); +} + +#[test] +fn a_selection_starting_on_the_first_line_takes_the_whole_unit() { + let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\n assign a=b;\nendmodule\n"; + let out = fixed(src, "2-3"); + assert_eq!(middle(src, &out, 2, 5), " always @(*) begin\n x = 1;\n y = 2;\n end\n"); +} + +#[test] +fn blank_lines_alone_change_nothing() { + let src = "module m;\n wire a;\n\n\n wire b;\nendmodule\n"; + assert_eq!(select(src, "3-4"), src); +} + +#[test] +fn leading_and_trailing_comments_travel_with_their_unit() { + let src = "module m;\n always @* begin\n // why\n x=1; // what\n y=2;\n end\nendmodule\n"; + let out = fixed(src, "4"); + assert_eq!(middle(src, &out, 3, 4), " // why\n x = 1; // what\n"); +} + +#[test] +fn a_comment_after_begin_is_not_line_clean_and_the_parent_is_taken() { + let src = "module m;\n always @* begin // note\n x=1;\n end\nendmodule\n"; + let out = fixed(src, "3"); + assert_eq!(middle(src, &out, 2, 4), " always @(*) begin\n // note\n x = 1;\n end\n"); +} + +#[test] +fn two_statements_on_one_line_are_taken_together() { + let src = "module m;\n always @* begin\n x=1; y=2;\n z=3;\n end\nendmodule\n"; + let out = fixed(src, "3"); + assert_eq!(middle(src, &out, 3, 3), " x = 1;\n y = 2;\n"); + assert!(out.contains(" z=3;\n"), "{out}"); +} + +#[test] +fn a_selection_across_two_branches_takes_the_whole_if() { + let src = "module m;\n always @* begin\n if (a) begin\n x=1;\n end else begin\n y=2;\n end\n end\nendmodule\n"; + let out = fixed(src, "4-6"); + let mid = middle(src, &out, 3, 7); + assert_eq!(mid, " if (a) begin\n x = 1;\n end else begin\n y = 2;\n end\n"); +} + +// ------------------------------------------------------------------ +// Fences +// ------------------------------------------------------------------ + +#[test] +fn a_fence_inside_the_target_is_emitted_as_written() { + let src = "module m;\n always @* begin\n x=1;\n // lucisv: off\n y = 2;\n // lucisv: on\n z=3;\n end\nendmodule\n"; + let out = fixed(src, "2-8"); + assert!(out.contains(" y = 2;\n"), "{out}"); + assert!(out.contains(" x = 1;\n") && out.contains(" z = 3;\n"), "{out}"); +} + +#[test] +fn a_fence_around_the_target_wins() { + let src = "module m;\n // lucisv: off\n always @* begin\n x=1;\n end\n // lucisv: on\nendmodule\n"; + assert_eq!(select(src, "4"), src); + assert_eq!(select(src, "3-5"), src); +} + +#[test] +fn a_fence_straddling_the_target_trims_the_fenced_units() { + let src = "module m;\n always @* begin\n a=1;\n b=2;\n // lucisv: off\n c = 3;\n // lucisv: on\n d=4;\n end\nendmodule\n"; + // Lines 3-6 meet a, b, and c (fenced): c is trimmed off the end. + let out = fixed(src, "3-6"); + assert_eq!(middle(src, &out, 3, 4), " a = 1;\n b = 2;\n"); + assert!(out.ends_with( + " // lucisv: off\n c = 3;\n // lucisv: on\n d=4;\n end\nendmodule\n" + )); + // Lines 6-8 meet c (fenced) and d — whose extent starts at `on`: both go. + assert_eq!(select(src, "6-8"), src); +} + +// ------------------------------------------------------------------ +// Deferral to `format_range` +// ------------------------------------------------------------------ + +#[test] +fn a_module_header_or_whole_module_selection_is_format_range() { + let src = "module m(input a,output b);\n wire x;\n assign x=a;\nendmodule\nmodule n;\nendmodule\n"; + for spec in ["1", "1-4", "1-6", "4", "2-5"] { + let lines = LineRanges::parse(spec).expect("spec"); + let range = format_range(src, &Config::default(), &lines).expect("range formats"); + assert_eq!(select(src, spec), range, "spec {spec}"); + } +} + +// ------------------------------------------------------------------ +// Files that do not parse +// ------------------------------------------------------------------ + +const BROKEN: &str = "\ +module m; + always @* begin + x=1; + end + assign y = ; +endmodule +"; + +#[test] +fn an_error_outside_the_target_does_not_stop_it() { + let out = fixed(BROKEN, "3"); + assert_eq!(middle(BROKEN, &out, 3, 3), " x = 1;\n"); +} + +#[test] +fn an_error_inside_the_target_refuses() { + let err = select_with(BROKEN, "5", &Config::default()).expect_err("refused"); + assert!(err.contains("syntax error") || err.contains("parse"), "{err}"); +} + +// ------------------------------------------------------------------ +// Idempotence and multiple ranges +// ------------------------------------------------------------------ + +#[test] +fn formatting_the_same_target_twice_changes_nothing() { + for spec in ["3-12", "6-10", "4", "8", "13"] { + fixed(FOUR, spec); + } +} + +#[test] +fn two_ranges_lay_out_two_targets_and_nothing_between() { + let src = "module m;\n always @* begin\n x=1;\n y=2;\n z=3;\n end\nendmodule\n"; + let out = fixed(src, "3,5"); + assert_eq!( + out, + "module m;\n always @* begin\n x = 1;\n y=2;\n z = 3;\n end\nendmodule\n" + ); +} + +#[test] +fn overlapping_targets_are_reselected_from_their_hull() { + // `4` selects the inner statement, `2` the always holding it. + let src = "module m;\n always @* begin\n x=1;\n y=2;\n end\nendmodule\n"; + let out = fixed(src, "2,4"); + assert_eq!(out, "module m;\n always @(*) begin\n x = 1;\n y = 2;\n end\nendmodule\n"); +} + +// ------------------------------------------------------------------ +// Masked-corruption attacks on the splice +// ------------------------------------------------------------------ + +/// Either a correct result (equivalent to the input, a fixed point) or a +/// refusal — never silently wrong. +fn correct_or_refused(src: &str, spec: &str) -> Option { + let out = select_with(src, spec, &Config::default()).ok()?; + verify_equivalence(src, &out).expect("the result is equivalent to the input"); + assert_eq!(select(&out, spec), out, "and a fixed point"); + Some(out) +} + +#[test] +fn a_trailing_comment_on_the_last_line_survives() { + let src = "module m;\n always @* begin\n x=1; /* a */ /* b */\n end\nendmodule\n"; + let out = correct_or_refused(src, "3").expect("formats"); + assert!(out.contains("/* a */") && out.contains("/* b */"), "{out}"); +} + +#[test] +fn crlf_line_endings_are_kept() { + let src = "module m;\r\n always @* begin\r\n x=1;\r\n y=2;\r\n end\r\nendmodule\r\n"; + let out = correct_or_refused(src, "3-4").expect("formats"); + assert_eq!( + out, + "module m;\r\n always @* begin\r\n x = 1;\r\n y = 2;\r\n end\r\nendmodule\r\n" + ); +} + +#[test] +fn crlf_with_a_trailing_comment_on_the_last_line_keeps_every_line_ending() { + // QA finding 1: the `\r` after a trailing `//` comment is the line + // ending, not part of the unit, so the splice leaves it in place. + let src = "module m;\r\n initial begin\r\n a = 1; // c\r\n b = 2; // d\r\n end\r\nendmodule\r\n"; + let out = correct_or_refused(src, "3-4").expect("formats"); + assert_eq!(out, src.replace("b = 2", "b = 2")); + let out = correct_or_refused(src, "4").expect("formats"); + assert_eq!(out, src.replace("b = 2", "b = 2")); +} + +#[test] +fn a_multi_line_block_comment_inside_the_target_survives() { + let src = + "module m;\n always @* begin\n /* one\n two */\n x=1;\n end\nendmodule\n"; + let out = correct_or_refused(src, "2-6").expect("formats"); + assert!(out.contains("/* one\n two */"), "{out}"); +} + +#[test] +fn a_multi_line_string_inside_the_target_is_kept_or_refused() { + let src = + "module m;\n initial begin\n $display(\"a\\\n b\");\n x=1;\n end\nendmodule\n"; + if let Some(out) = correct_or_refused(src, "2-6") { + assert!(out.contains("\"a\\\n b\""), "{out}"); + } +} + +#[test] +fn a_target_at_the_end_of_a_file_without_a_final_newline() { + let src = "always @* begin\n x=1;\nend"; + let out = correct_or_refused(src, "2").expect("formats"); + assert_eq!(out, "always @* begin\n x = 1;\nend"); + let src = "wire a;\nassign b=a;"; + let out = correct_or_refused(src, "2").expect("formats"); + assert_eq!(out, "wire a;\nassign b = a;"); +} + +#[test] +fn multi_byte_characters_before_the_target_do_not_shift_it() { + let src = "module m;\n // café — ünïcode\n wire a; // ß\n assign b=a;\nendmodule\n"; + let out = correct_or_refused(src, "4").expect("formats"); + assert_eq!(middle(src, &out, 4, 4), " assign b = a;\n"); +} + +#[test] +fn the_safety_net_rejects_a_mis_spliced_output() { + // An off-by-one at the end of the splice duplicates the `;`; at the + // start it drops the trailing comment's first byte. Both must be caught. + let src = "module m;\n always @* begin\n x=1; // c\n end\nendmodule\n"; + let duplicated = "module m;\n always @* begin\n x = 1;; // c\n end\nendmodule\n"; + assert!(verify_equivalence(src, duplicated).is_err()); + let dropped = "module m;\n always @* begin\n x = 1; c\n end\nendmodule\n"; + assert!(verify_equivalence(src, dropped).is_err()); + let crlf = "module m;\r\n always @* begin\r\n /* one\r\n two */\r\n x=1;\r\n end\r\nendmodule\r\n"; + let lost_comment_line = + "module m;\r\n always @* begin\r\n /* one */\r\n x = 1;\r\n end\r\nendmodule\r\n"; + assert!(verify_equivalence(crlf, lost_comment_line).is_err()); +} + +#[test] +fn a_column_zero_directive_does_not_set_the_indentation_of_the_code_it_guards() { + let src = "module m;\n`ifdef A\n wire a;\n`endif\n wire b;\nendmodule\n"; + let out = fixed(src, "2-4"); + // The code says where the block stands; the directives are indented with + // it, as a whole-file run indents them. + assert_eq!(middle(src, &out, 2, 4), " `ifdef A\n wire a;\n `endif\n"); +} diff --git a/docs/features/range-formatting/README.md b/docs/features/range-formatting/README.md index cb0a6f3..3dd3688 100644 --- a/docs/features/range-formatting/README.md +++ b/docs/features/range-formatting/README.md @@ -364,6 +364,11 @@ is a leaf, as it was for fences. ## Status / TODO +- Editors' "Format Selection" no longer uses this engine: since TODO §66.2 + the LSP range requests call `format_selection`, which lays out the smallest + sibling run in place — see `docs/features/selection-formatting/README.md`. + The CLI's `--lines` still runs here, unchanged. + - [x] `range.rs`: `LineRanges` (`parse`/`new`, sorted+merged, reversed and zero refused, past-EOF clamped) with unit tests for every spelling. - [x] `range.rs`: `Pick`/`Selection`/`Plan`/`Split`, the `Planner` walk in diff --git a/docs/features/selection-formatting/README.md b/docs/features/selection-formatting/README.md new file mode 100644 index 0000000..04c1b70 --- /dev/null +++ b/docs/features/selection-formatting/README.md @@ -0,0 +1,348 @@ +# selection-formatting + +## Goal + +VS Code's "Format Selection" (`textDocument/rangeFormatting`) failed more than +half the time on the selections people actually make — one whole `always` +block, one whole `case`, usually nested in blocks the selection does not +cover. The request went to `format_range` (the CLI's `--lines`), whose unit is +a whole module-level item laid out at formatter depth: selecting a `case` +re-laid the whole `always`, a block in a four-space or tab-indented file came +back re-indented to two spaces, a selection inside `generate` or a function +re-laid the whole region, and any parse error anywhere refused the request. +`format_selection` lays out **only the smallest run of sibling items or +statements the selection covers**, at the indentation its first line was +written at, and splices it into otherwise untouched bytes. The owner's rule: +don't worry about the parent; the selected block keeps the indentation level +it starts at; the result must be functionally the same. + +## Semantics + +### Scopes and units + +A *scope* is a sibling list exactly as `fence.rs` defines one: item lists +(file, module, package, generate region, generate `begin`…`end`, class) and +statement lists (`begin`…`end`, `fork`…`join*`, function and task bodies). A +single-statement body (`if (a) x = 1;`, `always @* x = 1;`) or a block-less +generate item is not a scope; it is walked *through* to the scopes it reaches. +A *unit* is one item or statement with its whole extent: first leading comment +or attribute through the comments written after it on the same line. + +### Locating the target (`selection/locate.rs`) + +For one selected line span, starting at the file scope: + +1. Take the units whose lines meet the span. Blank lines select nothing; a + span meeting no unit changes nothing. +2. If exactly one unit is met, the span touches neither its first line nor its + last, and exactly **one** of its nested scopes has a unit the span meets, + descend into that scope and repeat. + *(Lead ruling 2026-11-09, QA note 2: only the unit's **first** line is + asked about. A selection over a block's last statements and its closing + `end` descends and lays out those statements; the closing line alone + meets no nested unit and still names the unit it closes.)* +3. Otherwise the target is the run of consecutive units met — a partial + selection expands to whole units. +4. **Fences outrank the selection.** Units a fenced region *of this scope* + reaches (a region nested inside a unit's own code does not count) are + trimmed from both ends of the run; an empty run changes nothing. A region is + never half inside the splice. +5. **Line-clean or one level up.** The run must be replaceable by whole lines: + only spaces/tabs before its first byte on that line, only whitespace after + its last byte on that line, no sibling unit's extent and no dangling comment + of the scope inside it. If not (`begin // note` makes the first statement's + leading comment start on the `begin` line; `x = 1; y = 2;` with only `x` + selected is fine because both are met), the enclosing unit is the target, + checked the same way. At the file scope there is nowhere to go up to, and + the request is deferred. +6. **Big containers defer.** A run holding a `module`/`interface`/`program` + or `package` item goes to `format_range(source, config, lines)` unchanged — + header/footer splitting and whole-file selections behave exactly as before. + +The located target is recorded as a **path** — `(unit index, child scope +index)` per descent, plus the run's start and length — not as bytes or lines. + +### Layout and splice (`selection/mod.rs`, `format::print_run`) + +- `print_run` builds the ordinary `Fmt` over the whole source (fenced regions + from `fence::collect`, no range splits) and calls `item_seq(run, depth)` or + `stmt_seq(run)` on the sub-slice. `depth` is the AST depth `item_kind` + would pass down (it only feeds the alignment width budget). +- The **base indentation** is the leading whitespace of the run's first unit's + line, as written (tabs included) — or, when that unit is a compiler directive + and a later unit is not, the later unit's: directives are commonly written at + column 0 while the code they guard is indented, and the code says where the + block stands. The directive is then indented with the block, as a whole-file + run indents it. +- `Printer::print_at(doc, base)` starts the text with `base`, writes it after + every line break before the indentation, and charges its width against the + line budget (a tab counts as one indent width). `Doc::Verbatim` and + `Doc::Inline` keep their own absolute indentation, and a line holding nothing + but indentation is emptied so blank lines never keep the base's tabs. + `print` is `print_at(doc, "")`, byte for byte the old printer. +- The splice replaces `line start of the first unit .. end of the last unit's + extent` with the printed text and nothing else: blank lines at the boundary, + the rest of the last line and the file tail (final newline or not) are + untouched. In a file whose lines end in `\r\n` (judged at the target), every + line break the printer wrote becomes `\r\n`; source text copied through + keeps the `\r\n` it had. + +### Several ranges + +Each merged span of `LineRanges` selects its own target. Targets whose byte +ranges overlap are replaced by the target of the hull of their spans, until +none overlap. They are spliced bottom-up and verified together, so the +all-or-nothing contract covers the whole request. If any span defers, the +whole request goes to `format_range`. + +### Safety net (unchanged) + +`verify_equivalence(source, output)` over the whole file, then convergence by +**replaying the targets**: the output is parsed the same way, each path is +resolved in its tree, laid out and spliced again, and `verify_convergence` +must find nothing to change. `verify.rs` is not touched. Any failure — a target +that cannot be found again or cut cleanly in the output included — is an error +and no edit (`FormatError::Selection` for the selection's own refusals). + +### A file that does not parse + +`parse_source` first. If it fails, `parse_source_tolerant` builds the tree and +the target is located in it the same way. The request is refused when any +parse diagnostic lies inside `line start .. end` of a target, or any unit of +the target (at any depth reachable through the scope walk) is an `Error` node. +The replay parses the output the same way and applies the same check. + +**Verdict:** sound and useful. Sound because the layout is token-verified over +the whole file like every other path: recovery can only mis-guess the *nesting* +around a target (an `assign` after a missing `end` becomes a statement), which +changes at most how a clean run is laid out, never its tokens — and the target +itself is required to be free of diagnostics and error nodes. Useful because +in the corpus sweep below, with a broken line injected in every file, 75 % of +selections still answered. + +## Assumptions + +- A tab in the base indentation is worth one indent width for the line budget. + The printer cannot know the reader's tab stop; only group breaking depends + on it, and the replay uses the same rule, so it cannot break convergence. +- Comment `col` is a byte column with a tab counting 1, so `raw_lines`' + dedent-by-column cancels a base containing tabs exactly as it cancels + spaces (exercised by the tab tests). +- A parse diagnostic's span is the token the parser gave up on, not the extent + of what it swallowed; the `Error`-node walk covers the latter at list level. + An error node nested in an expression or header list is assumed to come with + a diagnostic inside it. The safety net backs both. +- The alignment of a sub-slice is planned over the sub-slice only (a run + holding half of an alignment group aligns that half). Stable under replay. +- With `uvm-utils-indent` on, a run holding a `` `uvm_*_utils_begin `` without + its `_end` indents what follows it inside the run, as a whole-file run would. + +## Handshakes + +- **Consumes** `fence::collect`, `fence::region_at`-shaped regions, + `fence::with_trailing_comments` (already `pub(crate)`), `Fmt::item_seq` / + `Fmt::stmt_seq` (already `pub(super)` within `format`), `format_range`, + `verify_equivalence`, `verify_convergence`, `vlog_parser::parse_source`, + `parse_source_tolerant`. +- **Provides** `vlog_formatter::format_selection(source, config, lines)` and + `Printer::print_at(doc, base)`; `format::print_run` / `format::Run` + (`pub(crate)`); a new `FormatError::Selection(String)` variant (every match + on `FormatError` in the workspace already has a catch-all arm). +- **Changed for the server:** `lucisv_server::format::{range_formatting, + ranges_formatting}` now call `format_selection`. `on_type.rs`'s + semicolon trigger calls `format::range_formatting`, so it changes too. +- **Request (not done — outside this lane's files): `crates/lucisv_server/src/on_type.rs`.** + Two of its unit tests pin behaviour this design changes on purpose, and fail: + 1. `a_semicolon_in_a_buffer_the_engine_refuses_answers_nothing_at_all` + (line ~1175) — its buffer's error (`wire ;`, line 3) is *outside* the + keystroke's statement (line 2), so the request now formats line 2 (design + step 7). Proposed fix: put the error on the keystroke's own line, e.g. + `"module m;\n wire a = ;\nendmodule\n"` with the `;` at line 1, + char 13 — the change made to the twin test in + `server/tests/formatting.rs`. + 2. `a_semicolon_at_eof_with_no_trailing_newline_still_lays_out_its_line` + (line ~1210) — the splice no longer adds a final newline (design step 5); + the expected text becomes `"module m;\n wire a;\nendmodule"` and the + comment above it should say the file tail is untouched. + The module doc at line ~64 ("`format_range` selects by …") is also stale. +- The CLI `--lines` keeps calling `format_range`; `range.rs` is unchanged. + +## Status / TODO + +- [x] `printer.rs`: `print_at(doc, base)`; `print` delegates with `""`. + Whole-file output byte-identical (snapshot + idempotency suite green + before any selection test existed). +- [x] `format/mod.rs`: `Run`, `print_run`, `FormatError::Selection`. +- [x] `selection/scope.rs`: scopes, units, extents, the nested-scope walk. +- [x] `selection/locate.rs`: locate (descend, fences, line-clean, defer), + path resolution, error-node walk, base indentation. +- [x] `selection/mod.rs`: `format_selection`, multi-target hull merging, + bottom-up splice, CRLF, tolerant path, replay. +- [x] `tests/selection.rs` — 33 tests (incl. the directive-base test). +- [x] Server: `ranges_formatting` → `format_selection`; 3 handler tests in + `format.rs`, 1 dispatch test + 1 updated in `server/tests/formatting.rs`, + 1 e2e leg. +- [x] `on_type.rs` test updates — Handshake request above (applied by the lead, 2026-11-09). + +## Work log + +### 2026-11-09 — dev + +- Built as designed, as a directory module (`selection/{mod,scope,locate}.rs`, + each well under 300 production lines) rather than one file. +- **Deviation 1 — multi-range lives in the engine.** The design put the + per-span targets and hull re-selection in the LSP handler; `format_selection` + takes a `LineRanges` anyway, so it does that itself and verifies all targets + in one pass. The server only swaps `format_range` for `format_selection`. +- **Deviation 2 — descent needs exactly one reached child scope.** A span + covering both branches of an `if` reaches two scopes; it takes the `if` + rather than one branch. +- **Deviation 3 — directive base.** The base indentation is taken from the + first non-directive unit of the run; found by a scratch run where a run + starting at a column-0 `` `ifdef `` pulled the guarded code to column 0. +- **Fence check** counts only regions opened in the run's own scope; a region + nested in a unit's code is laid out verbatim by the printer as in a + whole-file run, so it does not trim the unit. +- **`FormatError::Selection(String)`** added for refusals that are neither a + parse error nor a verification failure (a parse error inside the target, a + target that cannot be found again). +- **Server tests updated:** `a_keystroke_the_engine_refuses_is_answered_with_ + silence_and_not_a_popup` (`server/tests/formatting.rs`) — its buffer's error + was on another line, which no longer refuses; the error now sits on the + keystroke's own line. No `format.rs` test pinned over-reach: the existing + range tests select whole module items and come out identical. +- **Corpus sweep** (scratch test, release, under `tools/guard.sh`, not + committed): 428 formattable files of `corpus/{common_cells,ibex,picorv32, + opentitan/hw/ip}` (every ~2nd file), windows of 1, 2, 4 and 8 lines at a + stride of 5+w: **33 438 calls, 21 473 changed, 11 965 unchanged, 0 + verification errors, 0 selection refusals, 0 source errors.** Same files + with ` @@ broken = ;` injected at the middle line: 33 626 calls, 14 159 + changed, 10 954 unchanged, 4 281 refused because the target holds the + error (or recovery swallowed the rest of the file into an error node), 4 232 + source errors (the span reached a module-level unit and was deferred to + `format_range`, which parses strictly), 0 verification errors. + +## QA log + +### 2026-11-09 — QA + +**Gates (main checkout, all guarded, no guard kills):** `cargo fmt --all --check` clean; +`cargo clippy --workspace --all-targets` 0 warnings; `cargo test`: `-p vlog_formatter` +347 passed / 0 failed, `-p lucisv_server` 1881 passed / 0 failed / 40 ignored, `-p lucisv` +143 passed / 0 failed. `verify.rs`, `range.rs`, `fence.rs`, `crates/lucisv` untouched +(`git diff --stat`). No source or test files edited by QA; all experiments in a throwaway copy +(deleted). + +**Hand-written attack set:** 221 (source, selection) cases in 2/3/4-space and tab files +(nested `generate for` / `always_ff` / `case`, mis-indented parents, `if`/`else` chains, `for`, +`fork`/`join`, function and task bodies, case-item blocks, class methods, gen-if/gen-case), +comments everywhere, `` `define `` with `\` continuations, `` `ifdef `` at run boundaries, +escaped identifiers, attributes, labels, fences (enclosing / unmatched / straddling), CRLF, no +final newline, multibyte, mixed whitespace, tabs, empty file, past-EOF, one-line/cursor-only, +statements sharing a line, multi-range hulls, files with parse errors. Every window of each +case was then run (24 719 calls): **0 panics, 0 token-nonequivalent outputs (independent +`verify_equivalence`), 0 non-idempotent results, 0 verification errors except the CRLF finding +below.** A "far" detector (changed lines not touching the selection) fired 573 times; every +one inspected was the target growing to its whole unit (selection touching a unit's first/last +line, a leading `///` comment line, or the module header deferral) as the spec says. + +**Corpus sweep** (release, 409 files of `corpus/`, 12 random windows of 1-12 lines each, +fixed seed): clean 4 908 calls: 3 611 changed / 1 265 unchanged / 32 refused / 0 verification +errors / 0 panics / 0 non-equivalent. One random line replaced by ` @@ broken ( ;` (4 908 +calls): 1 005 changed / 617 unchanged / 3 286 refused (error inside target or swallowed by +recovery) / 0 verification errors / 0 panics / 0 non-equivalent. CRLF-converted (818 calls): 594 +changed / 212 unchanged / 7 refused / **5 verification errors** and 1 mixed-EOL output (finding 1). +(A shifted-window re-run flagged 18 "non-idempotent" calls; all were artifacts of the shifted +window landing on the module header, i.e. a different target — not a defect.) + +**Sabotage (copy only):** (A) splice tail skips the line after the target: 27 of 33 +`tests/selection.rs` tests fail; runtime net alone rejected 14 294 of 24 719 calls, 0 corrupted +outputs returned. (B) base indentation prefixed onto every `Doc::Verbatim`: 1 test fails +(`a_fence_inside_the_target_is_emitted_as_written`); runtime net (replay convergence) +rejected 283 calls, 0 corrupted outputs returned; the whole-file suite cannot see it (empty +base) — so one test is all that pins it. (C) fence trimming removed: 2 tests fail +(`a_fence_around_the_target_wins`, `a_fence_straddling_the_target_trims_the_fenced_units`); +net rejected 241 calls. + +**Findings** + +- SHOULD-FIX 1 — CRLF file + target whose last line ends in a `//` comment loses its `\r`. + `print_run`'s `out.trim_end()` (`format/mod.rs`, `print_run`) strips the `\r` that the trailing + comment's text carries while `Unit::extent` (`scope.rs`) includes it in the replaced + bytes, so the line ends in a bare `\n`; the replay then often disagrees and the request is + *refused* ("formatting is not idempotent; line N changed from "" to """), otherwise the file + comes back with one bare-`\n` line. Repro: `"module m;\r\n initial begin\r\n a = 1; // c\r\n + b = 2; // d\r\n end\r\nendmodule\r\n"`, lines `3-4` -> Err; `3-3` of a one-statement + variant -> Err; corpus `opentitan/.../uart_tx_rx_vseq.sv` as CRLF, line `215-215` -> Ok with a + bare `\n` on line 215. The LF twin of each is fine. Safe (no corruption) but Windows files + with trailing comments cannot be range-formatted. +- NOTE 2 — selecting interior statements together with the parent's closing `end` (e.g. the + last statements of a generate `begin`…`end` plus its `end`) takes the whole parent: corpus + `common_cells/src/rr_arb_tree.sv` lines `310-319` re-lays 116..292. By design (step 2/3) + but it is the most common sloppy selection; consider whether the owner wants it. +- NOTE 3 — inner indentation comes from `Config::indent_width` (2 for the library default), + so the engine alone on a 4-space file gives a 4-space block with 2-space nesting inside + (`gen-4sp` cases); the server passes the editor `tabSize`, so with `indent_width = 4` the + owner's case comes out right (demo below). For tab files the nested levels are `\t…\t` plus + spaces (`\t\t\t\t case`), same as the whole-file printer's no-tab model. +- NOTE 4 — a selection spanning module-header ports and body items formats only the body + items (the header lines are not units); header-only selections defer to `format_range`. +- NOTE 5 — a column-0 directive in a run together with indented code is moved to the block's + indentation (`` `endif `` + next statement selected -> `` `endif `` indented while `` `ifdef `` + stays at column 0). Token-equivalent; cosmetic. +- NOTE 6 — with a missing `end` the tolerant tree nests later statements into the open block, so + they get laid out one level deeper than the (misplaced) `end` implies. Tokens identical. + I could not construct a counterexample where a wrong parse changes meaning: only whitespace + is chosen by layout, the token/comment stream is compared exactly, and line-sensitive + tokens (`` `define ``, directives, line comments) are tokens whose text includes their line. + +**Usability (owner's complaint)**, 4-space file, `generate for` -> `always_ff` -> `case`, +`indent_width = 4`: selecting exactly the `case` lines (6-10), exactly the `always_ff` lines +(5-11), one middle line (8) and the three case items (7-9) all yield the same correct result, +and every byte outside the `case` is unchanged: + + before after (selection 8-8) + always_ff @(posedge clk) begin always_ff @(posedge clk) begin + case (sel[i]) case (sel[i]) + 2'b00: q[i]<=a; 2'b00: q[i] <= a; + 2'b01 : q[i] <= b; 2'b01: q[i] <= b; + default:q[i]<=c; default: q[i] <= c; + endcase endcase + end end + +**Not verified:** the editor (VS Code / Vim) end to end; opentitan sweep and the byte-identity +corpus gates (the 347-test formatter suite incl. snapshots is green, which is the evidence for +`print_at("")` == old `print`); files over 120 KB; non-ASCII-heavy corpora beyond the +hand-written multibyte cases; `--release` gate script `tools/gates.sh`. + +## Review + +**2026-11-09 — lead. Verdict: accepted, with two fixes of mine after QA.** + +1. **The design is a splice, not a second inverted fence**, and that is what + answers the owner's complaint: the target keeps the indentation it was + written at because nothing above it is laid out at all. The safety + argument is the old one, unchanged — whole-file `verify_equivalence` + (`verify.rs` untouched, so invariant #4 does not apply) plus a replay of + the located target. QA's three sabotages were each caught, with zero + corrupted outputs returned in 24,719 hand-case calls and 10,634 corpus + calls; no panic. +2. **QA SHOULD-FIX 1 (CRLF), fixed by the lead.** `Unit::extent` counted the + `\r` after a trailing `//` comment as part of the unit, so the splice ate + it. The extent now stops before it (`selection/scope.rs`); `print_run` + trims spaces and newlines only, as `render` does. Pinned by + `crlf_with_a_trailing_comment_on_the_last_line_keeps_every_line_ending`. +3. **QA NOTE 2, ruled: only the first line stops the descent.** A selection + over a block's last statements and its `end` re-laid 177 unselected lines + of `rr_arb_tree.sv`. It now lays out the statements it covers; the `end` + line alone still names the unit it closes. Three tests pin the three + cases. +4. **`on_type.rs`** (the dev's Handshake request): accepted. The `;` trigger + shares the engine, so an error elsewhere in the buffer no longer silences + it and the file tail is not normalized; two tests updated, one added. +5. **Accepted as they are**: the dev's four deviations; NOTE 3 (nested levels + use `indent_width`, which the server takes from the editor's `tabSize`); + NOTE 4 and NOTE 5 (cosmetic, token-equivalent). +6. **Open**: the LSP reply is still one whole-document edit; the engine now + knows the exact bytes it replaced, so a minimal edit is possible. Not + verified in a running editor.