textDocument/rangesFormatting: the engine took multi-range LineRanges
natively (this is literally the CLI's --lines a-b,c-d call), so the
server adapter is map(lines_of) around it and the verified
all-or-nothing contract rides through whole. range_formatting is now
DEFINED as the one-element case, making refusal equality structural;
lines_of extracted with its own test, plus a latent debug-overflow fix
(end.line + 1 at u32::MAX -> saturating, proven by deliberate
breakage). The capability widens documentRangeFormattingProvider from
true to {rangesSupport: true} only for clients that asked (read from
the raw initialize params; lsp-types 0.97 spells neither half) — every
pre-round client sees a byte-identical initialize result, proven on
the wire. The round's discovery: vscode-languageclient 9.0.1 has been
sending rangesSupport and gating its multi-range provider on our
answer all along — the bare boolean was turning the feature off.
SnippetTextEdit and workspace/textDocumentContent are parked with
evidence: absent from lsp-types 0.97 and from the pinned client's
node_modules (a snippet edit sent today would write literal ${1:...}
into the buffer), and the thin extension deliberately has no content
provider. Each parking carries a one-grep re-check trigger. The
whole-document reply shape is kept: splitting per-range would claim
byte ownership the engine never verified.
24 tests added; QA re-ran every evidence grep, verified the client
citations against formatting.js, and closed with zero findings. This
completes TODO.md §9c and the LSP 3.18 audit's feature work.
docs/features/lsp-318-extras/README.md
Co-Authored-By: Claude Fable 5 <[email protected]>
826 lines
38 KiB
Rust
826 lines
38 KiB
Rust
//! `textDocument/formatting`, `textDocument/rangeFormatting` and
|
|
//! `textDocument/rangesFormatting`.
|
|
//!
|
|
//! 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 requests too — their output is verified over the whole buffer,
|
|
//! and what makes a request 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, TextDocumentIdentifier, TextEdit};
|
|
use lucisv_core::config::{Discovery, FileConfig};
|
|
use vlog_formatter::{format_range, format_source, Config, LineRanges};
|
|
|
|
use crate::settings::ClientSettings;
|
|
use crate::state::Document;
|
|
|
|
/// Indent widths a client may ask for. The same 1..8 range `lucisv.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 `lucisv.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 `lucisv.toml` error governing this buffer, if there is one.
|
|
pub problem: Option<String>,
|
|
}
|
|
|
|
/// Resolve the settings governing a buffer.
|
|
///
|
|
/// Precedence, highest first:
|
|
///
|
|
/// 1. **`lucisv.toml`** — a checked-in config is the project speaking, and it
|
|
/// must stay authoritative or format-on-save would disagree with CI's
|
|
/// `lucisv --check`. That divergence is the exact thing lifting the config
|
|
/// into `lucisv_core` exists to remove.
|
|
/// 2. **The client's `lucisv.*` settings** (`settings.rs`) — typed on purpose
|
|
/// into an editor's settings UI, so more deliberate than a tab size, but
|
|
/// it is one user's editor and the repository outranks it.
|
|
/// 3. **`FormattingOptions::tab_size`** — 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, so it is the weakest thing that is still a signal.
|
|
/// This is *not* the CLI's flag-beats-config order, and deliberately so.
|
|
/// 4. **The built-in default.**
|
|
///
|
|
/// Each rung applies only where every rung above it is silent, so a project
|
|
/// with no `lucisv.toml` and no `lucisv.*` settings behaves exactly as it did
|
|
/// before either existed.
|
|
pub fn settings_for(
|
|
doc: &Document,
|
|
client: &ClientSettings,
|
|
options: &FormattingOptions,
|
|
) -> Settings {
|
|
let (file, problem) = discover(doc.path.as_deref());
|
|
Settings { config: config_from(&file, client, options), problem }
|
|
}
|
|
|
|
/// Resolve the settings governing a buffer for a request that carries no
|
|
/// `FormattingOptions`.
|
|
///
|
|
/// `textDocument/willSaveWaitUntil` has no options field at all — the protocol
|
|
/// simply does not carry one there. So the ladder `settings_for` documents
|
|
/// runs with rung 3 missing, which is the same thing `indent_width` does for a
|
|
/// lint fix: `lucisv.toml` > the pushed `lucisv.*` settings > the built-in
|
|
/// default. Spelled as hard tabs and a zero width because `config_from` takes
|
|
/// neither, so nothing is guessed on the user's behalf.
|
|
pub fn settings_without_editor_options(doc: &Document, client: &ClientSettings) -> Settings {
|
|
let none = FormattingOptions { tab_size: 0, insert_spaces: false, ..Default::default() };
|
|
settings_for(doc, client, &none)
|
|
}
|
|
|
|
/// 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 }))
|
|
}
|
|
|
|
/// `textDocument/rangesFormatting`, the LSP 3.18 multi-range request.
|
|
///
|
|
/// Spelled out here because `lsp-types` 0.97 predates it — the same reason
|
|
/// `pairs::ScopePairsParams` is hand-rolled. See
|
|
/// `docs/features/lsp-318-extras/README.md`.
|
|
pub const RANGES_FORMATTING: &str = "textDocument/rangesFormatting";
|
|
|
|
/// `textDocument/rangesFormatting` params: one document, `n` ranges, one set
|
|
/// of options.
|
|
#[derive(serde::Deserialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct RangesFormattingParams {
|
|
pub text_document: TextDocumentIdentifier,
|
|
pub ranges: Vec<Range>,
|
|
pub options: FormattingOptions,
|
|
}
|
|
|
|
/// Format the constructs a selection reaches, and nothing else.
|
|
///
|
|
/// The one-range case of [`ranges_formatting`], which is where the whole
|
|
/// answer lives — an `n`-range request is this request with `n` line spans.
|
|
pub fn range_formatting(
|
|
doc: &Document,
|
|
config: &Config,
|
|
range: Range,
|
|
) -> Result<Option<TextEdit>, String> {
|
|
ranges_formatting(doc, config, std::slice::from_ref(&range))
|
|
}
|
|
|
|
/// Format the constructs any of several selections reach, and nothing else.
|
|
///
|
|
/// The ranges are a *set*: they are sorted and merged by `LineRanges::new`
|
|
/// before the engine sees them, so overlapping, adjacent, repeated and
|
|
/// unsorted input from the client all reach the same answer. No range is
|
|
/// formatted on its own — one `format_range` call lays out the union, which is
|
|
/// what keeps the all-or-nothing contract (CLAUDE.md invariant #1) whole
|
|
/// rather than making it a promise per range.
|
|
///
|
|
/// 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. An empty range list is not an
|
|
/// error — it is an ask for nothing, answered with no edit.
|
|
pub fn ranges_formatting(
|
|
doc: &Document,
|
|
config: &Config,
|
|
ranges: &[Range],
|
|
) -> Result<Option<TextEdit>, String> {
|
|
if ranges.is_empty() {
|
|
return Ok(None);
|
|
}
|
|
let lines = LineRanges::new(ranges.iter().copied().map(lines_of))?;
|
|
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 1-based inclusive line span an LSP range names.
|
|
///
|
|
/// The protocol's `Range` is a half-open span of UTF-16 positions; the engine
|
|
/// wants lines, so only the line numbers survive the conversion — which
|
|
/// sidesteps the UTF-16 column question rather than solving it again. 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.
|
|
///
|
|
/// One conversion, shared by both range requests: a second spelling of this
|
|
/// rule would be a second thing to get wrong.
|
|
fn lines_of(range: Range) -> (u32, u32) {
|
|
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.saturating_add(1) };
|
|
(first, last.max(first))
|
|
}
|
|
|
|
/// 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 the same ladder
|
|
/// `settings_for` documents with rung 3 missing: `lucisv.toml` > `lucisv.indent` >
|
|
/// 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>, client: &ClientSettings) -> usize {
|
|
let (file, _problem) = discover(path);
|
|
file.indent.or(client.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 `lucisv.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, the pushed `lucisv.*` settings and the client's tab
|
|
/// options into formatter settings, in the precedence `settings_for`
|
|
/// documents. Written weakest-first, so the last writer wins.
|
|
///
|
|
/// 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
|
|
/// lucisv does not do, and silently honoring half of it is worse than ignoring
|
|
/// it. `lucisv.lineLength` has no `FormattingOptions` analog at all — the
|
|
/// protocol carries no line-length option — so before it existed there was no
|
|
/// way to set a width from an editor without a `lucisv.toml`.
|
|
fn config_from(file: &FileConfig, client: &ClientSettings, 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) = client.indent {
|
|
config.indent_width = indent;
|
|
}
|
|
if let Some(line_length) = client.line_length {
|
|
config.max_width = line_length;
|
|
}
|
|
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::settings::ClientSettings;
|
|
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() }
|
|
}
|
|
|
|
/// No `lucisv.*` settings pushed — what every test predating them assumes.
|
|
fn none() -> ClientSettings {
|
|
ClientSettings::default()
|
|
}
|
|
|
|
/// The settings a buffer resolves to, with nothing pushed by the client.
|
|
fn settings(ws: &Workspace, uri: &Uri, options: &FormattingOptions) -> Settings {
|
|
settings_with(ws, uri, &none(), options)
|
|
}
|
|
|
|
/// The settings a buffer resolves to against a given pushed configuration.
|
|
fn settings_with(
|
|
ws: &Workspace,
|
|
uri: &Uri,
|
|
client: &ClientSettings,
|
|
options: &FormattingOptions,
|
|
) -> Settings {
|
|
settings_for(ws.document(uri).expect("open"), client, options)
|
|
}
|
|
|
|
fn edit_of(
|
|
ws: &Workspace,
|
|
uri: &Uri,
|
|
options: &FormattingOptions,
|
|
) -> Result<Option<TextEdit>, String> {
|
|
edit_with(ws, uri, &none(), options)
|
|
}
|
|
|
|
fn edit_with(
|
|
ws: &Workspace,
|
|
uri: &Uri,
|
|
client: &ClientSettings,
|
|
options: &FormattingOptions,
|
|
) -> Result<Option<TextEdit>, String> {
|
|
let doc = ws.document(uri).expect("open");
|
|
formatting(doc, &settings_for(doc, client, options).config)
|
|
}
|
|
|
|
/// A scratch directory holding a `lucisv.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!("lucisv_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 `lucisv.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("lucisv.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 nothing = FileConfig::default();
|
|
assert_eq!(
|
|
config_from(¬hing, &none(), &options(4, false)).indent_width,
|
|
2,
|
|
"hard tabs ignored"
|
|
);
|
|
assert_eq!(
|
|
config_from(¬hing, &none(), &options(40, true)).indent_width,
|
|
2,
|
|
"out of range ignored"
|
|
);
|
|
assert_eq!(
|
|
config_from(¬hing, &none(), &options(0, true)).indent_width,
|
|
2,
|
|
"zero ignored"
|
|
);
|
|
assert_eq!(
|
|
config_from(¬hing, &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(), &none(), &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 `lucisv.toml` is always
|
|
// deliberate. See `settings_for`.
|
|
let file = FileConfig { line_length: Some(120), indent: Some(4), ..Default::default() };
|
|
let config = config_from(&file, &none(), &options(2, true));
|
|
assert_eq!(config.indent_width, 4, "lucisv.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), ..Default::default() };
|
|
assert_eq!(config_from(&only_width, &none(), &options(3, true)).indent_width, 3);
|
|
}
|
|
|
|
#[test]
|
|
fn a_lucisv_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_lucisv_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("lucisv.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 `lucisv.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(), &none()), 4);
|
|
assert_eq!(
|
|
indent_width(None, &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(), &none()), 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");
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// the precedence ladder, one rung at a time
|
|
// ------------------------------------------------------------------
|
|
|
|
/// `lucisv.*` settings as a client would push them.
|
|
fn pushed(line_length: Option<usize>, indent: Option<usize>) -> ClientSettings {
|
|
ClientSettings { line_length, indent, ..Default::default() }
|
|
}
|
|
|
|
#[test]
|
|
fn rung_1_a_config_file_beats_a_pushed_setting() {
|
|
// The whole reason the ladder is in this order: a checked-in
|
|
// `lucisv.toml` is the project speaking, and format-on-save must agree
|
|
// with what `lucisv --check` does in CI.
|
|
let tree = Tree::new("indent = 4\nline-length = 120\n");
|
|
let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n");
|
|
let client = pushed(Some(80), Some(8));
|
|
let settings = settings_with(&ws, &uri, &client, &options(2, true));
|
|
assert_eq!(settings.config.indent_width, 4, "lucisv.toml wins");
|
|
assert_eq!(settings.config.max_width, 120, "for line-length too");
|
|
let edit = edit_with(&ws, &uri, &client, &options(2, true)).expect("formats");
|
|
assert_eq!(edit.expect("changed").new_text, "module m;\n wire a;\nendmodule\n");
|
|
}
|
|
|
|
#[test]
|
|
fn rung_2_a_pushed_setting_beats_the_editors_tab_size() {
|
|
// `tabSize` arrives on every request whether the user chose it or
|
|
// not; `lucisv.indent` was typed on purpose.
|
|
let (ws, uri) = document("module m;\nwire a;\nendmodule\n");
|
|
let client = pushed(None, Some(4));
|
|
let settings = settings_with(&ws, &uri, &client, &options(2, true));
|
|
assert_eq!(settings.config.indent_width, 4);
|
|
let edit = edit_with(&ws, &uri, &client, &options(2, true)).expect("formats");
|
|
assert_eq!(edit.expect("changed").new_text, "module m;\n wire a;\nendmodule\n");
|
|
}
|
|
|
|
#[test]
|
|
fn rung_3_the_tab_size_still_beats_the_default_where_nothing_was_pushed() {
|
|
let (ws, uri) = document("module m;\nwire a;\nendmodule\n");
|
|
// Pushed settings that say nothing about indent leave rung 3 in charge.
|
|
let client = pushed(Some(120), None);
|
|
let settings = settings_with(&ws, &uri, &client, &options(3, true));
|
|
assert_eq!(settings.config.indent_width, 3, "the tab size");
|
|
assert_eq!(settings.config.max_width, 120, "and the pushed width");
|
|
}
|
|
|
|
#[test]
|
|
fn rung_4_the_default_applies_when_every_rung_above_is_silent() {
|
|
let (ws, uri) = document("module m;\nwire a;\nendmodule\n");
|
|
// Hard tabs, so even the tab size is not a usable signal.
|
|
let settings = settings_with(&ws, &uri, &none(), &options(4, false));
|
|
assert_eq!(settings.config.indent_width, Config::default().indent_width);
|
|
assert_eq!(settings.config.max_width, Config::default().max_width);
|
|
}
|
|
|
|
#[test]
|
|
fn each_key_climbs_the_ladder_independently() {
|
|
// A `lucisv.toml` naming only `indent` must not also claim the width:
|
|
// the pushed `lineLength` is still the best answer for that key.
|
|
let tree = Tree::new("indent = 4\n");
|
|
let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n");
|
|
let settings = settings_with(&ws, &uri, &pushed(Some(60), Some(8)), &options(2, true));
|
|
assert_eq!(settings.config.indent_width, 4, "config wins the key it names");
|
|
assert_eq!(settings.config.max_width, 60, "and is silent about the other");
|
|
}
|
|
|
|
#[test]
|
|
fn a_pushed_line_length_is_the_only_way_to_set_a_width_without_a_config() {
|
|
// The protocol has no line-length option at all, so before
|
|
// `lucisv.lineLength` a config-less project could not narrow its lines
|
|
// from the editor. This is the new capability, at the level that
|
|
// actually reflows text.
|
|
let long = "module m;\n assign a = bbbbbbbbbbbb + cccccccccccc + dddddddddddd + eeeeeeeeeeee;\nendmodule\n";
|
|
let (ws, uri) = document(long);
|
|
assert_eq!(edit_of(&ws, &uri, &options(2, true)).expect("formats"), None, "fits at 100");
|
|
let edit = edit_with(&ws, &uri, &pushed(Some(40), None), &options(2, true))
|
|
.expect("formats")
|
|
.expect("40 columns must reflow it");
|
|
assert!(edit.new_text.lines().count() > long.lines().count(), "{}", edit.new_text);
|
|
}
|
|
|
|
#[test]
|
|
fn an_untitled_buffer_honours_pushed_settings() {
|
|
// It has no directory to discover a `lucisv.toml` from, so rung 2 is the
|
|
// highest rung it has — and before this feature it had only `tabSize`.
|
|
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_with(&ws, &uri, &pushed(Some(60), Some(4)), &options(2, true));
|
|
assert_eq!(settings.problem, None);
|
|
assert_eq!(settings.config.indent_width, 4, "pushed indent beats the tab size");
|
|
assert_eq!(settings.config.max_width, 60);
|
|
}
|
|
|
|
#[test]
|
|
fn a_lint_fix_climbs_the_same_ladder_without_rung_3() {
|
|
// A code action has no `tabSize`, so `lucisv.indent` is the only thing
|
|
// under a `lucisv.toml` here.
|
|
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(), &pushed(None, Some(8))), 4, "config wins");
|
|
assert_eq!(indent_width(None, &pushed(None, Some(8))), 8, "untitled: the pushed value");
|
|
assert_eq!(indent_width(None, &none()), Config::default().indent_width, "then default");
|
|
}
|
|
|
|
#[test]
|
|
fn a_request_without_options_climbs_the_same_ladder_without_rung_3() {
|
|
// What `willSaveWaitUntil` resolves to: the protocol sends no
|
|
// `FormattingOptions` with it, so the editor's tab size is simply not
|
|
// one of the inputs.
|
|
let tree = Tree::new("indent = 4\n");
|
|
let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n");
|
|
let doc = ws.document(&uri).expect("open");
|
|
let settings = settings_without_editor_options(doc, &pushed(None, Some(8)));
|
|
assert_eq!(settings.config.indent_width, 4, "the config still wins");
|
|
assert_eq!(settings.problem, None);
|
|
|
|
// With no config, the pushed setting is the highest rung there is.
|
|
let (ws, uri) = document("module m;\nwire a;\nendmodule\n");
|
|
let doc = ws.document(&uri).expect("open");
|
|
let settings = settings_without_editor_options(doc, &pushed(Some(60), Some(8)));
|
|
assert_eq!(settings.config.indent_width, 8);
|
|
assert_eq!(settings.config.max_width, 60);
|
|
// And with nothing pushed either, the built-in default — never a
|
|
// guess from an option that was not sent.
|
|
let settings = settings_without_editor_options(doc, &none());
|
|
assert_eq!(settings.config.indent_width, Config::default().indent_width);
|
|
assert_eq!(settings.config.max_width, Config::default().max_width);
|
|
}
|
|
|
|
#[test]
|
|
fn a_broken_config_leaves_the_pushed_settings_in_charge() {
|
|
// Nothing from a broken `lucisv.toml` is used, so the next rung down is
|
|
// the one that answers — which is now the pushed settings, not the
|
|
// built-in default.
|
|
let tree = Tree::new("indent = 4\nbogus = 1\n");
|
|
let (ws, uri) = tree.document("module m;\nwire a;\nendmodule\n");
|
|
let settings = settings_with(&ws, &uri, &pushed(Some(60), Some(8)), &options(2, true));
|
|
assert!(settings.problem.is_some(), "the user is still told");
|
|
assert_eq!(settings.config.indent_width, 8);
|
|
assert_eq!(settings.config.max_width, 60);
|
|
}
|
|
|
|
/// 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, &none(), &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");
|
|
}
|
|
|
|
// ------------------------------------------------------------------
|
|
// `rangesFormatting` — the union of the ranges, on the one engine
|
|
// ------------------------------------------------------------------
|
|
|
|
/// Four items, one per line, so two disjoint ranges can reach two of them
|
|
/// and leave the ones between untouched.
|
|
const FOUR: &str = "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n";
|
|
|
|
fn multi(text: &str, ranges: &[Range]) -> Result<Option<TextEdit>, String> {
|
|
let (ws, uri) = document(text);
|
|
let doc = ws.document(&uri).expect("open");
|
|
ranges_formatting(doc, &settings_for(doc, &none(), &options(2, true)).config, ranges)
|
|
}
|
|
|
|
/// The `new_text` a multi-range request answers with, or `None`.
|
|
fn multi_text(text: &str, ranges: &[Range]) -> Option<String> {
|
|
multi(text, ranges).expect("formats").map(|edit| edit.new_text)
|
|
}
|
|
|
|
#[test]
|
|
fn two_ranges_lay_out_both_the_items_they_reach_and_nothing_between() {
|
|
// Lines 2 and 4 selected, line 3 not: `b` keeps its bytes.
|
|
let both = multi_text(FOUR, &[at(1, 0, 1, 11), at(3, 0, 3, 11)]).expect("changed");
|
|
assert_eq!(both, "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n");
|
|
}
|
|
|
|
#[test]
|
|
fn a_multi_range_answer_is_the_union_of_the_single_range_answers() {
|
|
// The contract, stated as an equality rather than as a re-spelled
|
|
// expectation: where two ranges do not interact, asking for both at
|
|
// once is asking for each and taking both results. Line 2 formatted
|
|
// alone, then line 4 formatted on *that* text, must be byte-identical
|
|
// to one request naming both.
|
|
let first = ranged(FOUR, at(1, 0, 1, 11)).expect("formats").expect("changed").new_text;
|
|
let second = ranged(&first, at(3, 0, 3, 11)).expect("formats").expect("changed").new_text;
|
|
let both = multi_text(FOUR, &[at(1, 0, 1, 11), at(3, 0, 3, 11)]).expect("changed");
|
|
assert_eq!(both, second);
|
|
}
|
|
|
|
#[test]
|
|
fn ranges_arrive_unsorted_overlapping_adjacent_or_twice_and_mean_the_same_thing() {
|
|
// `LineRanges::new` sorts and merges, and this asserts it through the
|
|
// answer rather than restating the arithmetic. All four spellings name
|
|
// lines 2 and 3.
|
|
let want = multi_text(FOUR, &[at(1, 0, 2, 11)]).expect("changed");
|
|
assert_eq!(want, "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n");
|
|
for (spelling, ranges) in [
|
|
("unsorted", vec![at(2, 0, 2, 11), at(1, 0, 1, 11)]),
|
|
("overlapping", vec![at(1, 0, 2, 4), at(2, 0, 2, 11)]),
|
|
("adjacent", vec![at(1, 0, 1, 11), at(2, 0, 2, 11)]),
|
|
("the same range twice", vec![at(1, 0, 2, 11), at(1, 0, 2, 11)]),
|
|
] {
|
|
assert_eq!(multi_text(FOUR, &ranges).as_deref(), Some(want.as_str()), "{spelling}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn an_empty_range_list_is_an_ask_for_nothing_and_not_an_error() {
|
|
// A client with no selections must not get a popup. `LineRanges::new`
|
|
// refuses an empty list — that refusal is the CLI's (`--lines ''` is a
|
|
// typo), and it is answered before the engine here.
|
|
assert_eq!(multi(FOUR, &[]).expect("never an error"), None);
|
|
}
|
|
|
|
#[test]
|
|
fn one_range_over_the_whole_buffer_is_the_whole_file_format() {
|
|
let whole = multi_text(FOUR, &[at(0, 0, 99, 0)]).expect("changed");
|
|
assert_eq!(whole, "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n");
|
|
// And so is every line named separately, which is the same union.
|
|
let each: Vec<Range> = (0..5).map(|line| at(line, 0, line, 11)).collect();
|
|
assert_eq!(multi_text(FOUR, &each).as_deref(), Some(whole.as_str()));
|
|
}
|
|
|
|
#[test]
|
|
fn a_one_element_multi_range_request_is_the_single_range_request() {
|
|
// `range_formatting` is *defined* as this call, so the two can never
|
|
// drift — but the equality is what a client relies on, so it is
|
|
// asserted rather than argued.
|
|
for range in [at(1, 4, 1, 4), at(1, 0, 3, 0), at(3, 0, 3, 9), at(0, 0, 99, 0)] {
|
|
assert_eq!(ranged(THREE, range), multi(THREE, &[range]), "{range:?}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_refused_buffer_is_refused_identically_whichever_range_request_asked() {
|
|
// No partial output on either path (CLAUDE.md invariant #1), and the
|
|
// same message: both are one `format_range` call away from the engine.
|
|
let broken = "module m;\n wire ;\nendmodule\n";
|
|
let one = ranged(broken, at(0, 0, 0, 9));
|
|
let many = multi(broken, &[at(0, 0, 0, 9), at(2, 0, 2, 9)]);
|
|
assert!(one.is_err() && many.is_err(), "a broken buffer is refused both ways");
|
|
assert_eq!(one, many, "byte-identical refusals, message included");
|
|
}
|
|
|
|
#[test]
|
|
fn a_multi_range_format_is_a_fixed_point_under_the_same_ranges() {
|
|
// Idempotency through the new path: format lines 2 and 4, then ask for
|
|
// exactly the same two ranges on the answer — nothing left to do.
|
|
let ranges = [at(1, 0, 1, 11), at(3, 0, 3, 11)];
|
|
let once = multi_text(FOUR, &ranges).expect("changed");
|
|
assert_eq!(multi_text(&once, &ranges), None, "the second run has nothing to say");
|
|
}
|
|
|
|
#[test]
|
|
fn a_multi_range_request_over_already_formatted_lines_produces_no_edit() {
|
|
let clean = "module m;\n wire a;\n wire b;\nendmodule\n";
|
|
assert_eq!(multi(clean, &[at(0, 0, 0, 9), at(1, 0, 1, 9)]).expect("formats"), None);
|
|
}
|
|
|
|
#[test]
|
|
fn multi_byte_content_survives_a_multi_range_format_too() {
|
|
// The columns are UTF-16 units and only the lines reach the engine, so
|
|
// an emoji two lines up must not shift which items are laid out.
|
|
let text = "module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n";
|
|
let out = multi_text(text, &[at(2, 0, 2, 11), at(3, 0, 3, 11)]).expect("changed");
|
|
assert_eq!(out, "module m;\n // é ✓ 🎉 note\n wire a;\n wire b;\nendmodule\n");
|
|
assert!(out.contains("é ✓ 🎉"), "comments are never dropped");
|
|
}
|
|
|
|
#[test]
|
|
fn the_line_conversion_is_the_one_rangeformatting_always_used() {
|
|
// Pinned directly, because both requests now share it: a cursor names
|
|
// its own line; an end at character 0 of a *later* line stops one line
|
|
// short; an end at character 0 on the start line does not.
|
|
assert_eq!(lines_of(at(1, 4, 1, 4)), (2, 2), "a cursor");
|
|
assert_eq!(lines_of(at(1, 0, 3, 0)), (2, 3), "select two lines");
|
|
assert_eq!(lines_of(at(2, 0, 3, 0)), (3, 3), "select one line");
|
|
assert_eq!(lines_of(at(2, 0, 2, 0)), (3, 3), "an empty range on its own line");
|
|
assert_eq!(lines_of(at(0, 0, 99, 0)), (1, 99), "past the end of the buffer");
|
|
// And it never produces a span `LineRanges` would refuse: line 0 is
|
|
// impossible (1-based), and `last` can never fall below `first`.
|
|
assert_eq!(lines_of(at(0, 0, 0, 0)), (1, 1), "the very first line");
|
|
assert_eq!(
|
|
lines_of(at(u32::MAX, 0, u32::MAX, 0)),
|
|
(u32::MAX, u32::MAX),
|
|
"a saturating add, not an overflow"
|
|
);
|
|
}
|
|
|
|
#[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);
|
|
}
|
|
}
|