Files
lucisv/crates/vlog_formatter/src/selection/mod.rs
T

271 lines
10 KiB
Rust

// Author: Guoliang Chen, a Senior Digital Design Engineer
//! 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, format_range_with_parsed, print_run, Config, FormatError};
use crate::range::LineRanges;
use crate::verify::{verify_convergence, verify_equivalence_items, 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, cached) = crate::auto::resolve_concrete(source, config);
let config = &config;
let (tree, regions, before_items) = match cached {
Some(p) => (Tree { file: p.file, diagnostics: Vec::new() }, Some(p.regions), Some(p.items)),
None => (Tree::parse(source).map_err(FormatError::Source)?, None, None),
};
let Some(root) = Scope::root(&tree.file) else {
return match (regions, before_items) {
(Some(regions), Some(items)) => format_range_with_parsed(
source,
config,
lines,
&crate::format::ParsedSource { file: tree.file, regions, items },
),
_ => format_range(source, config, lines),
};
};
let regions = regions.unwrap_or_else(|| fence::collect(source, &tree.file));
let locator = Locator::new(source, regions.clone());
let Ok(targets) = select(&locator, root, source, lines) else {
return match before_items {
Some(items) => format_range_with_parsed(
source,
config,
lines,
&crate::format::ParsedSource { file: tree.file, regions, items },
),
None => 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"))?;
match before_items {
Some(items) => verify_equivalence_items(&items, &output)?,
None => crate::verify::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
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com