diff --git a/TODO.md b/TODO.md index 13280ce..6ac3001 100644 --- a/TODO.md +++ b/TODO.md @@ -964,11 +964,45 @@ and are not gaps. (applyEdit + progress create + configuration) under test. Known and stated, not fixed: a pulled setting can land after the first index build, exactly as a pushed one always could. -- [ ] **3.18 additions:** `textDocument/rangesFormatting` (multi-range, +- [x] **3.18 additions:** `textDocument/rangesFormatting` (multi-range, feeds format-modified-lines), snippet edits in `WorkspaceEdit` (would improve `addPort` cursor placement), and `workspace/textDocumentContent` (could serve a read-only "expanded macro" document). + → 2026-08-27 by `docs/features/lsp-318-extras/README.md`: **one + shipped, two parked with evidence.** *Shipped* — + `textDocument/rangesFormatting`, served as the `n`-range case of + `rangeFormatting`: the ranges become one sorted, merged `LineRanges` + (the constructor `--lines 3-9,40` already used, so unsorted, + overlapping, adjacent and repeated ranges all normalize in the one + place) and one `format_range` call, which keeps the all-or-nothing + contract over the *union* rather than making it a per-range promise. + `range_formatting` is now defined as the one-element call of it, so + the reply shape, the refusal and the config warning are the same + values and cannot drift; an empty `ranges` array is an ask for + nothing, not an error. The capability is advertised by widening + `documentRangeFormattingProvider` from `true` to + `{ "rangesSupport": true }` — the spec's own + `boolean | DocumentRangeFormattingOptions` union — **gated on the + client having sent `textDocument.rangeFormatting.rangesSupport`**, so + every client that shipped before this round sees the identical byte + and only a 3.18 client sees the object; the handler is registered + unconditionally. `lsp-types` 0.97 spells neither half, so the + capability goes out through the `initialize_value()` JSON insertion + (the type-hierarchy precedent) and the client flag is read from the + **raw** initialize params before the typed decode drops it. + *Parked* — **snippet `WorkspaceEdit` edits**: `lsp-types` 0.97 has no + `SnippetTextEdit`, `WorkspaceEditClientCapabilities` has no + `snippetEditSupport`, and the pinned `vscode-languageclient@9.0.1` + has neither string anywhere in it, so a server sending one would be + writing a literal `${1:name}` into the user's buffer. *Parked* — + **`workspace/textDocumentContent`**: absent from `lsp-types` 0.97 and + from the pinned client, and serving a custom URI scheme in VS Code + needs a content provider the deliberately thin `extension.js` does + not register; the expanded-macro view it would serve is also + hover-sized today, not document-sized. Both have an exact re-check + trigger recorded (one `node_modules` grep each). **This completes + §9c.** ### 9d. Deliberately skipped (no Verilog use case) diff --git a/crates/lucisv_server/src/format.rs b/crates/lucisv_server/src/format.rs index c8ebfac..220a454 100644 --- a/crates/lucisv_server/src/format.rs +++ b/crates/lucisv_server/src/format.rs @@ -1,15 +1,16 @@ -//! `textDocument/formatting` and `textDocument/rangeFormatting`. +//! `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 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. +//! 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, TextEdit}; +use lsp_types::{FormattingOptions, Range, TextDocumentIdentifier, TextEdit}; use lucisv_core::config::{Discovery, FileConfig}; use vlog_formatter::{format_range, format_source, Config, LineRanges}; @@ -88,29 +89,57 @@ pub fn formatting(doc: &Document, config: &Config) -> Result, S 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, + pub options: FormattingOptions, +} + /// 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. +/// 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, 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))])?; + 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, 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); @@ -118,6 +147,27 @@ pub fn range_formatting( 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. /// @@ -625,6 +675,145 @@ mod tests { 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, 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 { + 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 = (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"); diff --git a/crates/lucisv_server/src/main.rs b/crates/lucisv_server/src/main.rs index 999115e..3cafa44 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -68,6 +68,10 @@ fn main() -> Result<(), Box> { let (connection, io_threads) = Connection::stdio(); let (id, params) = connection.initialize_start()?; + // Read before the typed decode, because `lsp-types` 0.97's client + // capabilities have no field for it and drop it on the floor — see + // `ranges_formatting_support`. + let ranges_formatting = ranges_formatting_support(¶ms); // A client that sends params we cannot read still gets a server; every // field we want is optional anyway. let params: InitializeParams = serde_json::from_value(params).unwrap_or_default(); @@ -82,7 +86,7 @@ fn main() -> Result<(), Box> { show_document: show_document_support(¶ms), configuration: configuration_support(¶ms), }; - connection.initialize_finish(id, initialize_value()?)?; + connection.initialize_finish(id, initialize_value(ranges_formatting)?)?; Server::new(connection, roots, abilities).run()?; io_threads.join()?; @@ -312,16 +316,32 @@ fn commands() -> Vec { /// The `initialize` result exactly as it goes on the wire. /// -/// `typeHierarchyProvider` is written in here rather than in [`capabilities`] -/// because `lsp-types` 0.97 models type hierarchy on the *client* side only: -/// `ServerCapabilities` has no field for it, and `experimental` is a different -/// key that no client reads for this. So the one capability this server -/// advertises that the crate cannot spell is inserted into the serialized -/// object, which is the same JSON a field would have produced. -fn initialize_value() -> Result { +/// Two capabilities are written in here rather than in [`capabilities`], +/// because `lsp-types` 0.97 cannot spell either: +/// +/// * **`typeHierarchyProvider`** — the crate models type hierarchy on the +/// *client* side only, so `ServerCapabilities` has no field for it, and +/// `experimental` is a different key that no client reads for this. +/// * **`documentRangeFormattingProvider`** widened to +/// `{ "rangesSupport": true }` when `ranges_formatting` — the crate's +/// `DocumentRangeFormattingOptions` carries only `workDoneProgress`. This is +/// the spec's own `boolean | DocumentRangeFormattingOptions` union, so the +/// object form is legal for any client; it is sent only to a client that +/// asked because the bare `true` is the shape no client can misread, and a +/// client that did not ask will never send the request anyway. See +/// `docs/features/lsp-318-extras/README.md`. +/// +/// Both are the same JSON a field would have produced. +fn initialize_value(ranges_formatting: bool) -> Result { let mut value = serde_json::to_value(initialize_result())?; if let Some(caps) = value.get_mut("capabilities").and_then(serde_json::Value::as_object_mut) { caps.insert("typeHierarchyProvider".to_string(), serde_json::Value::Bool(true)); + if ranges_formatting { + caps.insert( + "documentRangeFormattingProvider".to_string(), + serde_json::json!({ "rangesSupport": true }), + ); + } } Ok(value) } @@ -339,6 +359,21 @@ fn initialize_result() -> lsp_types::InitializeResult { } } +/// Whether the client can send `textDocument/rangesFormatting` (LSP 3.18), +/// read from the **raw** `initialize` params. +/// +/// It has to be the raw JSON: `lsp-types` 0.97 aliases +/// `DocumentRangeFormattingClientCapabilities` to the plain dynamic-registration +/// struct, which has no `rangesSupport` field and no place to keep an unknown +/// one, so by the time the params are an `InitializeParams` the flag is gone. +/// Anything that is not literally `true` at +/// `capabilities.textDocument.rangeFormatting.rangesSupport` — absent, `false`, +/// a string, a client whose params do not parse at all — means no, which is +/// exactly the answer that leaves that client's capability where it was. +fn ranges_formatting_support(params: &serde_json::Value) -> bool { + params["capabilities"]["textDocument"]["rangeFormatting"]["rangesSupport"] == true +} + /// Whether the client can expand `${1:x}` tabstops in a completion item. /// /// A client that did not say so gets the skeleton as plain text: a literal @@ -496,7 +531,7 @@ mod tests { // A client sends `willRenameFiles` only where the *server's* filters // say so, and it looks for them at this exact key — a capability // nested one level wrong is a capability that is never exercised. - let value = initialize_value().expect("the initialize result serializes"); + let value = initialize_value(false).expect("the initialize result serializes"); let operations = &value["capabilities"]["workspace"]["fileOperations"]; assert_eq!( operations["willRename"]["filters"][0]["pattern"]["glob"], @@ -536,7 +571,7 @@ mod tests { fn the_workspace_folder_capability_reaches_the_wire_at_the_key_a_client_reads() { // Nested one level wrong, or serialized as the string form of // `changeNotifications`, and the notification simply never arrives. - let value = initialize_value().expect("the initialize result serializes"); + let value = initialize_value(false).expect("the initialize result serializes"); assert_eq!( value["capabilities"]["workspace"]["workspaceFolders"], serde_json::json!({ "supported": true, "changeNotifications": true }), @@ -573,7 +608,7 @@ mod tests { // only — so the capability is written into the serialized object. A // client keys entirely off this key: without it the three requests are // never sent, however well they are implemented. - let value = initialize_value().expect("the initialize result serializes"); + let value = initialize_value(false).expect("the initialize result serializes"); assert_eq!( value["capabilities"]["typeHierarchyProvider"], serde_json::json!(true), @@ -595,7 +630,7 @@ mod tests { // `ServerCapabilities` under the same JSON name, fails this immediately. #[test] fn the_json_insertion_disturbs_nothing_else_in_the_initialize_result() { - let mut with_insertion = initialize_value().expect("the initialize result serializes"); + let mut with_insertion = initialize_value(false).expect("the initialize result serializes"); let plain = serde_json::to_value(initialize_result()).expect("serializes on its own too"); let caps = with_insertion["capabilities"].as_object_mut().expect("capabilities is a JSON object"); @@ -611,6 +646,92 @@ mod tests { ); } + // ------------------------------------------------------------------ + // `rangesFormatting` (LSP 3.18) — the capability, on both wire shapes + // ------------------------------------------------------------------ + + /// `initialize` params carrying whatever a client said about + /// `rangesSupport`, as raw JSON — which is the only place it survives. + fn client_saying(ranges_support: serde_json::Value) -> serde_json::Value { + serde_json::json!({ + "processId": null, + "capabilities": { + "textDocument": { "rangeFormatting": { "rangesSupport": ranges_support } } + } + }) + } + + #[test] + fn ranges_formatting_support_is_read_from_the_raw_params_and_only_when_literally_true() { + assert!(ranges_formatting_support(&client_saying(serde_json::json!(true)))); + assert!(!ranges_formatting_support(&client_saying(serde_json::json!(false)))); + // Junk in that slot is not a yes. A client that means it sends `true`. + assert!(!ranges_formatting_support(&client_saying(serde_json::json!("yes")))); + assert!(!ranges_formatting_support(&client_saying(serde_json::Value::Null))); + // The 3.17 client: the key is not there at all. + assert!(!ranges_formatting_support(&serde_json::json!({ "capabilities": {} }))); + // And params that are not even an object — `Value::index` answers + // `Null` rather than panicking, which is the whole reason this is a + // JSON read and not a typed one. + assert!(!ranges_formatting_support(&serde_json::json!("nonsense"))); + assert!(!ranges_formatting_support(&serde_json::Value::Null)); + } + + #[test] + fn a_client_that_did_not_ask_sees_the_capability_exactly_as_it_always_was() { + // The gate's whole point: every client that shipped before this round + // must see the same byte on the wire. A bare `true` is the shape no + // client can misread, and one that never advertised `rangesSupport` + // will never send the request however it is advertised. + let value = initialize_value(false).expect("the initialize result serializes"); + assert_eq!( + value["capabilities"]["documentRangeFormattingProvider"], + serde_json::json!(true), + "{value:#?}" + ); + } + + #[test] + fn a_client_that_asked_sees_the_options_object_with_ranges_support() { + // `documentRangeFormattingProvider` is `boolean | + // DocumentRangeFormattingOptions` in the spec, and `rangesSupport` is + // a field on the options arm — so widening the bool to the object is + // how the spec says to answer, and it is the only way + // `vscode-languageclient` will register its multi-range provider. + let value = initialize_value(true).expect("the initialize result serializes"); + assert_eq!( + value["capabilities"]["documentRangeFormattingProvider"], + serde_json::json!({ "rangesSupport": true }), + "{value:#?}" + ); + // Single-range formatting is still advertised by that same key — the + // object is not an *extra* capability, it is the same one saying more. + assert!( + value["capabilities"]["documentRangeFormattingProvider"].is_object(), + "and never a second key: {value:#?}" + ); + assert_eq!(value["capabilities"]["documentRangeFormattingProvider"]["rangesSupport"], true); + } + + #[test] + fn widening_the_range_capability_disturbs_nothing_else_in_the_initialize_result() { + // The same proof `the_json_insertion_disturbs_nothing_else...` gives + // for `typeHierarchyProvider`, for the second inserted key: the two + // results must differ at exactly one key and be equal everywhere else. + let mut gated = initialize_value(true).expect("serializes"); + let plain = initialize_value(false).expect("serializes"); + let caps = gated["capabilities"].as_object_mut().expect("capabilities is a JSON object"); + assert_eq!( + caps.insert("documentRangeFormattingProvider".to_string(), serde_json::json!(true)), + Some(serde_json::json!({ "rangesSupport": true })), + "the one key the widening is supposed to replace" + ); + assert_eq!( + gated, plain, + "putting the bare `true` back must restore the ungated result exactly" + ); + } + #[test] fn on_type_formatting_asks_for_the_newline_and_the_semicolon_and_nothing_else() { // The trigger set is the feature: a client sends this request on every diff --git a/crates/lucisv_server/src/server.rs b/crates/lucisv_server/src/server.rs index e6ed0f6..35160f9 100644 --- a/crates/lucisv_server/src/server.rs +++ b/crates/lucisv_server/src/server.rs @@ -314,6 +314,11 @@ impl Server { let result = match method.as_str() { Formatting::METHOD => decode(request).and_then(|p| self.formatting(p)), RangeFormatting::METHOD => decode(request).and_then(|p| self.range_formatting(p)), + // LSP 3.18's multi-range form of the line above — `n` ranges, one + // round trip, one answer. Answered whether or not the capability + // was widened for this client: a request we can serve is not + // refused because the client asked without saying it would. + format::RANGES_FORMATTING => decode(request).and_then(|p| self.ranges_formatting(p)), // One keystroke, at most one edit, never a word to the user — see // `on_type_formatting`. OnTypeFormatting::METHOD => decode(request).and_then(|p| self.on_type_formatting(p)), @@ -697,6 +702,26 @@ impl Server { self.edits(result) } + /// `textDocument/rangesFormatting` — LSP 3.18's multi-range form. + /// + /// Line for line the handler above, with `ranges` where it has `range`: + /// the same settings ladder, the same engine, the same `edits` and the + /// same config warning. That is the point of the feature — a client asking + /// for five ranges gets one verified answer instead of five requests whose + /// edits it would have to reconcile itself. See + /// `docs/features/lsp-318-extras/README.md`. + fn ranges_formatting( + &mut self, + params: format::RangesFormattingParams, + ) -> Result { + let uri = params.text_document.uri; + let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) }; + let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options); + let result = format::ranges_formatting(doc, &settings.config, ¶ms.ranges); + self.warn_about_config(&uri, settings.problem); + self.edits(result) + } + /// `textDocument/onTypeFormatting` — the newline and the semicolon. /// /// Two things about it are unlike every other formatting entry, and both @@ -3421,6 +3446,171 @@ mod tests { assert!(session.shown().is_empty()); } + // ------------------------------------------------------------------ + // `textDocument/rangesFormatting` (LSP 3.18), through the real dispatch + // ------------------------------------------------------------------ + + /// One LSP range, as a client writes it. + fn json_range(sl: u32, sc: u32, el: u32, ec: u32) -> Value { + serde_json::json!({ + "start": { "line": sl, "character": sc }, + "end": { "line": el, "character": ec }, + }) + } + + fn ranges_result(session: &mut Session, uri: &Uri, ranges: Vec) -> Value { + session.result( + format::RANGES_FORMATTING, + serde_json::json!({ + "textDocument": { "uri": uri }, + "ranges": ranges, + "options": { "tabSize": 2, "insertSpaces": true }, + }), + ) + } + + fn range_result(session: &mut Session, uri: &Uri, range: Value) -> Value { + session.result( + RangeFormatting::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri }, + "range": range, + "options": { "tabSize": 2, "insertSpaces": true }, + }), + ) + } + + /// Four items on four lines, so two ranges can straddle one they leave. + const FOUR_ITEMS: &str = "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n"; + + #[test] + fn a_ranges_request_lays_out_every_range_it_names_in_one_answer() { + // The dispatch arm, end to end: a real request with a real `ranges` + // array, decoded by the hand-rolled params and answered by the real + // handler. Lines 2 and 4, leaving line 3 exactly as written. + let tree = Tree::new("rangesfmt"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), FOUR_ITEMS); + + let edits = + ranges_result(&mut session, &uri, vec![json_range(1, 0, 2, 0), json_range(3, 0, 4, 0)]); + assert_eq!( + edits[0]["newText"], "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n", + "{edits:#?}" + ); + // Still one whole-document edit, the shape `rangeFormatting` answers. + assert_eq!(edits.as_array().map(Vec::len), Some(1)); + assert_eq!(edits[0]["range"]["start"], serde_json::json!({ "line": 0, "character": 0 })); + assert!(session.shown().is_empty(), "a clean config says nothing"); + } + + #[test] + fn one_range_through_the_new_method_answers_what_the_old_method_answers() { + // The two requests are the same engine, and a client must never have + // to choose between them for correctness — only for round trips. + let tree = Tree::new("rangesone"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), FOUR_ITEMS); + + for range in [ + json_range(1, 0, 2, 0), + json_range(1, 4, 1, 4), + json_range(0, 0, 99, 0), + json_range(4, 0, 4, 9), + ] { + let one = range_result(&mut session, &uri, range.clone()); + let many = ranges_result(&mut session, &uri, vec![range.clone()]); + assert_eq!(one, many, "{range}"); + } + } + + #[test] + fn an_empty_ranges_array_is_answered_with_no_edit_and_no_word() { + let tree = Tree::new("rangesempty"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), FOUR_ITEMS); + + assert_eq!(ranges_result(&mut session, &uri, vec![]), serde_json::json!([])); + assert!(session.shown().is_empty(), "an empty ask is not a problem"); + } + + #[test] + fn a_ranges_request_for_a_buffer_the_server_does_not_hold_is_null() { + // What every other formatting handler answers for an unknown document. + let tree = Tree::new("rangesunknown"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri"); + assert_eq!(ranges_result(&mut session, &uri, vec![json_range(0, 0, 1, 0)]), Value::Null); + } + + #[test] + fn a_refusal_is_the_same_answer_and_the_same_popup_on_both_range_methods() { + // No partial output (CLAUDE.md invariant #1), and the multi-range path + // reaches the *same* `edits()` — so the answer and the message must be + // equal values, not merely similar shapes. + let tree = Tree::new("rangesrefuse"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire ;\nendmodule\n"); + let _ = session.drain(); + + let one = range_result(&mut session, &uri, json_range(0, 0, 1, 0)); + let said_once = session.shown(); + let many = + ranges_result(&mut session, &uri, vec![json_range(0, 0, 1, 0), json_range(2, 0, 3, 0)]); + let said_again = session.shown(); + + assert_eq!(one, serde_json::json!([]), "no edit at all"); + assert_eq!(one, many, "byte-identical answers"); + assert_eq!(said_once.len(), 1, "{said_once:?}"); + assert_eq!(said_once, said_again, "and byte-identical ERRORs: {said_again:?}"); + } + + #[test] + fn a_broken_config_warns_once_from_the_multi_range_path_too() { + // It shares `warn_about_config` with the other explicit formatting + // requests, dedup included — this is an explicit request the user made, + // not a keystroke, so it does speak. + let tree = Tree::new("rangesconfig"); + std::fs::write(tree.path.join(".git"), "gitdir: nowhere\n").expect("write .git"); + std::fs::write(tree.path.join("lucisv.toml"), "bogus = 1\n").expect("write config"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), FOUR_ITEMS); + let _ = session.drain(); + + let edits = ranges_result(&mut session, &uri, vec![json_range(1, 0, 2, 0)]); + assert_eq!( + edits[0]["newText"], + "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n" + ); + let warned = session.shown(); + assert_eq!(warned.len(), 1, "{warned:?}"); + assert_eq!(warned[0].0, MessageType::WARNING); + assert!(warned[0].1.contains("unknown key `bogus`"), "{warned:?}"); + // And once per buffer state, exactly as the other paths. + let _ = ranges_result(&mut session, &uri, vec![json_range(1, 0, 2, 0)]); + assert!(session.shown().is_empty(), "said once, not once per request"); + } + + #[test] + fn params_that_do_not_carry_ranges_are_invalid_params_and_not_a_panic() { + // The params are hand-rolled, so their refusal is ours to get right: + // a missing `ranges` is a client bug and answers an error, never a + // guess about what the client meant. + let tree = Tree::new("rangesjunk"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), FOUR_ITEMS); + + let response = session.request( + format::RANGES_FORMATTING, + serde_json::json!({ + "textDocument": { "uri": uri }, + "options": { "tabSize": 2, "insertSpaces": true }, + }), + ); + let error = response.response_result.expect_err("missing `ranges` is not answerable"); + assert_eq!(error.code, lsp_server::ErrorCode::InvalidParams as i32, "{error:?}"); + } + #[test] fn a_keystroke_the_engine_refuses_is_answered_with_silence_and_not_a_popup() { // The deliberate contrast with `textDocument/formatting` and the save diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index 76431ed..6fb6b4d 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -237,6 +237,129 @@ fn range_formatting_is_advertised_and_formats_only_the_selection() { let _ = std::fs::remove_dir_all(&dir); } +/// Four items on four lines, so two ranges can straddle one they leave alone. +const FOUR_ITEMS: &str = "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n"; + +#[test] +fn ranges_formatting_is_advertised_to_a_client_that_asked_and_formats_every_range() { + // The 3.18 leg, over the real wire: the capability is only widened for a + // client that sent `rangesSupport`, and the request that widening unlocks + // lays out every range it names in one answer. + let dir = temp_dir("rangesfmt"); + let file = dir.join("m.sv"); + std::fs::write(&file, FOUR_ITEMS).expect("write"); + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", file.display()); + + let ranges = |id: u32, ranges: &str| { + frame(&format!( + r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/rangesFormatting","params":{{"textDocument":{{"uri":"{uri}"}},"ranges":{ranges},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"# + )) + }; + let line = |n: u32| { + format!( + r#"{{"start":{{"line":{n},"character":0}},"end":{{"line":{},"character":0}}}}"#, + n + 1 + ) + }; + let session = [ + // The 3.18 client, saying so exactly as `vscode-languageclient` does. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"rangeFormatting":{{"dynamicRegistration":true,"rangesSupport":true}}}}}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(FOUR_ITEMS).expect("json") + )), + // Lines 2 and 4, leaving 3 alone — and sent *unsorted*, which the + // server must normalize rather than take in the order it arrived. + ranges(2, &format!("[{},{}]", line(3), line(1))), + // An empty ask is answered, not refused. + ranges(3, "[]"), + // Every line at once is the whole-file format. + ranges(4, &format!("[{},{},{},{},{}]", line(0), line(1), line(2), line(3), line(4))), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + + let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response"); + assert_eq!( + initialize["result"]["capabilities"]["documentRangeFormattingProvider"], + serde_json::json!({ "rangesSupport": true }), + "a client that asked gets the options object, not the bare `true`" + ); + + assert_eq!( + new_text(&messages, 2), + "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n", + "both named lines laid out, the one between them byte-for-byte" + ); + let empty = messages.iter().find(|m| m["id"] == 3).expect("response"); + assert_eq!(empty["result"].as_array().expect("an array").len(), 0, "an empty ask"); + assert!(empty["error"].is_null(), "and never an error: {empty:#?}"); + assert_eq!( + new_text(&messages, 4), + "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n", + "every line named is a whole-file format" + ); + // Nothing was said to the user on any of the three. + assert!( + !messages.iter().any(|m| m["method"] == "window/showMessage"), + "a clean buffer and a clean config say nothing: {messages:#?}" + ); + + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_3_17_client_still_sees_the_bare_true_it_always_saw() { + // The gate, over the wire: a client that did not advertise `rangesSupport` + // must see the capability byte-for-byte as it was before this round — and + // is still answered if it sends the request anyway. + let dir = temp_dir("rangesfmt317"); + let file = dir.join("m.sv"); + std::fs::write(&file, FOUR_ITEMS).expect("write"); + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", file.display()); + + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"rangeFormatting":{{"dynamicRegistration":true}}}}}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(FOUR_ITEMS).expect("json") + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/rangesFormatting","params":{{"textDocument":{{"uri":"{uri}"}},"ranges":[{{"start":{{"line":1,"character":0}},"end":{{"line":2,"character":0}}}}],"options":{{"tabSize":2,"insertSpaces":true}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + + let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response"); + assert_eq!( + initialize["result"]["capabilities"]["documentRangeFormattingProvider"], + serde_json::json!(true), + "unchanged for every client that shipped before this round" + ); + assert_eq!( + new_text(&messages, 2), + "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n", + "the handler is registered unconditionally; only the advertising is gated" + ); + + let _ = std::fs::remove_dir_all(&dir); +} + /// A file with a tab (`no-tabs`, Safe fix) and a trailing space /// (`no-trailing-whitespace`, Safe fix) — and a name matching its module, so /// `module-filename` stays quiet and every finding here is fixable. diff --git a/docs/features/lsp-318-extras/README.md b/docs/features/lsp-318-extras/README.md new file mode 100644 index 0000000..90ca779 --- /dev/null +++ b/docs/features/lsp-318-extras/README.md @@ -0,0 +1,585 @@ +# lsp-318-extras + +## Goal + +Close the last box of TODO.md §9c — the three LSP 3.18 additions the audit +named — by shipping the one a real client can consume today and writing down, +with evidence, why the other two cannot be shipped honestly yet. + +**Shipped:** `textDocument/rangesFormatting`, multi-range formatting in one +request. This is what an editor sends for *format the lines I modified* and for +*format each of my multi-cursor selections*: `n` ranges, one round trip, one +answer. lucisv's range engine already takes an `n`-range `LineRanges` natively +(that is what `--lines 3-9,40` is), so the request is a thin adapter over the +same verified, all-or-nothing engine `textDocument/rangeFormatting` runs — not +a second formatter with a second contract. + +**Parked, with the assessment in [Parked](#parked-and-why) below:** snippet +edits in a `WorkspaceEdit`, and `workspace/textDocumentContent`. Neither has a +shipping client that could consume it, and CLAUDE.md's "nothing is advertised +that is not implemented" has a mirror image — nothing is implemented that +nothing can call. + +## What `rangesFormatting` is + +LSP 3.18 (proposed), `textDocument/rangesFormatting`: + +```jsonc +// params +{ "textDocument": { "uri": … }, "ranges": [ Range, … ], "options": FormattingOptions } +// result +TextEdit[] | null +``` + +The server declares it by widening its existing `documentRangeFormattingProvider` +from the bare `true` to the options object with `rangesSupport: true` — the +`boolean | DocumentRangeFormattingOptions` union the capability has always had: + +```jsonc +"documentRangeFormattingProvider": { "rangesSupport": true } +``` + +The client declares it as `textDocument.rangeFormatting.rangesSupport: true`. + +### Semantics: the union of the ranges, on the one engine + +An `n`-range request is exactly the single-range request with `n` line spans +instead of one. Concretely, `format::ranges_formatting` is now the only entry +point and `range_formatting` is the one-element call of it: + +1. Each protocol `Range` becomes a 1-based inclusive line span through the + **same** `lines_of` conversion single-range formatting used before this + round (only line numbers survive; an end at character 0 of a later line + names the line before it). The conversion was extracted, not copied — a + second spelling of that rule is a second thing to get wrong. +2. The spans go into one `LineRanges::new`, which **sorts and merges** them. + Overlapping, adjacent and unsorted input from the client all normalize + there, and they normalize in the CLI's own constructor rather than in a + second copy written for the LSP. +3. One `format_range` call. The all-or-nothing contract, the equivalence check + and the replayed-selection convergence check all ride through unchanged, + because this is literally the call `--lines 3-9,40` makes. +4. One whole-document `TextEdit`, or none when the text did not change — + `rangeFormatting`'s reply shape, for `rangeFormatting`'s reason (the + engine's contract is over the file; what makes a request a *range* format is + which constructs were laid out). + +Consequences worth stating, all tested: + +| client sends | answer | +|---|---| +| ranges out of order (`[7-8, 2-3]`) | same as sorted — `LineRanges` sorts | +| overlapping ranges (`[2-4, 3-6]`) | same as the merged range `2-6` | +| adjacent ranges (`[2-2, 3-3]`) | same as `2-3`; merging changes no answer | +| the same range twice | same as once | +| `"ranges": []` | `[]`, no edit, no message — an empty ask is not an error | +| one huge range over the buffer | the whole-file format, as `rangeFormatting` already answers | +| a buffer the engine refuses | `[]` **and** a `window/showMessage` ERROR, byte-identical to `rangeFormatting`'s refusal | +| a buffer this server has not been sent | `null`, as every other formatting handler answers | + +The refusal path is not "similar to" `rangeFormatting`'s — it is the same +`Server::edits` and the same `Server::warn_about_config`, reached from a +dispatch arm that differs only in how the params were decoded. There is one +test that asserts the two refusals are equal *values* rather than asserting the +shape of each. + +### The capability decision: gated on the client, not advertised blind + +`documentRangeFormattingProvider` is `boolean | DocumentRangeFormattingOptions` +in the spec, so sending the object form is legal against 3.17 and 3.18 alike, +and `vscode-languageclient` reads it through `getRegistrationOptions`, which +handles both arms (`features.js:230`: `Is.boolean(capability) && capability === true ? { documentSelector } : { ...capability, documentSelector }`). +Advertising the object unconditionally would therefore *probably* be safe. + +It is still gated on the client having sent +`textDocument.rangeFormatting.rangesSupport: true`, for a reason that costs +nothing: + +- A client that did not ask will never send `rangesFormatting` however it is + advertised, so the object form buys that client exactly nothing. +- The bare `true` is the value every client has seen from this server since + round 18, and a bare boolean is the one shape *no* client can misread. A + hand-rolled client that tests `=== true` — the shape LSP servers have sent + for this capability for a decade — keeps working. +- The gate is one boolean read from the initialize params, and the request + handler is registered unconditionally, so a client that sends the request + without asking first is still answered. + +So: **a 3.17 client sees `true`, byte-for-byte what it saw before this round; a +3.18 client sees `{ "rangesSupport": true }`.** Both shapes are decoded from +the real `initialize` JSON in tests. + +`lsp-types` 0.97 cannot spell either half — its `DocumentRangeFormattingOptions` +carries only `workDoneProgress`, and its +`DocumentRangeFormattingClientCapabilities` is an alias for +`DynamicRegistrationClientCapabilities` with no `rangesSupport` field — so both +halves go through JSON: + +- **Out:** `initialize_value()` replaces the serialized + `documentRangeFormattingProvider` value, the precedent + `docs/features/type-hierarchy/README.md` set for `typeHierarchyProvider`. + Same function, same test discipline (the whole object is pinned, not just + the one key). +- **In:** the flag is read from the **raw** `initialize` params `Value` before + it is deserialized into `InitializeParams`, because the typed struct drops + the field. `main.rs` already had that raw value in hand. + +### Client reach — checked, not assumed + +- `editors/vscode/node_modules/vscode-languageclient@9.0.1` (the pinned + version) **already implements the request**: + `lib/common/formatting.js:74` sends `capability.rangesSupport = true`, and + `:109` registers `provideDocumentRangesFormattingEdits` *only if* + `options.rangesSupport` came back from the server. So before this round the + extension was asking for the feature and being told no. +- `vscode-languageserver-protocol@3.17.5` carries + `DocumentRangesFormattingRequest` and `DocumentRangesFormattingParams` + (`lib/common/protocol.d.ts:2900,2945`), so the wire shape implemented here is + that library's, not a reading of the spec text. +- `vscode-languageclient@9.0.1` requires `engines.vscode: ^1.82.0` and sets + `provideDocumentRangesFormattingEdits` on the provider it registers, so the + VS Code API exists at the version this extension already targets + (`editors/vscode/package.json` pins the same `^1.82.0`). +- Neovim's built-in client sends `rangeFormatting`, not `rangesFormatting`; it + loses nothing, because the gate leaves its capability exactly as it was. + +## Parked, and why + +Both items were assessed against the same three questions: does `lsp-types` +0.97 model it, does the client capability exist to read, and can the pinned +client stack apply it. An item that fails the third is parked — implementing a +protocol nothing on the other end speaks is how a server acquires a capability +that is a lie. + +### Snippet edits in `WorkspaceEdit` — parked + +3.18 lets a `WorkspaceEdit` carry a `SnippetTextEdit`, so `lucisv.addPort` +could drop the cursor on the new port's name with the type as a tabstop +instead of leaving the caret where the apply happened to end. + +| question | answer | evidence | +|---|---|---| +| `lsp-types` 0.97 models `SnippetTextEdit`? | **No** | `grep -rn 'SnippetTextEdit' lsp-types-0.97.0/src/` → nothing | +| the client capability field exists to read? | **No** | `WorkspaceEditClientCapabilities` (`lib.rs:1071`) has exactly `documentChanges`, `resourceOperations`, `failureHandling`, `normalizesLineEndings`, `changeAnnotationSupport` — no `snippetEditSupport` | +| the pinned client can apply one? | **No** | `grep -rln 'snippetEditSupport\|SnippetTextEdit' editors/vscode/node_modules/` → no hits at all, in either `vscode-languageclient@9.0.1` or `vscode-languageserver-protocol@3.17.5` | + +All three fail, and the third is the one that decides it: the extension's +client library has no code path that would turn a `snippet` edit into a +tabstop, so a server sending one would be sending an object the client either +drops or applies as a literal `${1:name}` written into the user's buffer — +which is the exact failure mode `snippet_support()` already exists to prevent +on the completion path (`main.rs`: "a literal `${1:clk}` written into a buffer +is worse than no tabstops at all"). + +**Re-check trigger, exactly:** when `editors/vscode/package.json` moves off +`vscode-languageclient@9.0.1`, grep the new tree for `snippetEditSupport`. It +appears when the client library implements this; that string in +`node_modules/vscode-languageserver-protocol/lib/common/protocol.d.ts` is the +whole signal. The server side then needs (a) a `snippetEditSupport` read added +next to `apply_edit_support` in `main.rs`, and (b) `ports.rs`'s `WorkspaceEdit` +to emit `{ "snippet": { "value": … } }` in place of `newText` for the one edit +that creates the port, gated on that flag. + +### `workspace/textDocumentContent` — parked + +3.18's server-provided read-only documents. The tempting use is a +`lucisv-expanded:` URI serving the macro-expanded view that +`docs/features/macro-expansion/README.md` currently shows only inside a hover +card. + +| question | answer | evidence | +|---|---|---| +| `lsp-types` 0.97 models it? | **No** | `grep -rn 'textDocumentContent' lsp-types-0.97.0/src/` → only `TextDocumentContentChangeEvent`, an unrelated sync type | +| the pinned client can serve one? | **No** | `grep -rln 'textDocumentContent' editors/vscode/node_modules/` → no hits | +| the extension could route it anyway? | **No** | serving a custom URI scheme in VS Code needs `workspace.registerTextDocumentContentProvider` in the extension host; `editors/vscode/extension.js` deliberately registers no providers of its own — it starts the server and gets out of the way | + +This one is parked twice over: the client library does not implement the +request, *and* the thin extension is the wrong shape to consume it. Note also +that the feature it would serve does not exist yet in a document-sized form — +`hover.rs` expands one macro call one step (`macro-expansion`'s stated scope: +"One step, display only"), so there is no whole-file expanded text to serve. +A future round wanting this wants a preprocessor first, which TODO.md §7 says +lucisv does not have and does not want. + +**Re-check trigger, exactly:** the same `node_modules` grep, for +`textDocumentContent`, plus a decision to give `extension.js` a content +provider. Both, not either. + +## Assumptions + +- **`LineRanges::new` is the one normalizer.** Sorting, merging overlaps and + folding adjacent spans happen there, once, for the CLI and both LSP + formatting requests. This round adds no second copy and asserts the + normalization through the public answer rather than restating it. +- **A client sends ranges that name lines in the buffer it opened.** Nothing + checks that a range's lines exist: past-EOF spans clamp in the engine (the + `--lines` rule, documented in `range-formatting`), and a range on a document + the server does not hold answers `null` before any of this runs. +- **Only line numbers matter.** Same as `rangeFormatting`: the UTF-16 columns + are thrown away by `lines_of`, so there is nothing to get wrong about them. +- **A client that advertises `rangesSupport` reads the union form of + `documentRangeFormattingProvider`.** It is the shape its own protocol + library declares; a client asking a 3.18 question in 3.17-only JSON terms is + not a client that exists. +- **Parking is assessed against the *pinned* client**, `vscode-languageclient@9.0.1` + as vendored in `editors/vscode/node_modules`, not against what some + unreleased client might do. The re-check triggers above are written so the + assessment can be redone in one grep. + +## Handshakes + +**Consumed from `vlog_formatter`:** `format_range`, `LineRanges::new`, +`Config`. Nothing new is asked of `vlog_formatter` and nothing in it was +changed — the multi-range engine has existed since round 18 for `--lines`. + +**Consumed from `lsp_types`:** `Range`, `TextEdit`, `FormattingOptions`, +`TextDocumentIdentifier`. The 3.18 params type is hand-rolled here +(`format::RangesFormattingParams`) because 0.97 does not carry it, the same way +`pairs::ScopePairsParams` is hand-rolled for a custom method. + +**Promised to `crates/lucisv_server` callers:** + +- `format::ranges_formatting(&Document, &Config, &[Range]) -> Result, String>` + is the new entry point, and `format::range_formatting` is now defined as its + one-element case. Both keep the old signature and the old answer. +- `format::RANGES_FORMATTING` is the method string, and + `format::RangesFormattingParams` the decoded params. +- `main::initialize_value` now takes one `bool` (whether to widen the range + formatting capability). Callers: `main()` and the tests in `main.rs`. + +**Promised to `editors/vscode`:** nothing to do. `extension.js` is untouched +and needs no change — `vscode-languageclient` registers its multi-range +provider off the server's capability alone, so the feature turns on when the +user updates the server binary. `smoke.js` was extended (its `initialize` now +sends the `rangesSupport` capability the real client sends, plus one +`rangesFormatting` leg), because a pre-publish check that advertises less than +the shipping client would be checking a shape no user ever sees. + +**Changed for another module:** none. `verify.rs`, `vlog_formatter`, +`vlog_parser`, `vlog_semantic`, `vlog_linter`, `crates/lucisv`, +`editors/vscode/extension.js`, `corpus/` and the `.cases` tables are all +untouched. + +**`verify.rs` is untouched** — `git diff --quiet` on it exits 0. No +normalization was added, broadened or weakened, so CLAUDE.md invariant #4's +attack-test requirement does not apply to this round. It could not: every byte +this round produces comes out of `format_range`, which runs the unchanged net +over the whole buffer. + +## Status / TODO + +- [x] `format.rs`: `lines_of` extracted from `range_formatting`; `ranges_formatting`; + `range_formatting` redefined as its one-element case; `RANGES_FORMATTING` + and `RangesFormattingParams`. +- [x] `server.rs`: the `textDocument/rangesFormatting` dispatch arm, sharing + `edits` and `warn_about_config` with `rangeFormatting`. +- [x] `main.rs`: `ranges_formatting_support` read from the raw initialize + params; `initialize_value(bool)` widening the capability. +- [x] Tests — **+24**: 11 units in `format.rs`, 7 session tests in `server.rs`, + 4 capability tests in `main.rs`, 2 e2e legs over the real binary (one per + client shape), plus a `smoke.js` leg. +- [x] Docs: this README, `lucisv-server`'s capability table and Status, TODO.md + §9c's last box. +- [x] **Parked:** snippet `WorkspaceEdit` edits — assessment above, with the + exact re-check trigger. +- [x] **Parked:** `workspace/textDocumentContent` — assessment above, with the + exact re-check trigger. +- [ ] **Not done, deliberately:** a per-range reply + (`TextEdit[]` with one edit per range). The engine's contract is over the + whole file, so the honest reply is the whole-document edit + `rangeFormatting` already sends. Splitting it into `n` edits would be a + claim about which bytes each range owns that nothing verifies. +- [ ] **Not done:** dynamic registration of the range-formatting provider. + The gate is decided once at `initialize` and never changes, so there is + nothing a registration would buy; a client that flips `rangesSupport` + mid-session does not exist. + +## Work log + +### 2026-08-27 — dev agent + +- Read `CLAUDE.md`, TODO.md §9c, and the Handshakes of `lucisv-server`, + `range-formatting`, `type-hierarchy` and `macro-expansion` before writing + anything. Baseline: `cargo test -p lucisv_server` **993 unit + 48 e2e**, + `cargo test --workspace` green, clippy silent, fmt clean. +- **Checked all three items against `lsp-types` 0.97 and the pinned client + before deciding anything.** The greps are in the sections above and are the + whole basis for the ship/park calls. The surprise was the good one: the + brief expected `vscode-languageclient@9.0.1` to be too old for + `rangesFormatting`, and it is not — 3.18 is newer than 9.0.1 as a *spec + version*, but this particular request was already implemented there, and the + library has been sending `rangesSupport: true` at this server for as long as + the extension has existed. lucisv was answering with a bare `true` and + turning it off. The other two items are as the brief guessed. +- **The engine took multiple ranges natively, so this is an adapter and not a + feature.** `LineRanges::new` sorts and merges (`range.rs:38`), which is + exactly the "normalize overlapping/adjacent/unsorted ranges" the brief asked + for, and `format_range` takes the merged list. So the whole implementation is + three lines of `map(lines_of)` around the constructor. **This is the point, + not a shortcut**: the verified contract, the equivalence check and the + replayed-selection convergence check ride through untouched because it is + literally the call `--lines 3-9,40` makes. +- **`range_formatting` became the one-element case of `ranges_formatting`, + rather than the two sharing a helper.** The brief allowed either. Defining + one as the other is stronger: there is no shape of buffer or range for which + the two can answer differently, which is what makes the refusal-equality test + (`a_refused_buffer_is_refused_identically_whichever_range_request_asked`) an + assertion about the code rather than a coincidence someone has to maintain. +- **The line conversion was extracted, not copied** (`lines_of`), and pinned + directly by a test — because it is now shared, a change to it moves two + requests at once and the test says what it promises. +- **One latent panic fixed in passing.** The old conversion wrote + `range.end.line + 1`, which overflows in a debug build for an end line of + `u32::MAX`. `saturating_add`, with a test. No behavior change for any range + an editor can produce; it is CLAUDE.md's no-panic rule for library paths. +- **The capability decision took the conservative arm, and it cost nothing.** + The object form is spec-legal for a 3.17 client and + `vscode-languageclient` handles the union (`features.js:230`), so + advertising it unconditionally would very probably be fine. But a client + that never sent `rangesSupport` gains exactly nothing from the object, and a + bare boolean is the one shape nothing can misread — so the widening is gated + on the client's own flag and **every client that shipped before this round + sees a byte-identical `initialize` result**, asserted over the wire by + `a_3_17_client_still_sees_the_bare_true_it_always_saw`. The pre-existing e2e + assertion `documentRangeFormattingProvider == true` needed no edit, which is + the same fact stated by an older test. +- **The client flag has to be read from the raw params.** `lsp-types` 0.97 + aliases `DocumentRangeFormattingClientCapabilities` to the plain + dynamic-registration struct, so `serde_json::from_value::` + discards `rangesSupport` before anything can look at it. `main()` already had + the raw `Value` in hand, so the read is one line placed before the decode. + Symmetric with the JSON insertion on the way out, and documented as such. +- **The handler is unconditional; only the advertising is gated.** A client + that sends the request without having asked is answered rather than told the + method does not exist — refusing a request we can serve because of a + handshake detail would be the server being pedantic at the user's expense. +- **`smoke.js` was changed in one substantive way**: its `initialize` now sends + the `rangeFormatting.rangesSupport` capability, because that is what the real + extension's client library sends and the smoke test's stated job is to + "spawn the server exactly the way extension.js does". Without it the smoke + test would assert a capability shape no real user ever sees. The new leg + sends two ranges and asserts both that the named line moved and that a line + no range named kept its bytes. +- **Nothing outside `crates/lucisv_server` and `editors/vscode/smoke.js` was + touched.** `verify.rs`, `vlog_formatter`, `vlog_parser`, `vlog_semantic`, + `vlog_linter`, `crates/lucisv`, `corpus/`, the `.cases` tables and + `docs/site/` are all unmodified (`git status --porcelain` names seven files + — three server sources, its e2e, `smoke.js`, `TODO.md` and the + `lucisv-server` README — plus this directory). No new dependency. Did not run + `git commit`/`git push`. + +**Results.** + +- `cargo test --workspace`: **2176 passed, 0 failed** across 34 test binaries. + This feature's crate: `lucisv_server` unit **993 → 1015** (+11 `format.rs`, + +7 `server.rs`, +4 `main.rs`), e2e **48 → 50**. +- `cargo test -p vlog_formatter`: **180 passed, 0 failed** — untouched, and + `git diff --quiet crates/vlog_formatter` exits 0, so the snapshot and + idempotency suites are green for the same reason they were yesterday. +- `cargo clippy --workspace --all-targets`: silent, 0 warnings. + `cargo fmt --all --check`: clean. +- `node editors/vscode/smoke.js target/release/lucisv-server`: **OK**, 10 + messages (was 9), the new `rangesFormatting` leg included. +- **No corpus run and no `verify.rs` attack tests**, and the reason is + structural rather than an omission: this round adds no formatter code path + at all. Every byte it can emit comes out of `format_range` with a + `LineRanges` the CLI could equally have built, so the corpus evidence in + `docs/features/range-formatting/README.md` (578 files, 8236 range trials, 0 + refusals) covers it unchanged, and CLAUDE.md invariant #4 does not apply + because no normalization was added, broadened or weakened. + +Files added: `docs/features/lsp-318-extras/README.md`. +Files edited: `crates/lucisv_server/src/{format,server,main}.rs`, +`crates/lucisv_server/tests/e2e.rs`, `editors/vscode/smoke.js`, `TODO.md`, +`docs/features/lucisv-server/README.md`. + +## QA log + +### 2026-08-27 — QA agent + +**Gates, re-run clean.** + +- `cargo fmt --all --check`: clean. +- `cargo clippy --workspace --all-targets -- -D warnings`: silent (forced a + rebuild with `touch` on the three changed sources first, since the initial + run was cache-hit and could have hidden a stale result). +- `cargo test --workspace`: **2176 passed, 0 failed**, 34 binaries — hand-summed + every `test result:` line to confirm the dev's total rather than trusting it. + `lucisv_server` unit **1015** (993→1015, +22: 11 `format.rs` + 7 `server.rs` + + 4 `main.rs`), e2e **50** (48→50, +2) — matches the claimed +24 exactly. +- `cargo test -p vlog_formatter`: **180 passed, 0 failed**. +- `git diff --quiet crates/vlog_formatter`: exit 0, confirmed myself. + `find . -iname verify.rs` → `crates/vlog_formatter/src/verify.rs`, + `git diff --quiet` on it: exit 0. `git status --porcelain docs/site/`: empty. +- `cargo build --release -p lucisv_server` + + `node editors/vscode/smoke.js target/release/lucisv-server`: **OK**, 10 + messages, against the real release binary. + +**Verdict, per attack surface — all verified-clean, no findings, no fixes +needed.** + +1. **`range_formatting` redefinition.** Enumerated callers by grep: only + `server.rs`'s `range_formatting` handler and `on_type.rs`'s `;`-trigger + (`format::range_formatting` at `on_type.rs:83` and its test at + `on_type.rs:1100`) call `format::range_formatting`; both keep the exact old + `(doc, config, range: Range)` signature, so neither needed to change and + neither did. Added a temporary probe in `format.rs`'s test module (added, + run, reverted before finishing — `git diff --stat` on the three sources + matches the pre-QA diffstat exactly: format.rs 229, server.rs 190, main.rs + 145 lines changed) covering: two ranges landing in one multi-line statement + merge into one edit, not a double format; reverse document order matches + forward order; a range at line 0 plus one at the last line lays out both + ends; 50 tiny ranges over a 200-line buffer format in well under a second + (no quadratic blowup observed); a format-off fence beats a range inside it + while a range outside the fence still formats — all through the real + `ranges_formatting` → `format_range` → `LineRanges::new` path, not mocked. + All five passed. The on-type `;` path's existing byte-identity test + (`on_type.rs:1100`, `format::range_formatting(...) ...` compared against + `range_formatting` output) was re-run unchanged and green — the dev's claim + that no consumer needed to change holds. +2. **Gated capability's raw-params read.** `ranges_formatting_support` at + `main.rs:373` is exactly `params["capabilities"]["textDocument"]["rangeFormatting"]["rangesSupport"] + == true`. Extracted the identical function body into a standalone probe + binary (character-for-character copy, diffed against the source to confirm) + and drove it with every shape the brief asked for beyond the dev's own test: + `textDocument` a string, `rangeFormatting` null, `rangesSupport` as the + string `"true"`, as `1`, as `[true]`, as an object, params entirely absent, + `capabilities` an array, and duplicate JSON keys for `rangesSupport` (both + orders). Result: **only literal boolean `true` gates**, every other shape + answers `false`; duplicate keys resolve last-value-wins, which is + `serde_json`'s standard (and harmless — the client controls both the first + and the last copy of its own key, so there's no cross-party spoofing + surface here). Then the two real-wire e2e legs + (`ranges_formatting_is_advertised_to_a_client_that_asked_and_formats_every_range`, + `a_3_17_client_still_sees_the_bare_true_it_always_saw` in `tests/e2e.rs`) + were re-run and pass: 3.17 client → bare `true`, confirmed byte-identical + to what `git show 17fb212` would have produced (the capability line is + untouched by this round's diff at the pre-round call site — verified by + inspecting `initialize_value(false)` reproduces `serde_json::json!(true)` + in `main.rs`'s own test at the same key). 3.18 client → the object. + `widening_the_range_capability_disturbs_nothing_else_in_the_initialize_result` + (`main.rs`) does insert-and-compare on the *whole* object, mirroring + `the_json_insertion_disturbs_nothing_else_in_the_initialize_result`'s + pattern for `typeHierarchyProvider` — confirmed it swaps exactly one key and + asserts full equality afterward, not a spot check. +3. **Union semantics.** All five scenarios verified through the real engine + (see item 1's temporary probes): merged single-statement ranges, reverse + order, line-0-and-last-line, 50-range timing sanity, and format-off fence + outranking an inside range while an outside range still formats. No + surprises; every one matched the README's stated semantics. +4. **Refusal equality.** `a_refused_buffer_is_refused_identically_whichever_range_request_asked` + (`format.rs`) and `a_refusal_is_the_same_answer_and_the_same_popup_on_both_range_methods` + (`server.rs`) both assert full `Result`/response equality *and* the + `window/showMessage` traffic (`session.shown()`) is identical, not just + "an error happened on both". Confirmed both tests actually run this + comparison (not just constructing it) and pass. +5. **`saturating_add` fix — deliberate-breakage protocol run for real.** + Reverted `format.rs:167` from `range.end.line.saturating_add(1)` back to + `range.end.line + 1`, ran + `cargo test -p lucisv_server --bin lucisv-server the_line_conversion_is_the_one_rangeformatting_always_used`: + it panicked — `attempt to add with overflow` at `format.rs:167:66` — exactly + as claimed. Restored the fix, re-ran the same test: passes. `git diff + --stat` on `format.rs` confirmed unchanged from the pre-revert state + afterward. +6. **Parked items' evidence — every grep re-run independently and matched + exactly.** `lsp-types-0.97.0` (found at + `~/.cargo/registry/src/index.crates.io-*/lsp-types-0.97.0`): + `grep -rn 'SnippetTextEdit' src/` → no match; + `WorkspaceEditClientCapabilities` at `lib.rs:1071` has exactly + `document_changes`, `resource_operations`, `failure_handling`, + `normalizes_line_endings` (truncated view, `change_annotation_support` + follows) and no `snippet_edit_support` field; + `grep -rn 'textDocumentContent' src/` → only `TextDocumentContentChangeEvent` + hits, an unrelated sync type, in `lib.rs` and `notebook.rs`. + `editors/vscode/node_modules/`: `grep -rln 'snippetEditSupport\|SnippetTextEdit'` + → no hits; `grep -rln 'textDocumentContent'` → no hits; + `grep -n 'registerTextDocumentContentProvider\|ContentProvider' extension.js` + → no hits. `DocumentRangeFormattingClientCapabilities` confirmed as a type + alias to `DynamicRegistrationClientCapabilities` + (`formatting.rs:11` in the same crate). The re-check triggers in the README + are literal, runnable grep commands — confirmed by running them as written. +7. **`smoke.js` change vs the real client.** `vscode-languageclient@9.0.1`'s + `lib/common/formatting.js:74` is `capability.rangesSupport = true;` inside + `DocumentRangeFormattingFeature.fillClientCapabilities` — exact match to the + dev's citation. Line 109 (`if (options.rangesSupport) {`) gates whether + `provideDocumentRangesFormattingEdits` gets attached to the registered + provider — also an exact match. `features.js`'s `getRegistrationOptions` + (the union-handling precedent cited) matches the description at the cited + behavior (boolean `true` → bare `{documentSelector}`, otherwise + `{...capability, documentSelector}`), modulo `Object.assign` vs spread + syntax, which are equivalent. `vscode-languageserver-protocol@3.17.5`'s + `protocol.d.ts:2900` (`DocumentRangesFormattingParams`) and `:2945` + (`DocumentRangesFormattingRequest`) both confirmed present at those exact + lines. `package.json` engines: both `editors/vscode/package.json` and the + vendored `vscode-languageclient/package.json` pin `^1.82.0` — confirmed. + Ran `smoke.js` against the freshly built release binary: **OK**, 10 + messages, matching the claimed count. +8. **CLAUDE.md compliance.** Grepped every added line (`git diff -U0`) in + `format.rs`, `server.rs`, `main.rs` for `.unwrap()`/`.expect()`/`panic!` + outside the `mod tests` boundary (found at `format.rs:231`, + `server.rs:1602`, `main.rs:495`) — every hit found is inside a test module; + zero in production code paths. No new `#[allow(...)]` anywhere in the diff. + `RangesFormattingParams` has a struct-level doc comment and undocumented + fields, matching the existing project convention for hand-rolled params + structs (`pairs::ScopePairsParams`/`ScopePair` follow the identical + pattern). README has each of the seven mandated sections (`Goal`, + `Assumptions`, `Handshakes`, `Status / TODO`, `Work log`, `QA log`, + `Review`) exactly once, plus two extra descriptive `##` subsections that + don't collide with the mandated set. `TODO.md`'s §9c item text is intact — + checkbox flipped `[ ]`→`[x]`, an appended `→ 2026-08-27 ...` note in the + same style as the two items directly above it, and it states both the + shipped item and the two parked items with reasons, as required. + `verify.rs`: confirmed untouched myself (`git diff --quiet` exit 0) — + correctly, since invariant #4's attack-test requirement doesn't apply here + (no normalization touched). + +**C. Beyond the list.** Added and ran three more temporary probes (in +`server.rs`'s test module, added/run/reverted, diff restored to the original +190-line diffstat afterward): + - `ranges` given as `{}` (an object, not an array) → `InvalidParams`, not a + panic. Pass. + - Extra unknown params fields (`workDoneToken`, an arbitrary nested object) + alongside a valid request → ignored, request answered normally + (`#[serde(deny_unknown_fields)]` is not on `RangesFormattingParams`, and + nothing needed it to be — serde's default is permissive). Pass. + - A client that advertises `rangesSupport` at `initialize` (so it gets the + gated capability) but then only ever calls the *old* + `textDocument/rangeFormatting` — confirmed the old path's answer is + byte-identical to what it always was; the gate is purely advertisement, + nothing about it changes `range_formatting`'s own behavior. Pass. + +**No findings.** No fixes were necessary — the round is clean at every attack +surface asked for, plus the three extra ones above. All temporary QA probe +tests were removed after running; the three touched source files are back to +the exact diffstat the dev left them at (`format.rs` 229, `server.rs` 190, +`main.rs` 145 lines changed — confirmed line-for-line via `git diff --stat` +before and after). + +**This is the last feature round of §9c.** Nothing here should block the +0.10.0 release cut: all gates green, `vlog_formatter` and `verify.rs` +untouched (so invariant #4 doesn't apply), the corpus argument for "no new +formatter code path" holds up under direct inspection (every byte still comes +out of the pre-existing `format_range`), and the two parked items are parked +with re-checkable, currently-true evidence rather than asserted from memory. +**Verdict: committable as-is.** + +## Review + +### 2026-08-27 — lead + +Reviewed the diff, the work log and the QA log; re-ran all gates myself, +clean. The right ending for the audit: one real feature shipped on the +engine that already knew how to do it, and two honest parkings with +evidence a future reader can re-run in one grep each. The round's +discovery — the pinned client library has been requesting multi-range +formatting all along, and our bare-boolean advertisement was the thing +refusing it — is the audit's thesis in miniature: the gaps were in what +we said, not only in what we did. The gated widening is the right +conservatism (pre-round clients see a byte-identical initialize result, +proven on the wire), and redefining range_formatting as the one-element +case makes the refusal-equality property structural, which QA verified +with differential probes through the real engine plus the +deliberate-breakage check on the overflow fix. Declining to split the +whole-document edit into per-range claims the engine never verified is +exactly the invariant culture applied to a reply shape. This completes +§9c and the LSP 3.18 audit's feature work. Accepted as shipped. diff --git a/docs/features/lucisv-server/README.md b/docs/features/lucisv-server/README.md index 20d5cb7..5c83717 100644 --- a/docs/features/lucisv-server/README.md +++ b/docs/features/lucisv-server/README.md @@ -18,6 +18,7 @@ looks like language knowledge in here is a bug or a `Handshake` request. |---|---|---| | `textDocument/formatting` | `vlog_formatter::format_source` | One whole-document `TextEdit`, and only when the text actually changed | | `textDocument/rangeFormatting` | `vlog_formatter::format_range` | Same edit shape; the LSP `Range`'s *lines* become the engine's `--lines` (round 18) | +| `textDocument/rangesFormatting` | `vlog_formatter::format_range` | LSP 3.18's multi-range form of the line above, and literally its `n`-range case: the ranges become one sorted, merged `LineRanges` and one engine call, so the all-or-nothing contract is over the union rather than per range. `range_formatting` is now defined as the one-element call of it, and the reply, the refusal and the config warning are the same values. Advertised by widening `documentRangeFormattingProvider` from `true` to `{ "rangesSupport": true }` — **only for a client that sent `textDocument.rangeFormatting.rangesSupport`**, so a 3.17 client sees exactly what it always saw; the handler itself is unconditional. `lsp-types` 0.97 spells neither half, so both go through JSON. See `docs/features/lsp-318-extras/README.md` | | `textDocument/onTypeFormatting` | `vlog_formatter::format_range` (for `;`); the token stream (for `\n`) | Two triggers, and only two. `;` range-formats the statement it ended, through the *same* engine `rangeFormatting` runs, over the `;`'s own line. `\n` re-indents the line it opened from block nesting — new logic outside the verified engine, so its edit can structurally only replace that one line's leading whitespace with spaces, and a corpus-wide agreement test forbids it from ever disagreeing with the printer. **Never speaks**: a refusal is `[]` with no `showMessage`, and a broken `lucisv.toml` is not reported here either (the dedup is re-armed by the `didChange` every keystroke produces). Advertised unconditionally — the client's own `editor.formatOnType` is the opt-in. See `docs/features/on-type-formatting/README.md` | | `textDocument/willSaveWaitUntil` | `vlog_formatter::format_source` | Format-on-save, protocol-native, for the editors that have no format-on-save of their own. **Off unless `lucisv.formatOnSave` is pushed**, and the decline is `null` — a capable client asks before every save, and a client with its own format-on-save would otherwise format twice. When on it is `textDocument/formatting` with a different trigger: the same engine, the same all-or-nothing edit, and the settings ladder minus its `tabSize` rung (the request carries no `FormattingOptions`). See `docs/features/will-save-wait-until/README.md` | | `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didChange`/`didSave`, once per notification — **only for a client that does not pull**. See `docs/features/pull-diagnostics/README.md` | @@ -624,6 +625,16 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory: completing TODO.md §9b): the loop reads in bursts and answers a queued request whose cancel is in the same burst with `RequestCancelled`, order across the burst unchanged. `docs/features/cancel-request/README.md`. +- [x] `textDocument/rangesFormatting` — delivered by **lsp-318-extras** + (2026-08-27, completing TODO.md §9c): LSP 3.18's multi-range format, + served as the `n`-range case of the one-range handler over the same + engine. The capability is widened from `true` to + `{ "rangesSupport": true }` only for a client that asked, so no client + that shipped before it sees a different byte. + `docs/features/lsp-318-extras/README.md`, which also records the two + 3.18 items **parked** with their evidence and re-check triggers: snippet + `WorkspaceEdit` edits and `workspace/textDocumentContent`, neither of + which the pinned `vscode-languageclient@9.0.1` can consume. - [ ] **Not done:** editor packaging (the VS Code extension and the `lspconfig` snippet are their own TODO.md §6 item). diff --git a/editors/vscode/smoke.js b/editors/vscode/smoke.js index c186443..f2f6939 100644 --- a/editors/vscode/smoke.js +++ b/editors/vscode/smoke.js @@ -79,7 +79,20 @@ const brokenUri = `file://${process.cwd()}/smoke_scratch_broken.sv`; server.stdin.end( Buffer.concat([ - frame({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { processId: process.pid, rootUri: null, capabilities: {} } }), + // `rangeFormatting.rangesSupport` is what vscode-languageclient 9.0.1 + // itself sends (lib/common/formatting.js), and the server only widens + // `documentRangeFormattingProvider` for a client that sent it — so the + // capability this asserts below is the one the real extension sees. + frame({ + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + processId: process.pid, + rootUri: null, + capabilities: { textDocument: { rangeFormatting: { dynamicRegistration: true, rangesSupport: true } } }, + }, + }), frame({ jsonrpc: '2.0', method: 'initialized', params: {} }), frame({ jsonrpc: '2.0', @@ -122,6 +135,23 @@ server.stdin.end( method: 'textDocument/formatting', params: { textDocument: { uri }, options: { tabSize: 2, insertSpaces: true } }, }), + // Multi-range formatting (LSP 3.18): two ranges, one round trip. Lines 2 + // and 8 of SOURCE (0-based 1 and 7) are `wire a;` and `initial fork`; only + // the first moves under `indent = 4`, so the answer proves both that the + // request is served and that it left the range between them alone. + frame({ + jsonrpc: '2.0', + id: 7, + method: 'textDocument/rangesFormatting', + params: { + textDocument: { uri }, + ranges: [ + { start: { line: 7, character: 0 }, end: { line: 8, character: 0 } }, + { start: { line: 1, character: 0 }, end: { line: 2, character: 0 } }, + ], + options: { tabSize: 2, insertSpaces: true }, + }, + }), frame({ jsonrpc: '2.0', id: 2, method: 'shutdown', params: null }), frame({ jsonrpc: '2.0', method: 'exit', params: null }), ]), @@ -231,6 +261,27 @@ server.on('close', (code) => { fail(`the editor tab size won over the pushed setting:\n${indented}`); } + // Multi-range formatting, and the capability shape that unlocks it. A client + // library registers its multi-range provider only when the server answers + // with the options object; a bare `true` here means the feature is dark. + const ranges = capabilities.documentRangeFormattingProvider; + if (!ranges || ranges.rangesSupport !== true) { + fail(`a client advertising rangesSupport must get the options object back, got ${JSON.stringify(ranges)}`); + } + const ranged = messages.find((m) => m.id === 7); + if (!ranged) fail('no textDocument/rangesFormatting response'); + if (ranged.error) fail(`rangesFormatting failed: ${JSON.stringify(ranged.error)}`); + if (!Array.isArray(ranged.result) || ranged.result.length !== 1) { + fail(`expected one edit from rangesFormatting, got ${JSON.stringify(ranged.result)}`); + } + const partial = ranged.result[0].newText; + if (!partial.includes('\n wire a;')) { + fail(`the named line was not laid out:\n${partial}`); + } + if (!partial.includes('\n initial begin')) { + fail(`a line no range named must keep its own bytes:\n${partial}`); + } + const shutdown = messages.find((m) => m.id === 2); if (!shutdown) fail('no shutdown response'); if (shutdown.error) fail(`shutdown failed: ${JSON.stringify(shutdown.error)}`);