range-formatting: --lines M-N[,M-N...] formats only the top-level
items intersecting the ranges; modules/packages split head/body/tail
with independent decisions, everything else is atomic, and
unselected units are emitted as merged verbatim source slices (the
run-merge is load-bearing: per-item slices let separators collapse
blank lines between untouched items). Convergence via Selection
replay -- same-selection re-runs are fixed points, sound because the
equivalence check has already proven token identity; QA's sabotage
of the replay failed immediately on real RTL. The honest limit
(same line numbers can sweep in a neighbor after lines move;
449/8236 corpus trials, all settled next run) is measured and
pinned. Fence wins over range; alignment groups split at verbatim
boundaries; cache fully bypassed; LSP rangeFormatting advertised and
consumes only lines (no UTF-16 column math); tools/vfmt-changed.sh
derives ranges from git diff. Default behavior provably unchanged
(TSV md5 + all-578-file byte-compare vs a pre-round binary).
lint-rules-2: visit.rs walks class bodies (closing the classes
handshake; +6 real findings in UVM code), five new rules with
evidence-based defaults -- parameter/enum/struct-union-name-style ON
with Verible's exact names and published defaults (vendored waivers
now honored), module-name-style OFF (Verible has no such rule; the
brief's premise was checked and corrected), wire-reg-mixup ON (0
corpus noise in .v, 209 findings on a .sv rename -- both zeroes
proven). rules_markdown() generates the rule reference; 13 rules
total, zero CLI/server wiring needed.
Also: lead notes in classes and shared-fence-filter READMEs
documenting the fence asymmetry lint-rules-2 QA found (a fence in a
class body protects fixes via the scan backstop even though the
formatter ignores it there).
768 workspace tests. Dev: 2 Opus agents; QA: 2 Sonnet agents;
reviews in docs/features/{range-formatting,lint-rules-2}/README.md.
Co-Authored-By: Claude Fable 5 <[email protected]>
412 lines
19 KiB
Rust
412 lines
19 KiB
Rust
//! `textDocument/formatting` and `textDocument/rangeFormatting`.
|
|
//!
|
|
//! The formatter's contract is all-or-nothing (CLAUDE.md invariant #1), and
|
|
//! these handlers keep it: either one whole-document edit built from verified
|
|
//! output, or no edit at all and an error for the user to read. That holds for
|
|
//! the range request too — its output is verified over the whole buffer, and
|
|
//! what makes it a *range* format is which constructs it laid out, not which
|
|
//! bytes it was allowed to replace.
|
|
|
|
use std::path::Path;
|
|
|
|
use lsp_types::{FormattingOptions, Range, TextEdit};
|
|
use vfmt_core::config::{Discovery, FileConfig};
|
|
use vlog_formatter::{format_range, format_source, Config, LineRanges};
|
|
|
|
use crate::state::Document;
|
|
|
|
/// Indent widths a client may ask for. The same 1..8 range `vfmt.toml`'s own
|
|
/// `indent` key allows, so the two agree.
|
|
const INDENT_RANGE: std::ops::RangeInclusive<u32> = 1..=8;
|
|
|
|
/// What to format a buffer with, and the config problem to tell the user
|
|
/// about. The two are separate because a broken `vfmt.toml` must not stop the
|
|
/// buffer from being formatted.
|
|
pub struct Settings {
|
|
/// The settings to format with — the fallback defaults when `problem` is
|
|
/// set.
|
|
pub config: Config,
|
|
/// The `vfmt.toml` error governing this buffer, if there is one.
|
|
pub problem: Option<String>,
|
|
}
|
|
|
|
/// Resolve the settings governing a buffer.
|
|
///
|
|
/// Precedence is **`vfmt.toml` > the client's tab size > the built-in
|
|
/// default**, which is *not* the CLI's flag-beats-config order, and
|
|
/// deliberately so: a CLI flag is typed on purpose for one run, while
|
|
/// `FormattingOptions::tab_size` is sent on every request whether or not the
|
|
/// user ever chose it (it is the editor's own default, or its guess from the
|
|
/// file). Letting an editor default silently beat a checked-in `vfmt.toml`
|
|
/// would make format-on-save disagree with CI's `vfmt --check` — the exact
|
|
/// divergence lifting the config into `vfmt_core` exists to remove. Where the
|
|
/// config is silent the tab size still wins over the built-in default, so a
|
|
/// project with no `vfmt.toml` behaves as it did before.
|
|
pub fn settings_for(doc: &Document, options: &FormattingOptions) -> Settings {
|
|
let (file, problem) = discover(doc.path.as_deref());
|
|
Settings { config: config_from(&file, options), problem }
|
|
}
|
|
|
|
/// Format a buffer.
|
|
///
|
|
/// `Ok(None)` means "nothing to do" — the buffer is already formatted, and an
|
|
/// edit that changes nothing still moves the cursor in some editors. `Err`
|
|
/// carries the formatter's own message; the caller surfaces it, and must not
|
|
/// invent an edit from it.
|
|
pub fn formatting(doc: &Document, config: &Config) -> Result<Option<TextEdit>, String> {
|
|
let formatted = format_source(&doc.text, config).map_err(|e| e.to_string())?;
|
|
if formatted == doc.text {
|
|
return Ok(None);
|
|
}
|
|
Ok(Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted }))
|
|
}
|
|
|
|
/// Format the constructs a selection reaches, and nothing else.
|
|
///
|
|
/// The protocol's `Range` is a half-open span of UTF-16 positions; the engine
|
|
/// wants 1-based inclusive *lines*, so only the line numbers survive the
|
|
/// conversion. An end position at character 0 still names its line — an
|
|
/// editor's "select these three lines" ends at the start of the fourth — so
|
|
/// a range that stops at a line's very beginning does not drag that line in
|
|
/// unless it is also where the range started.
|
|
///
|
|
/// The reply is still one whole-document edit: the engine's contract is
|
|
/// all-or-nothing over the file, and a partial run's output differs from the
|
|
/// buffer only where it decided to differ.
|
|
pub fn range_formatting(
|
|
doc: &Document,
|
|
config: &Config,
|
|
range: Range,
|
|
) -> Result<Option<TextEdit>, String> {
|
|
let first = range.start.line.saturating_add(1);
|
|
// An end at character 0 of a later line is the start of that line, not
|
|
// any of its content.
|
|
let ends_before_its_line = range.end.character == 0 && range.end.line > range.start.line;
|
|
let last = if ends_before_its_line { range.end.line } else { range.end.line + 1 };
|
|
let lines = LineRanges::new([(first, last.max(first))])?;
|
|
let formatted = format_range(&doc.text, config, &lines).map_err(|e| e.to_string())?;
|
|
if formatted == doc.text {
|
|
return Ok(None);
|
|
}
|
|
Ok(Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted }))
|
|
}
|
|
|
|
/// The indent width governing a buffer, for a lint fix that has to write
|
|
/// spaces where a tab was.
|
|
///
|
|
/// A `textDocument/codeAction` request carries no `FormattingOptions`, so there
|
|
/// is no client `tabSize` to consider here — the precedence is just
|
|
/// `vfmt.toml` > the built-in default. A broken config is silent on this path:
|
|
/// the formatting path is where the user is told about it, and warning from a
|
|
/// lightbulb the editor requests on every cursor move would be noise.
|
|
pub fn indent_width(path: Option<&Path>) -> usize {
|
|
let (file, _problem) = discover(path);
|
|
file.indent.unwrap_or(Config::default().indent_width)
|
|
}
|
|
|
|
/// The config file governing `path`, by the CLI's own discovery rule, or the
|
|
/// error that stopped it from being read. A buffer with no path (`untitled:`)
|
|
/// has no directory to search from, so it gets no config.
|
|
fn discover(path: Option<&Path>) -> (FileConfig, Option<String>) {
|
|
let Some(path) = path else { return (FileConfig::default(), None) };
|
|
// A fresh `Discovery` per request, so a `vfmt.toml` edited while the
|
|
// server runs takes effect at the next format. One file read on an
|
|
// explicit, user-initiated request is cheaper than any cache invalidation
|
|
// scheme that could be wrong.
|
|
match Discovery::new(true).for_file(path) {
|
|
Ok(file) => (file, None),
|
|
Err(problem) => (FileConfig::default(), Some(problem)),
|
|
}
|
|
}
|
|
|
|
/// Fold the config file and the client's tab options into formatter settings,
|
|
/// in the precedence `settings_for` documents.
|
|
///
|
|
/// The client's `tab_size` is taken only when the request is sane: a client
|
|
/// asking for hard tabs, or for a 40-space indent, is asking for something
|
|
/// vfmt does not do, and silently honoring half of it is worse than ignoring
|
|
/// it. `max_width` is never taken from the client — the protocol has no
|
|
/// line-length option, so it comes from `vfmt.toml` or not at all.
|
|
fn config_from(file: &FileConfig, options: &FormattingOptions) -> Config {
|
|
let mut config = Config::default();
|
|
if options.insert_spaces && INDENT_RANGE.contains(&options.tab_size) {
|
|
config.indent_width = options.tab_size as usize;
|
|
}
|
|
if let Some(indent) = file.indent {
|
|
config.indent_width = indent;
|
|
}
|
|
if let Some(line_length) = file.line_length {
|
|
config.max_width = line_length;
|
|
}
|
|
config
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::state::Workspace;
|
|
use lsp_types::{Position, Uri};
|
|
use std::path::PathBuf;
|
|
use std::str::FromStr;
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
|
|
fn document(text: &str) -> (Workspace, Uri) {
|
|
let uri = Uri::from_str("file:///rtl/m.sv").expect("uri");
|
|
let mut ws = Workspace::default();
|
|
ws.set_document(uri.clone(), text.to_string());
|
|
(ws, uri)
|
|
}
|
|
|
|
fn options(tab_size: u32, insert_spaces: bool) -> FormattingOptions {
|
|
FormattingOptions { tab_size, insert_spaces, ..Default::default() }
|
|
}
|
|
|
|
/// The settings a buffer with no config file on disk resolves to.
|
|
fn settings(ws: &Workspace, uri: &Uri, options: &FormattingOptions) -> Settings {
|
|
settings_for(ws.document(uri).expect("open"), options)
|
|
}
|
|
|
|
fn edit_of(
|
|
ws: &Workspace,
|
|
uri: &Uri,
|
|
options: &FormattingOptions,
|
|
) -> Result<Option<TextEdit>, String> {
|
|
let doc = ws.document(uri).expect("open");
|
|
formatting(doc, &settings_for(doc, options).config)
|
|
}
|
|
|
|
/// A scratch directory holding a `vfmt.toml` and one source file, so
|
|
/// discovery runs against a real tree. Removed on drop.
|
|
struct Tree {
|
|
path: PathBuf,
|
|
}
|
|
|
|
impl Tree {
|
|
fn new(config: &str) -> Tree {
|
|
static COUNTER: AtomicUsize = AtomicUsize::new(0);
|
|
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
|
|
let path =
|
|
std::env::temp_dir().join(format!("vfmt_server_fmt_{}_{n}", std::process::id()));
|
|
let _ = std::fs::remove_dir_all(&path);
|
|
std::fs::create_dir_all(&path).expect("temp dir");
|
|
// A `.git` marker stops discovery here, so a `vfmt.toml` in a real
|
|
// ancestor of the temp dir can never leak into these tests.
|
|
std::fs::write(path.join(".git"), "gitdir: nowhere\n").expect("write .git");
|
|
std::fs::write(path.join("vfmt.toml"), config).expect("write config");
|
|
Tree { path }
|
|
}
|
|
|
|
/// An open buffer for `m.sv` inside this tree.
|
|
fn document(&self, text: &str) -> (Workspace, Uri) {
|
|
let file = self.path.join("m.sv");
|
|
std::fs::write(&file, text).expect("write source");
|
|
let uri = crate::uri::path_to_uri(&file).expect("uri");
|
|
let mut ws = Workspace::default();
|
|
ws.set_document(uri.clone(), text.to_string());
|
|
(ws, uri)
|
|
}
|
|
}
|
|
|
|
impl Drop for Tree {
|
|
fn drop(&mut self) {
|
|
let _ = std::fs::remove_dir_all(&self.path);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn an_unformatted_buffer_gets_one_whole_document_edit() {
|
|
let (ws, uri) = document("module m;\nwire a;\nendmodule\n");
|
|
let edit = edit_of(&ws, &uri, &options(2, true)).expect("formats").expect("changed");
|
|
assert_eq!(edit.range.start.line, 0);
|
|
assert_eq!(edit.range.start.character, 0);
|
|
assert_eq!(edit.range.end.line, 3, "one past the last line");
|
|
assert_eq!(edit.new_text, "module m;\n wire a;\nendmodule\n");
|
|
}
|
|
|
|
#[test]
|
|
fn an_already_formatted_buffer_gets_no_edit() {
|
|
let (ws, uri) = document("module m;\n wire a;\nendmodule\n");
|
|
assert_eq!(edit_of(&ws, &uri, &options(2, true)).expect("formats"), None);
|
|
}
|
|
|
|
#[test]
|
|
fn a_sane_tab_size_becomes_the_indent_width() {
|
|
let (ws, uri) = document("module m;\nwire a;\nendmodule\n");
|
|
let edit = edit_of(&ws, &uri, &options(4, true)).expect("formats").expect("changed");
|
|
assert_eq!(edit.new_text, "module m;\n wire a;\nendmodule\n");
|
|
}
|
|
|
|
#[test]
|
|
fn hard_tabs_and_absurd_widths_fall_back_to_the_default() {
|
|
let none = FileConfig::default();
|
|
assert_eq!(config_from(&none, &options(4, false)).indent_width, 2, "hard tabs ignored");
|
|
assert_eq!(config_from(&none, &options(40, true)).indent_width, 2, "out of range ignored");
|
|
assert_eq!(config_from(&none, &options(0, true)).indent_width, 2, "zero ignored");
|
|
assert_eq!(config_from(&none, &options(8, true)).indent_width, 8, "the top of the range");
|
|
}
|
|
|
|
#[test]
|
|
fn a_line_length_is_never_taken_from_the_client() {
|
|
let config = config_from(&FileConfig::default(), &options(4, true));
|
|
assert_eq!(config.max_width, Config::default().max_width);
|
|
}
|
|
|
|
#[test]
|
|
fn a_config_file_beats_the_editors_tab_size() {
|
|
// The precedence decision, pinned: `tab_size` is the editor's default
|
|
// unless the user changed it, and a checked-in `vfmt.toml` is always
|
|
// deliberate. See `settings_for`.
|
|
let file = FileConfig { line_length: Some(120), indent: Some(4), exclude: None };
|
|
let config = config_from(&file, &options(2, true));
|
|
assert_eq!(config.indent_width, 4, "vfmt.toml wins over tab_size");
|
|
assert_eq!(config.max_width, 120, "line-length has no client analog at all");
|
|
// Where the config is silent the tab size still beats the default.
|
|
let only_width = FileConfig { line_length: Some(120), indent: None, exclude: None };
|
|
assert_eq!(config_from(&only_width, &options(3, true)).indent_width, 3);
|
|
}
|
|
|
|
#[test]
|
|
fn a_vfmt_toml_governs_the_buffer_it_sits_above() {
|
|
let tree = Tree::new("indent = 4\n");
|
|
let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n");
|
|
// The client asks for 2, the config says 4: the config wins.
|
|
let settings = settings(&ws, &uri, &options(2, true));
|
|
assert_eq!(settings.config.indent_width, 4);
|
|
assert_eq!(settings.problem, None);
|
|
let edit = edit_of(&ws, &uri, &options(2, true)).expect("formats").expect("changed");
|
|
assert_eq!(edit.new_text, "module m;\n wire a;\nendmodule\n");
|
|
}
|
|
|
|
#[test]
|
|
fn a_broken_vfmt_toml_reports_a_problem_and_formats_with_defaults() {
|
|
let tree = Tree::new("indent = 4\nbogus = 1\n");
|
|
let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n");
|
|
let settings = settings(&ws, &uri, &options(2, true));
|
|
let problem = settings.problem.expect("a broken config must be reported");
|
|
assert!(problem.contains("unknown key `bogus`"), "{problem}");
|
|
assert!(problem.contains("vfmt.toml:2"), "the message names file and line: {problem}");
|
|
// Nothing from the broken file is used, not even the key that parsed.
|
|
assert_eq!(settings.config.indent_width, Config::default().indent_width);
|
|
// And the buffer is still formatted: an editor must not hard-fail on a
|
|
// config typo the way the CLI's exit 2 does.
|
|
let edit = edit_of(&ws, &uri, &options(2, true)).expect("formats").expect("changed");
|
|
assert_eq!(edit.new_text, "module m;\n wire a;\nendmodule\n");
|
|
}
|
|
|
|
#[test]
|
|
fn a_lint_fixs_indent_comes_from_the_config_or_the_built_in_default() {
|
|
// A code action has no `tabSize` to consider, so a quick fix that
|
|
// writes spaces where a tab was gets the buffer's own `vfmt.toml`.
|
|
let tree = Tree::new("indent = 4\n");
|
|
let (ws, uri) = tree.document("module m;\n\twire a;\nendmodule\n");
|
|
let doc = ws.document(&uri).expect("open");
|
|
assert_eq!(indent_width(doc.path.as_deref()), 4);
|
|
assert_eq!(indent_width(None), Config::default().indent_width, "an untitled buffer");
|
|
}
|
|
|
|
#[test]
|
|
fn a_broken_config_leaves_the_lint_fix_on_the_default_indent_and_says_nothing() {
|
|
let tree = Tree::new("indent = 4\nbogus = 1\n");
|
|
let (ws, uri) = tree.document("module m;\n\twire a;\nendmodule\n");
|
|
let doc = ws.document(&uri).expect("open");
|
|
assert_eq!(indent_width(doc.path.as_deref()), Config::default().indent_width);
|
|
}
|
|
|
|
#[test]
|
|
fn an_untitled_buffer_has_no_directory_to_discover_from() {
|
|
let uri = Uri::from_str("untitled:Untitled-1").expect("uri");
|
|
let mut ws = Workspace::default();
|
|
ws.set_document(uri.clone(), "module m;\nwire a;\nendmodule\n".to_string());
|
|
let settings = settings(&ws, &uri, &options(4, true));
|
|
assert_eq!(settings.problem, None);
|
|
assert_eq!(settings.config.indent_width, 4, "the tab size is all there is");
|
|
}
|
|
|
|
/// Three items, one per line, so a range's reach is visible line by line.
|
|
const THREE: &str = "module m;\n wire a;\n wire b;\nendmodule\n";
|
|
|
|
fn at(start_line: u32, start_char: u32, end_line: u32, end_char: u32) -> Range {
|
|
Range {
|
|
start: Position { line: start_line, character: start_char },
|
|
end: Position { line: end_line, character: end_char },
|
|
}
|
|
}
|
|
|
|
fn ranged(text: &str, range: Range) -> Result<Option<TextEdit>, String> {
|
|
let (ws, uri) = document(text);
|
|
let doc = ws.document(&uri).expect("open");
|
|
range_formatting(doc, &settings_for(doc, &options(2, true)).config, range)
|
|
}
|
|
|
|
#[test]
|
|
fn a_range_formats_only_the_lines_it_covers() {
|
|
// A cursor sitting on line 2 (0-based line 1) with nothing selected.
|
|
let edit = ranged(THREE, at(1, 4, 1, 4)).expect("formats").expect("changed");
|
|
assert_eq!(edit.new_text, "module m;\n wire a;\n wire b;\nendmodule\n");
|
|
// And the reply is still one whole-document edit.
|
|
assert_eq!(edit.range.start, Position { line: 0, character: 0 });
|
|
assert_eq!(edit.range.end.line, 4);
|
|
}
|
|
|
|
#[test]
|
|
fn a_selection_ending_at_the_start_of_a_line_stops_before_it() {
|
|
// "Select these two lines" in an editor ends at line 3, character 0.
|
|
let edit = ranged(THREE, at(1, 0, 3, 0)).expect("formats").expect("changed");
|
|
assert_eq!(edit.new_text, "module m;\n wire a;\n wire b;\nendmodule\n");
|
|
// One line only, ending where it began.
|
|
let edit = ranged(THREE, at(2, 0, 3, 0)).expect("formats").expect("changed");
|
|
assert_eq!(edit.new_text, "module m;\n wire a;\n wire b;\nendmodule\n");
|
|
}
|
|
|
|
#[test]
|
|
fn a_range_over_nothing_formattable_produces_no_edit() {
|
|
// Line 4 is `endmodule`, already written the way the formatter writes
|
|
// it, so there is nothing to send.
|
|
assert_eq!(ranged(THREE, at(3, 0, 3, 9)).expect("formats"), None);
|
|
}
|
|
|
|
#[test]
|
|
fn a_range_whose_end_is_past_the_document_still_answers() {
|
|
let edit = ranged(THREE, at(0, 0, 99, 0)).expect("formats").expect("changed");
|
|
assert_eq!(edit.new_text, "module m;\n wire a;\n wire b;\nendmodule\n");
|
|
}
|
|
|
|
#[test]
|
|
fn a_range_over_multi_byte_content_lands_on_the_right_lines() {
|
|
// The character columns are UTF-16 units; only the *lines* reach the
|
|
// engine, so the emoji line must not shift which item is formatted.
|
|
let text = "module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n";
|
|
let edit = ranged(text, at(2, 0, 2, 11)).expect("formats").expect("changed");
|
|
assert_eq!(
|
|
edit.new_text,
|
|
"module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n"
|
|
);
|
|
assert!(edit.new_text.contains("é ✓ 🎉"), "comments are never dropped");
|
|
}
|
|
|
|
#[test]
|
|
fn an_unparsable_buffer_produces_no_range_edit_either() {
|
|
// Range formatting cannot rescue broken input; the strict parse still
|
|
// has to succeed.
|
|
let message =
|
|
ranged("module m;\n wire ;\nendmodule\n", at(0, 0, 0, 9)).expect_err("must refuse");
|
|
assert!(!message.is_empty(), "the user needs something to read");
|
|
}
|
|
|
|
#[test]
|
|
fn an_unparsable_buffer_produces_no_edit() {
|
|
let (ws, uri) = document("module m;\n wire ;\nendmodule\n");
|
|
let message = edit_of(&ws, &uri, &options(2, true)).expect_err("must refuse");
|
|
assert!(!message.is_empty(), "the user needs something to read");
|
|
}
|
|
|
|
#[test]
|
|
fn multi_byte_content_survives_formatting() {
|
|
let (ws, uri) = document("module m;\n// é ✓ 🎉\nwire a;\nendmodule\n");
|
|
let edit = edit_of(&ws, &uri, &options(2, true)).expect("formats").expect("changed");
|
|
assert!(edit.new_text.contains("é ✓ 🎉"), "comments are never dropped");
|
|
// The replaced range must cover the whole document in UTF-16 terms.
|
|
assert_eq!(edit.range.end.line, 4);
|
|
}
|
|
}
|