Files
lucisv/crates/vlog_formatter/src/selection/mod.rs
T
Guoliang ChenandClaude Mythos 5.2 80017a59f2
release / build-and-publish (push) Successful in 5m22s
Release 0.65.5: named formatting styles
TODO §71.5. One setting picks a house layout — [format] style in
lucisv.toml, --style, the lucisv.format.style drop-down, the server and MCP:
lucisv (default), google, lowrisc, ansi, microsoft, nxp, and auto. Seven
layout rules (indent, width, begin placement, else placement, else after a
labelled end, one-per-line lists, list indent, alignment), one row per style
in one table in crates/vlog_formatter/src/style.rs. google and lowrisc follow
those published guides; ansi, microsoft and nxp are lucisv's guesses and say
so. auto formats with each preset and keeps the result that changes the
fewest lines (crates/vlog_formatter/src/auto.rs); the language server
remembers each document's preset (lucisv_server/src/auto_style.rs) so
selection and on-type formatting do not repeat the search. The style is part
of the format cache key.

Proof: default output byte-identical to 0.65.4 on 4 921 files (corpus +
OpenTitan hw) against an independently rebuilt 0.65.4; every style formatted
three times over the same files with no verification error, crash, token or
comment difference (independent lexer) or second-run change. verify.rs is
untouched.

Dev (three rounds), QA (two rounds, pass with findings) and lead review are
in docs/features/format-styles/README.md. Three one-line calls were added to
lucisv_server/src/server/notification.rs for the memory's invalidation.
TODO.md files the pre-existing bugs QA met on the way.

Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.65.5) and
editors/vscode/CHANGELOG.md.

Gates: tools/gates.sh PASS on this tree; vlog_formatter 376/0,
lucisv_server 1996/0, corpus 814/6.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 07:03:20 -08:00

243 lines
8.9 KiB
Rust

//! 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.
///
/// Under `style = "auto"` the style is the one the *whole* file is closest
/// to, so a selection lays out exactly as a whole-file format would.
///
/// Same stack requirement as [`crate::format_source`].
pub fn format_selection(
source: &str,
config: &Config,
lines: &LineRanges,
) -> Result<String, FormatError> {
let config = &crate::auto::concrete(source, config);
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<String, FormatError> {
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<ParseDiagnostic>,
}
impl Tree {
fn parse(src: &str) -> Result<Tree, vlog_parser::Error> {
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<Vec<Target>, Defer> {
let mut picked: Vec<Picked> = 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<Option<Picked>, 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<String> {
let mut placed = targets.iter().map(|t| resolve(src, root, t)).collect::<Option<Vec<_>>>()?;
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
}