TODO §66.2: the server's range, ranges and on-type formatting run on format_selection
textDocument/rangeFormatting, rangesFormatting and the on-type ';' now format the selected block in place of the enclosing module-level item; the reply is still one whole-document edit. On-type ';' now answers in a buffer whose error is elsewhere and adds no final newline. topo: the server → formatter edge and the selection-formatting row. Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
1 parent
3598a9145e
commit
2854bcaa2f
5 files changed
+144
-19
No files matched your search
@@ -6,13 +6,16 @@
|
||||
//! 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.
|
||||
//! not which bytes it was allowed to replace. The range requests go through
|
||||
//! `format_selection`: the smallest run of sibling items or statements the
|
||||
//! selection covers, laid out at the indentation it was written at — see
|
||||
//! `docs/features/selection-formatting/README.md`.
|
||||
|
||||
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 vlog_formatter::{format_selection, format_source, Config, LineRanges};
|
||||
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::state::Document;
|
||||
@@ -122,10 +125,12 @@ pub fn range_formatting(
|
||||
///
|
||||
/// 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.
|
||||
/// unsorted input from the client all reach the same answer. Each merged span
|
||||
/// selects its own target (targets that overlap are re-selected from the hull
|
||||
/// of their spans), but no range is formatted on its own — one
|
||||
/// `format_selection` call lays out and verifies them all, 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
|
||||
@@ -140,7 +145,7 @@ pub fn ranges_formatting(
|
||||
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())?;
|
||||
let formatted = format_selection(&doc.text, config, &lines).map_err(|e| e.to_string())?;
|
||||
if formatted == doc.text {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -700,6 +705,39 @@ mod tests {
|
||||
assert!(edit.new_text.contains("é ✓ 🎉"), "comments are never dropped");
|
||||
}
|
||||
|
||||
/// A file indented four spaces with a `case` nested in an `always`: the
|
||||
/// shape VS Code's "Format Selection" most often sends.
|
||||
const NESTED: &str = "module m;\n always @* begin\n case (s)\n 0: y=a;\n default:y=b;\n endcase\n z = 1;\n end\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn a_selected_case_is_laid_out_alone_at_the_indentation_it_starts_at() {
|
||||
let edit = ranged(NESTED, at(2, 0, 6, 0)).expect("formats").expect("changed");
|
||||
assert_eq!(
|
||||
edit.new_text,
|
||||
"module m;\n always @* begin\n case (s)\n 0: y = a;\n default: y = b;\n endcase\n z = 1;\n end\nendmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tab_indented_selection_keeps_its_tabs() {
|
||||
let text = "module m;\n\talways @* begin\n\t\tx=1;\n\tend\nendmodule\n";
|
||||
let edit = ranged(text, at(2, 0, 2, 4)).expect("formats").expect("changed");
|
||||
assert_eq!(edit.new_text, "module m;\n\talways @* begin\n\t\tx = 1;\n\tend\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parse_error_outside_the_selection_does_not_block_it() {
|
||||
let text = "module m;\n always @* begin\n x=1;\n end\n assign y = ;\nendmodule\n";
|
||||
let edit = ranged(text, at(2, 0, 2, 4)).expect("formats").expect("changed");
|
||||
assert_eq!(
|
||||
edit.new_text,
|
||||
"module m;\n always @* begin\n x = 1;\n end\n assign y = ;\nendmodule\n"
|
||||
);
|
||||
// Inside it, the request is refused with a message to read.
|
||||
let message = ranged(text, at(4, 0, 4, 4)).expect_err("must refuse");
|
||||
assert!(message.contains("syntax error"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unparsable_buffer_produces_no_range_edit_either() {
|
||||
// Range formatting cannot rescue broken input; the strict parse still
|
||||
@@ -802,7 +840,7 @@ mod tests {
|
||||
#[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.
|
||||
// same message: both are one `format_selection` 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)]);
|
||||
|
||||
@@ -61,9 +61,9 @@ pub fn on_type_formatting(
|
||||
/// Lay out the statement the `;` just ended, through the range engine.
|
||||
///
|
||||
/// The range asked for is the `;`'s **own line** and nothing else. That is not
|
||||
/// a narrower request than "the statement's lines": `format_range` selects by
|
||||
/// *unit*, so any line of a statement selects the whole statement (see
|
||||
/// `docs/features/range-formatting/README.md`). It is, however, a much safer
|
||||
/// a narrower request than "the statement's lines": `format_selection` selects
|
||||
/// by *unit*, so any line of a statement selects the whole statement (see
|
||||
/// `docs/features/selection-formatting/README.md`). It is, however, a much safer
|
||||
/// one — the `;` closing `module m (\n input a\n);` ends no statement at all,
|
||||
/// and naming its enclosing node's lines there would ask for the whole module
|
||||
/// back on a keystroke.
|
||||
@@ -1174,7 +1174,19 @@ mod tests {
|
||||
#[test]
|
||||
fn a_semicolon_in_a_buffer_the_engine_refuses_answers_nothing_at_all() {
|
||||
// Half-typed code is the normal case on this trigger, not a failure.
|
||||
assert_eq!(semicolon("module m;\n wire a;\n wire ;\nendmodule\n", 1), Vec::new());
|
||||
// The error is on the keystroke's own line: one elsewhere in the
|
||||
// buffer no longer refuses (selection-formatting, TODO §66.2).
|
||||
let text = "module m;\n wire a = ;\nendmodule\n";
|
||||
let at = Position { line: 1, character: 13 };
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
|
||||
assert_eq!(edits, Vec::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_semicolon_still_lays_out_its_statement_when_the_error_is_elsewhere() {
|
||||
let edits = semicolon("module m;\n wire a;\n wire ;\nendmodule\n", 1);
|
||||
assert_eq!(edits.len(), 1, "{edits:#?}");
|
||||
assert_eq!(edits[0].new_text, "module m;\n wire a;\n wire ;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1204,10 +1216,10 @@ mod tests {
|
||||
let at = Position { line: 1, character: 11 };
|
||||
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
|
||||
assert_eq!(edits.len(), 1, "{edits:#?}");
|
||||
// The engine's own canonicalization adds the missing final newline —
|
||||
// exactly what `textDocument/rangeFormatting` would also do here, and
|
||||
// not a moved byte this path invented on its own.
|
||||
assert_eq!(edits[0].new_text, "module m;\n wire a;\nendmodule\n");
|
||||
// Only the statement moves: the file's tail is outside the splice, so
|
||||
// the missing final newline stays missing — exactly what
|
||||
// `textDocument/rangeFormatting` answers here too.
|
||||
assert_eq!(edits[0].new_text, "module m;\n wire a;\nendmodule");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -135,6 +135,27 @@ fn a_ranges_request_lays_out_every_range_it_names_in_one_answer() {
|
||||
assert!(session.shown().is_empty(), "a clean config says nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_inside_a_nested_block_lays_out_only_that_block() {
|
||||
// The owner's report (TODO §66.2): a `case` selected inside an `always`
|
||||
// in a four-space file. Only the `case` moves, and it stays where it
|
||||
// starts; the statement after it and the parent keep their bytes.
|
||||
let tree = Tree::new("rangesnested");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let text = "module m;\n always @* begin\n case (s)\n 0: y=a;\n endcase\n z = 1;\n end\nendmodule\n";
|
||||
let uri = session.open(&tree.path.join("m.sv"), text);
|
||||
|
||||
let one = range_result(&mut session, &uri, json_range(2, 0, 5, 0));
|
||||
assert_eq!(
|
||||
one[0]["newText"],
|
||||
"module m;\n always @* begin\n case (s)\n 0: y = a;\n endcase\n z = 1;\n end\nendmodule\n",
|
||||
"{one:#?}"
|
||||
);
|
||||
// The multi-range method gives the same answer for the same selection.
|
||||
assert_eq!(ranges_result(&mut session, &uri, vec![json_range(2, 0, 5, 0)]), one);
|
||||
assert!(session.shown().is_empty());
|
||||
}
|
||||
|
||||
#[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
|
||||
@@ -250,9 +271,11 @@ fn a_keystroke_the_engine_refuses_is_answered_with_silence_and_not_a_popup() {
|
||||
// user cannot type past would arrive on every semicolon.
|
||||
let tree = Tree::new("ontypequiet");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\n wire ;\n");
|
||||
// The error sits on the keystroke's own line: since selection formatting
|
||||
// (TODO §66.2) an error on *another* line no longer refuses the request.
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a = ;\n");
|
||||
|
||||
assert_eq!(on_type(&mut session, &uri, ";", 1, 11), serde_json::json!([]));
|
||||
assert_eq!(on_type(&mut session, &uri, ";", 1, 13), serde_json::json!([]));
|
||||
assert!(session.shown().is_empty(), "not one word: {:?}", session.shown());
|
||||
// ...and the whole-document request on the same buffer still does say
|
||||
// something, so the silence is this path's decision and not a
|
||||
|
||||
@@ -278,6 +278,57 @@ fn range_formatting_is_advertised_and_formats_only_the_selection() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Tab-indented, with a parse error after the block: the shape of a buffer
|
||||
/// mid-edit that "Format Selection" (TODO §66.2) must still serve.
|
||||
const TABBED_BROKEN: &str = "module m;\n\talways @* begin\n\t\tif (a) x=1;\n\t\telse x=2;\n\tend\n\tassign y = ;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn range_formatting_lays_out_a_nested_selection_in_place_over_the_wire() {
|
||||
let dir = temp_dir("selectionfmt");
|
||||
let file = dir.join("m.sv");
|
||||
std::fs::write(&file, TABBED_BROKEN).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
let request = |id: u32, sl: u32, el: u32| {
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/rangeFormatting","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":{sl},"character":0}},"end":{{"line":{el},"character":0}}}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"#
|
||||
))
|
||||
};
|
||||
let session = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
|
||||
)),
|
||||
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(TABBED_BROKEN).expect("json")
|
||||
)),
|
||||
// The two statement lines inside the `always`.
|
||||
request(2, 2, 4),
|
||||
// The broken line itself: refused, no edit.
|
||||
request(3, 5, 6),
|
||||
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);
|
||||
assert_eq!(
|
||||
new_text(&messages, 2),
|
||||
"module m;\n\talways @* begin\n\t\tif (a) x = 1;\n\t\telse x = 2;\n\tend\n\tassign y = ;\nendmodule\n",
|
||||
"only the selected statement moves, tabs kept, error elsewhere ignored"
|
||||
);
|
||||
let refused = messages.iter().find(|m| m["id"] == 3).expect("response");
|
||||
assert!(
|
||||
refused.get("error").is_some()
|
||||
|| refused["result"].is_null()
|
||||
|| refused["result"] == serde_json::json!([]),
|
||||
"{refused}"
|
||||
);
|
||||
|
||||
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";
|
||||
|
||||
|
||||
+2
-1
@@ -151,7 +151,7 @@ what a change on the pointed-to side must not silently break.
|
||||
| `lucisv_server ◀──▶ vlog_semantic` | handshake | Three later additive performance surfaces: **`DeclLines` / `Def::lines`** record declaration and detail lines at index time (`FACTS_FORMAT` 3 → 4); **`WorkspaceIndex::absorb`** folds a scan batch with one merge rather than one merge per file; and **`WorkspaceIndex::files_spelling`** finds external uses by spelling, resolved or not, for rename's dangling-use refusal. The first feeds hover-line-index, the second scan-interleave, and the third refactor-rename's six-rung fan-out. Changing the facts codec, reference-fact census or merge semantics breaks those consumers. |
|
||||
| `lucisv_server ──▶ vlog_refactor` | depends | `prepare_rename`/`rename`, `find_references`, the port refactorings, `organize_imports`, `extract_module`, `inline_module`, `RefactorEdit::{edits,warnings,created}`, `rename_traced_with(files, known: &dyn KnownFacts, …)` (perf5r-scope-reuse, 2026-09-09: the engine may build its index from a caller's record for a file **only** when `known.facts_for(path, text)` answers for exactly these bytes — the server answers from the index cache's store entry, record and FNV-1a content hash read from one place, never from the workspace index's record; a reused file is parsed anyway if a later stage reads its `Semantics`; `rename_traced` is the door with nothing known), `rename_traced` + `RenameTrace`/`VerifyTrace`/`Stage` (perf5-p2: the rename with its stage timings and parse counts as an out parameter; `rename` is the same call with a trace nobody reads; the server logs one `timing: rename trace …` line under `--verbose` only), the parsed-input selectors `port_action_modules_in`/`imported_packages_in`/`extract_site_in`/`inline_site_in` (perf5-p1: the offer paths hand the document's own tolerant parse and diagnostics; the text forms are thin wrappers kept for standalone consumers and the every-offset parity test; a large-file buffer still takes the text form), `instantiation_plan`/`render_with`/`module_definition` (the inline instantiation ghost, signature help, inlay hints — the completion popup stopped consuming them 2026-08-30, names-only tier). Promise consumed: never a partial edit — `Ok` verified whole, `Err` is a sentence. |
|
||||
| `lucisv_server ◀──▶ vlog_refactor` | handshake | Request-scope selectors added for the performance wave: `prepare_rename_here` must produce the same answer/refusal text as whole-scope `prepare_rename`; `rename_name_at` must name the target that the rename engine acts on; `port_action_modules` and `enclosing_module` must name every module the corresponding port action/command can edit. The server uses those names to choose an index-derived file set; `extract_site`, `inline_site` and `imported_packages` also name source requirements. **`rename_preflight(semantics, offset, new_name)` (perf5r-preflight, 2026-09-08)** owes whole-scope `rename` the same *refusal* text one-directionally — it may always stand aside with `Ok(())` and never invents a refusal — and deliberately reads no workspace index (unlike `prepare_rename_here`): only refusals that are a pure function of the request buffer's own text (the new-name check, no symbol here, an unresolved or inherited-candidate reference, an unspelled declaration, the same name at a non-file-scope declaration); every index-answered refusal stays on the slow road. The engine remains the authority, and every selector must supply a superset of files needed for edits and refusals (inline gap: §2.9-33). |
|
||||
| `lucisv_server ──▶ vlog_formatter` | depends | `format_source`, `format_range`/`LineRanges` (range, ranges, on-type formatting), `Config`, `fence::protected_regions` (quick-fix filter). |
|
||||
| `lucisv_server ──▶ vlog_formatter` | depends | `format_source`, `format_selection`/`LineRanges` (range, ranges, on-type formatting — since TODO §66.2, 2026-11-09; `format_range` is now the CLI's `--lines` and the engine's own fallback for module/package-level selections), `Config`, `fence::protected_regions` (quick-fix filter). |
|
||||
| `lucisv_server ──▶ vlog_linter` | depends | `run`, `lint` + `LintContext::from_parse` (lints from the `Document`'s own parse — one-parse), `default_rules`, `apply_fixes`, `rule_by_name`. Same three promises the CLI relies on. |
|
||||
| `lucisv_mcp ──▶ lucisv_core, vlog_parser, vlog_semantic, vlog_refactor, vlog_formatter, vlog_linter` | depends | The MCP block (2026-09-23, `docs/mcp/PLAN.md`, `TODO-MCP.md`): `lucisv-mcp` composes the six libraries through their public APIs only — `Discovery`/`filelist`/`walk`/`content_hash`/`write_atomic` (core); `tokenize`, `parse_tolerant`, `parse_source` (strict, the structural edits' rule 1), `LineIndex`, `defines`, the AST (`Item`/`ItemKind`, `Meta::leading`, `Connections`), `PARSE_STACK_SIZE` (parser); `analyze`, `IndexBuilder::{add_file, add_facts}`, `WorkspaceIndex::{absorb, fingerprint, units, members_of, member_in, instantiations, workspace_symbols, find_define, files_mentioning, …}`, `resolve_external`, `FileFacts::{of, decode}`, `FACTS_FORMAT` (semantic); `rename`, `add_port`, `remove_port`, `find_references`, `instantiation_plan`, `module_definition`, `enclosing_module` (refactor); `format_source`/`fence` (formatter); `LintContext::from_parse`, `lint_with`, `select_rules`, `apply_fixes`, `rules_markdown`, `MentionOracle` (linter). **Never `lucisv_server`** (bin-only) and never `lsp-types`. Feature READMEs `docs/features/mcp-*`. **M7 (2026-09-23, the lean catalogue):** nine tools; `diff::unified`, `format_range` and the cursor refactorings (`expand_wildcard`, `convert_to_ansi`, `organize_imports`, `inline_module`, `propagate_ports`, `extract_module`) are no longer called — they stay in the CLI and the server. |
|
||||
| `lucisv_server ──▶ lsp-server / lsp-types` | depends | The transport (synchronous, no async runtime) and the protocol data model. Both pinned exactly. cancel-request additionally relies on `lsp-server 0.10.0`'s stdio transport being a **rendezvous channel** (its own forwarder queue exists because of it) — a version bump must re-read that crate's `stdio.rs`. |
|
||||
@@ -429,6 +429,7 @@ graph LR
|
||||
| `corpus-bugs ──▶ corpus-check` | depends | Fixes exactly the four root causes A–D the corpus check catalogued; measured back to 0 verification errors. |
|
||||
| `range-formatting ──▶ format-fences` | depends | A range is "an inverted fence": reuses `Doc::Verbatim`, `fence::collect`/`region_at`, and two helpers widened to `pub(crate)` (`line_start`, `with_trailing_comments`) — the only fence.rs change. |
|
||||
| `range-formatting ──▶ spans` | depends | The planner selects items by span/line. |
|
||||
| `selection-formatting ──▶ range-formatting / format-fences / lucisv-server` | depends | (2026-11-09, TODO §66.2) `format_selection` lays out the smallest run of sibling items/statements a line span covers at its written indentation and splices it in; defers to `format_range` for a module/package-level target; consumes `fence::collect`/`with_trailing_comments` and `Fmt::item_seq`/`stmt_seq`; adds `Printer::print_at` and `FormatError::Selection`. `verify.rs`, `range.rs`, `fence.rs` untouched. The server's range, ranges and on-type `;` requests all go through it. |
|
||||
| `alignment ──▶ spans` (+ name-spans) | depends | Anchor columns are derived from `name_span` byte offsets + the source text; deliberately **no** token-level representation of spacing. `doc.rs`/`printer.rs`/`verify.rs` untouched. |
|
||||
| `alignment ──▶ format-fences` | depends | `fence::region_at` (via `Fmt::is_fenced`) keeps fenced items out of alignment groups. |
|
||||
| `shared-fence-filter ◀──▶ linter-core / server-lint` | handshake | Closes server-lint Handshake 3: `fence::protected_regions` + `is_protected` become the **one** answer to "what may an automatic fix not touch"; CLI `--fix` and server quick fixes both call it; `vlog_linter` itself deliberately stays fence-blind. |
|
||||
|
||||
Reference in new issue
Block a user