From aa303ce9ae8c575bdc460b8b34d4095dc1386140 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Wed, 26 Aug 2026 11:06:51 -0700 Subject: [PATCH] =?UTF-8?q?LSP=20=C2=A79a:=20applyEdit=20compliance,=20pul?= =?UTF-8?q?l=20diagnostics,=20expand=20selection;=20v0.8.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The three top findings of the LSP 3.18 audit (TODO.md §9), one round of dev (Opus) + QA (Sonnet) + lead review: - executeCommand now pushes its WorkspaceEdit as workspace/applyEdit and reads the client's verdict; the old return-the-edit behavior stays as the documented fallback for clients without the capability. This fixes the three port commands doing nothing in stock clients — the returned edit was dropped by vscode-languageclient and Neovim alike. docs/features/apply-edit/README.md - textDocument/diagnostic + workspace/diagnostic (LSP 3.17), served from the same parse+lint pass the push model publishes, with resultId / unchanged caching on one generation counter; a pulling client is pushed nothing, a pushing client is unchanged. QA's exhaustive input trace found no stale-unchanged path. docs/features/pull-diagnostics/README.md - textDocument/selectionRange: chains from token spans, the tolerant parse's item/statement spans and the scope-pair matcher, filtered to strict nesting; the invariant swept over all 860 corpus files (6,880 positions, held everywhere). docs/features/selection-range/README.md 43 tests added across unit/e2e (server 557 -> 594+ unit, 29 -> 32 e2e); fmt/clippy/test/smoke all clean, re-verified independently by QA and by the lead. Co-Authored-By: Claude Fable 5 --- CHANGELOG.md | 43 ++ Cargo.lock | 16 +- Cargo.toml | 2 +- TODO.md | 19 +- crates/lucisv_server/src/main.rs | 111 +++- crates/lucisv_server/src/ports.rs | 7 +- crates/lucisv_server/src/selection.rs | 546 ++++++++++++++++ crates/lucisv_server/src/server.rs | 770 ++++++++++++++++++++++- crates/lucisv_server/tests/e2e.rs | 182 ++++++ docs/features/apply-edit/README.md | 215 +++++++ docs/features/lucisv-server/README.md | 4 +- docs/features/pull-diagnostics/README.md | 288 +++++++++ docs/features/selection-range/README.md | 227 +++++++ editors/vscode/package.json | 2 +- 14 files changed, 2378 insertions(+), 54 deletions(-) create mode 100644 crates/lucisv_server/src/selection.rs create mode 100644 docs/features/apply-edit/README.md create mode 100644 docs/features/pull-diagnostics/README.md create mode 100644 docs/features/selection-range/README.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 02e8b0a..b115cbd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,49 @@ All notable changes to lucisv are recorded here. Versions follow [semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes (see `README.md`) are the only frozen contract. +## 0.8.0 — 2026-08-26 + +The protocol-compliance release: the server was audited line-by-line +against the LSP 3.18 specification (the full gap list is TODO.md §9), +and the three findings that matter most shipped in one round. + +### Port commands now actually edit (workspace/applyEdit) + +`lucisv.addPort`, `lucisv.removePort` and `lucisv.propagatePorts` invoked +as *commands* did nothing in every stock client: the server returned the +`WorkspaceEdit` as the `executeCommand` result, which the protocol does +not define and which `vscode-languageclient` and Neovim both drop. (The +code-action lightbulb path was never affected — those edits ride inline.) +The server now pushes the edit as a `workspace/applyEdit` request with a +label for the undo stack, answers `null`, and reads the client's verdict: +a refusal becomes an error popup naming the command and the editor's own +reason. A client that never advertised `workspace.applyEdit` keeps the +old return-the-edit behavior — for that one it is the only thing that +could ever work. + +### Pull diagnostics (LSP 3.17) + +`textDocument/diagnostic` and `workspace/diagnostic` are served, from the +same parse+lint pass the push model publishes — one computation, two +deliveries, proven byte-identical in tests. Reports carry a `resultId` +and answer `unchanged` when nothing that feeds them has moved, so a +client re-pulling on focus changes costs nothing. A client that pulls is +pushed nothing at all — never both models for one client. Clients that +don't advertise the capability keep today's push behavior untouched. +Workspace reports cover the open buffers, which is the only scope this +server has ever diagnosed. + +### Expand selection (textDocument/selectionRange) + +One keystroke grows the selection from the identifier through the +statement, the enclosing `begin`/`end`, the process, the module, out to +the whole file. Chains are built from what the server already computes — +token spans, the tolerant parse's item/statement spans, and the +rainbow's own scope-pair matcher, which keeps expansion working in the +half-edited files where you actually reach for it. Every step strictly +contains the last; a sweep over all 860 corpus files (6,880 positions) +holds the invariant everywhere. + ## 0.7.2 — 2026-08-26 Honest columns, honest docs, and a CI that enforces the headline number. diff --git a/Cargo.lock b/Cargo.lock index 7e47ac1..8682997 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -97,7 +97,7 @@ dependencies = [ [[package]] name = "lucisv" -version = "0.7.2" +version = "0.8.0" dependencies = [ "lucisv_core", "rayon", @@ -108,11 +108,11 @@ dependencies = [ [[package]] name = "lucisv_core" -version = "0.7.2" +version = "0.8.0" [[package]] name = "lucisv_server" -version = "0.7.2" +version = "0.8.0" dependencies = [ "lsp-server", "lsp-types", @@ -248,14 +248,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] name = "vlog_formatter" -version = "0.7.2" +version = "0.8.0" dependencies = [ "vlog_parser", ] [[package]] name = "vlog_linter" -version = "0.7.2" +version = "0.8.0" dependencies = [ "vlog_formatter", "vlog_parser", @@ -264,11 +264,11 @@ dependencies = [ [[package]] name = "vlog_parser" -version = "0.7.2" +version = "0.8.0" [[package]] name = "vlog_refactor" -version = "0.7.2" +version = "0.8.0" dependencies = [ "vlog_parser", "vlog_semantic", @@ -276,7 +276,7 @@ dependencies = [ [[package]] name = "vlog_semantic" -version = "0.7.2" +version = "0.8.0" dependencies = [ "vlog_parser", ] diff --git a/Cargo.toml b/Cargo.toml index 0efa51d..d8bef5f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ members = [ ] [workspace.package] -version = "0.7.2" +version = "0.8.0" authors = ["Guoliang Chen"] edition = "2021" license = "MIT" diff --git a/TODO.md b/TODO.md index 11084ac..26b212e 100644 --- a/TODO.md +++ b/TODO.md @@ -644,7 +644,7 @@ and are not gaps. ### 9a. Compliance and high-value (round 1) -- [ ] **`executeCommand` must deliver its edit via `workspace/applyEdit`.** +- [x] **`executeCommand` must deliver its edit via `workspace/applyEdit`.** Today `ports::execute`'s `WorkspaceEdit` is returned as the request's *result* (`server.rs`, `ports.rs:79`), which the spec does not define and standard clients drop on the floor — `vscode-languageclient` does @@ -657,7 +657,11 @@ and are not gaps. response we can no longer ignore wholesale). Gate on the client's `workspace.applyEdit` capability with the old return-the-edit behavior as the documented fallback. -- [ ] **Pull diagnostics (3.17): `textDocument/diagnostic` + + → `docs/features/apply-edit/README.md`; the edit is pushed with a + `lucisv: ` label, the result is `null`, and a refusal is shown + as an ERROR naming the command. Watcher-registration answers stay + ignored; `editors/vscode/extension.js` needed no change. +- [x] **Pull diagnostics (3.17): `textDocument/diagnostic` + `workspace/diagnostic`.** The modern model — client controls timing, prioritizes visible editors, caches via `resultId`/`unchanged`. Advertise `DiagnosticOptions` (`inter_file_dependencies: true` — a @@ -667,10 +671,19 @@ and are not gaps. generation both stand. Keep push for clients that don't send `text_document.diagnostic` capability; never run both models for the same client (double diagnostics). -- [ ] **`textDocument/selectionRange`** — expand-selection. Cheap for + → `docs/features/pull-diagnostics/README.md`; one generation counter is + the whole `resultId` (bumped by `set_document` and `reindex`), the + push gate sits in `send_diagnostics` so the `didClose` clear is + suppressed too, and `workspace/diagnostic` reports the open buffers — + the honest limit, stated there. +- [x] **`textDocument/selectionRange`** — expand-selection. Cheap for us: the scope-pair matcher (`pairs.rs`) and AST spans already give the nesting chain; walk offset → enclosing token → statement → item → scope → file, one linked chain per input position. + → `docs/features/selection-range/README.md` + (`crates/lucisv_server/src/selection.rs`); token, AST, scope-pair and + file ranges are collected and filtered down to what strictly nests. No + expression step — deliberate, and recorded there. ### 9b. High-value, next rounds diff --git a/crates/lucisv_server/src/main.rs b/crates/lucisv_server/src/main.rs index 6e0e6d9..419e856 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -26,6 +26,7 @@ mod nav; mod pairs; mod ports; mod rename; +mod selection; mod server; mod settings; mod signature; @@ -42,11 +43,13 @@ use std::path::PathBuf; use lsp_server::Connection; use lsp_types::{ CallHierarchyServerCapability, CodeActionKind, CodeActionOptions, CodeActionProviderCapability, - CompletionOptions, DocumentLinkOptions, ExecuteCommandOptions, FoldingRangeProviderCapability, - InitializeParams, InlayHintOptions, InlayHintServerCapabilities, OneOf, PositionEncodingKind, - RenameOptions, SemanticTokensFullOptions, SemanticTokensLegend, SemanticTokensOptions, - SemanticTokensServerCapabilities, ServerCapabilities, SignatureHelpOptions, - TextDocumentSyncCapability, TextDocumentSyncKind, WorkDoneProgressOptions, + CompletionOptions, DiagnosticOptions, DiagnosticServerCapabilities, DocumentLinkOptions, + ExecuteCommandOptions, FoldingRangeProviderCapability, InitializeParams, InlayHintOptions, + InlayHintServerCapabilities, OneOf, PositionEncodingKind, RenameOptions, + SelectionRangeProviderCapability, SemanticTokensFullOptions, SemanticTokensLegend, + SemanticTokensOptions, SemanticTokensServerCapabilities, ServerCapabilities, + SignatureHelpOptions, TextDocumentSyncCapability, TextDocumentSyncKind, + WorkDoneProgressOptions, }; use crate::server::{ClientAbilities, Server}; @@ -63,6 +66,8 @@ fn main() -> Result<(), Box> { let abilities = ClientAbilities { snippets: snippet_support(¶ms), file_watching: watch::dynamic_registration(¶ms), + apply_edit: apply_edit_support(¶ms), + pull_diagnostics: pull_diagnostics_support(¶ms), }; connection.initialize_finish(id, serde_json::to_value(initialize_result())?)?; @@ -172,6 +177,21 @@ fn capabilities() -> ServerCapabilities { // sends the request after opting into `ProposedFeatures`, so an // extension older than this server simply never asks. inline_completion_provider: Some(OneOf::Left(true)), + // Expand-selection. Nothing to configure: the chain is computed from + // the buffer alone, and every position is answered. + selection_range_provider: Some(SelectionRangeProviderCapability::Simple(true)), + // Pull diagnostics (3.17), served from the same parse+lint pass the + // push model publishes. `inter_file_dependencies` because a save + // rebuilds the workspace index and *that* changes what other files + // report; `workspace_diagnostics` because `workspace/diagnostic` is + // answered — over the open buffers, which is the only scope this + // server has ever diagnosed. + diagnostic_provider: Some(DiagnosticServerCapabilities::Options(DiagnosticOptions { + identifier: Some(diagnostics::SOURCE.to_string()), + inter_file_dependencies: true, + workspace_diagnostics: true, + work_done_progress_options: WorkDoneProgressOptions::default(), + })), semantic_tokens_provider: Some(SemanticTokensServerCapabilities::SemanticTokensOptions( SemanticTokensOptions { work_done_progress_options: WorkDoneProgressOptions::default(), @@ -216,6 +236,33 @@ fn snippet_support(params: &InitializeParams) -> bool { .unwrap_or(false) } +/// Whether the client applies a `workspace/applyEdit` request. +/// +/// A client that did not say so gets a command's edit back as the request +/// result — which is what every client got before this was read, and is the +/// only thing left to try for one that cannot be pushed an edit. +fn apply_edit_support(params: &InitializeParams) -> bool { + params + .capabilities + .workspace + .as_ref() + .and_then(|workspace| workspace.apply_edit) + .unwrap_or(false) +} + +/// Whether the client pulls diagnostics (LSP 3.17). +/// +/// Sending the capability at all is what says so; its two fields are about +/// dynamic registration and related documents, neither of which this server +/// uses. A client that says nothing keeps the push model unchanged. +fn pull_diagnostics_support(params: &InitializeParams) -> bool { + params + .capabilities + .text_document + .as_ref() + .is_some_and(|text_document| text_document.diagnostic.is_some()) +} + /// The directories to index: the client's workspace folders, or the /// deprecated single root when that is all it sent. fn workspace_roots(params: &InitializeParams) -> Vec { @@ -255,6 +302,60 @@ mod tests { assert!(caps.inlay_hint_provider.is_some()); assert!(caps.call_hierarchy_provider.is_some()); assert!(caps.inline_completion_provider.is_some()); + assert!(caps.selection_range_provider.is_some()); + assert!(caps.diagnostic_provider.is_some()); + } + + #[test] + fn the_diagnostic_options_say_what_this_server_actually_does() { + let Some(DiagnosticServerCapabilities::Options(options)) = + capabilities().diagnostic_provider + else { + panic!("plain options, not a dynamic registration"); + }; + assert_eq!(options.identifier.as_deref(), Some(diagnostics::SOURCE), "same tag as a push"); + assert!(options.inter_file_dependencies, "a save changes other files' diagnostics"); + assert!(options.workspace_diagnostics, "`workspace/diagnostic` is answered"); + } + + #[test] + fn apply_edit_support_is_read_from_the_clients_own_capabilities() { + use lsp_types::{ClientCapabilities, WorkspaceClientCapabilities}; + assert!(!apply_edit_support(&InitializeParams::default()), "silence means no"); + + let saying = |apply_edit: Option| InitializeParams { + capabilities: ClientCapabilities { + workspace: Some(WorkspaceClientCapabilities { apply_edit, ..Default::default() }), + ..Default::default() + }, + ..Default::default() + }; + assert!(apply_edit_support(&saying(Some(true)))); + assert!(!apply_edit_support(&saying(Some(false)))); + assert!(!apply_edit_support(&saying(None))); + } + + #[test] + fn a_client_that_sent_the_diagnostic_capability_at_all_is_a_pulling_client() { + use lsp_types::{ + ClientCapabilities, DiagnosticClientCapabilities, TextDocumentClientCapabilities, + }; + assert!(!pull_diagnostics_support(&InitializeParams::default()), "silence means push"); + + let pulling = InitializeParams { + capabilities: ClientCapabilities { + text_document: Some(TextDocumentClientCapabilities { + // Both fields left unset: sending the capability is the + // whole of the statement, and neither field is about + // whether the client pulls. + diagnostic: Some(DiagnosticClientCapabilities::default()), + ..Default::default() + }), + ..Default::default() + }, + ..Default::default() + }; + assert!(pull_diagnostics_support(&pulling)); } #[test] diff --git a/crates/lucisv_server/src/ports.rs b/crates/lucisv_server/src/ports.rs index 4699f64..9711701 100644 --- a/crates/lucisv_server/src/ports.rs +++ b/crates/lucisv_server/src/ports.rs @@ -75,9 +75,10 @@ pub fn code_actions(ws: &Workspace, uri: &Uri, offset: u32) -> Vec Vec { + let converter = doc.positions(); + positions.iter().map(|position| chain(doc, converter.offset(*position))).collect() +} + +/// The chain for one byte offset. +fn chain(doc: &Document, offset: u32) -> SelectionRange { + let positions = doc.positions(); + let mut range: Option = None; + // Widest first, so each step is built already holding its parent. + for span in nested(enclosing(doc, offset)).into_iter().rev() { + range = Some(SelectionRange { range: positions.range(span), parent: range.map(Box::new) }); + } + range.unwrap_or_else(|| SelectionRange { range: positions.whole_document(), parent: None }) +} + +/// Every byte range this server can name that covers `offset`, from every +/// source, unordered and possibly overlapping — [`nested`] sorts it out. +fn enclosing(doc: &Document, offset: u32) -> Vec { + let mut spans = Vec::new(); + if let Some(token) = doc.tokens.iter().find(|token| covers(token.span, offset)) { + spans.push(token.span); + } + items(&doc.tree.items, offset, &mut spans); + // The scopes the AST does not model — an unclosed `begin` inside an + // otherwise fine module, a `case` in a file that only half parsed — still + // match over the token stream, and a user expanding a selection there is + // exactly the user whose file is mid-edit. + for pair in analyze(&doc.tokens).pairs { + let span = TextRange::new(pair.open.start, pair.close.end); + if covers(span, offset) { + spans.push(span); + } + } + spans.push(TextRange::new(0, doc.text.len() as u32)); + spans +} + +/// The subsequence that really nests, smallest first. +/// +/// Two ranges that both cover the cursor need not contain one another — an +/// item span and a scope pair can overlap when a parse went wrong — and LSP +/// requires every step to contain its child. So the list is walked smallest +/// first and a range is kept only when it strictly contains what was kept +/// before it; that also drops the duplicates the four sources produce for the +/// same construct. +fn nested(mut spans: Vec) -> Vec { + // A zero-width step selects nothing, which is not a step a user can see. + spans.retain(|span| !span.is_empty()); + spans.sort_by_key(|span| (span.len(), span.start)); + let mut out: Vec = Vec::new(); + for span in spans { + let keep = match out.last() { + Some(inner) => { + span.start <= inner.start && span.end >= inner.end && span.len() > inner.len() + } + None => true, + }; + if keep { + out.push(span); + } + } + out +} + +/// Whether a span covers an offset. The end is **included**: a cursor sitting +/// just after a word is still on that word, which is where an expand-selection +/// keystroke is most often pressed. +fn covers(span: TextRange, offset: u32) -> bool { + span.start <= offset && offset <= span.end +} + +/// The spans of every item that covers `offset`, descending only into the one +/// that does — the walk is per-keystroke, and a whole-file walk would visit +/// thousands of nodes to report a handful. +fn items(list: &[Item], offset: u32, out: &mut Vec) { + for item in list { + if !covers(item.span, offset) { + continue; + } + out.push(item.span); + match &item.kind { + ItemKind::Module(module) => items(&module.items, offset, out), + ItemKind::Class(class) => items(&class.items, offset, out), + ItemKind::Package { items: inner, .. } => items(inner, offset, out), + ItemKind::GenerateRegion { items: inner, .. } => items(inner, offset, out), + ItemKind::GenIf(gen_if) => gen_if_blocks(gen_if, offset, out), + ItemKind::GenFor(gen_for) => gen_block(&gen_for.body, offset, out), + ItemKind::GenCase(gen_case) => { + for case_item in &gen_case.items { + if covers(case_item.span, offset) { + out.push(case_item.span); + gen_block(&case_item.body, offset, out); + } + } + } + ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => { + statement(stmt, offset, out) + } + ItemKind::Function(decl) => statements(&decl.stmts, offset, out), + ItemKind::Task(decl) => statements(&decl.stmts, offset, out), + _ => {} + } + } +} + +/// A generate `if`, its `else if` ladder and its final `else`. +fn gen_if_blocks(gen_if: &GenIf, offset: u32, out: &mut Vec) { + gen_block(&gen_if.then, offset, out); + let mut els = gen_if.els.as_deref(); + while let Some(branch) = els { + match branch { + GenElse::If(_, nested) => { + gen_block(&nested.then, offset, out); + els = nested.els.as_deref(); + } + GenElse::Block(block) => { + gen_block(block, offset, out); + els = None; + } + } + } +} + +fn gen_block(block: &GenBlock, offset: u32, out: &mut Vec) { + if !covers(block.span, offset) { + return; + } + out.push(block.span); + items(&block.items, offset, out); +} + +fn statements(list: &[Stmt], offset: u32, out: &mut Vec) { + for stmt in list { + statement(stmt, offset, out); + } +} + +/// The spans of `stmt` and of every statement inside it that covers `offset`. +/// +/// The recursion is bounded by the parser's own nesting limit +/// (`docs/features/recursion-limit/README.md`): a tree this walks is a tree it +/// built. +fn statement(stmt: &Stmt, offset: u32, out: &mut Vec) { + if !covers(stmt.span, offset) { + return; + } + out.push(stmt.span); + match &stmt.kind { + StmtKind::Block { stmts, .. } | StmtKind::ForkJoin { stmts, .. } => { + statements(stmts, offset, out) + } + StmtKind::If { then, els, .. } => { + statement(then, offset, out); + if let Some(els) = els { + statement(els, offset, out); + } + } + StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => { + for case_item in items { + if covers(case_item.span, offset) { + out.push(case_item.span); + statement(&case_item.stmt, offset, out); + } + } + } + StmtKind::Labeled { stmt: inner, .. } => statement(inner, offset, out), + StmtKind::For { body, .. } + | StmtKind::While { body, .. } + | StmtKind::DoWhile { body, .. } + | StmtKind::Repeat { body, .. } + | StmtKind::Forever { body } + | StmtKind::Foreach { body, .. } => statement(body, offset, out), + StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => { + statement(inner, offset, out) + } + StmtKind::Assert { then, els, .. } => { + if let Some(then) = then { + statement(then, offset, out); + } + if let Some(els) = els { + statement(els, offset, out); + } + } + _ => {} + } +} + +#[cfg(test)] +mod tests { + use super::*; + use lsp_types::Range; + use vlog_semantic::WorkspaceIndex; + + fn doc_of(text: &str) -> Document { + Document::new(None, text.to_string(), &WorkspaceIndex::default()) + } + + /// The chain for the first occurrence of `needle`, as the source text of + /// each step, innermost first. + fn steps(text: &str, needle: &str) -> Vec { + let doc = doc_of(text); + let offset = text.find(needle).expect("the needle is in the text") as u32; + let position = doc.positions().position(offset); + let chains = selection_ranges(&doc, &[position]); + assert_eq!(chains.len(), 1, "one chain per position"); + let mut out = Vec::new(); + let mut step = Some(&chains[0]); + let positions = doc.positions(); + while let Some(current) = step { + let start = positions.offset(current.range.start) as usize; + let end = positions.offset(current.range.end) as usize; + out.push(text[start..end].to_string()); + step = current.parent.as_deref(); + } + out + } + + /// Every step of a chain, as `(start, end)` byte offsets. + fn spans(doc: &Document, offset: u32) -> Vec<(u32, u32)> { + let position = doc.positions().position(offset); + let chains = selection_ranges(doc, &[position]); + let positions = doc.positions(); + let mut out = Vec::new(); + let mut step = chains.first(); + while let Some(current) = step { + out.push((positions.offset(current.range.start), positions.offset(current.range.end))); + step = current.parent.as_deref(); + } + out + } + + #[test] + fn the_chain_runs_from_the_token_out_to_the_whole_file() { + let text = "module m;\n wire a;\nendmodule\n"; + let steps = steps(text, "wire"); + assert_eq!(steps.first().map(String::as_str), Some("wire"), "{steps:?}"); + assert_eq!(steps.last().map(String::as_str), Some(text), "the whole file closes it"); + assert!(steps.contains(&"wire a;".to_string()), "{steps:?}"); + } + + #[test] + fn a_statement_expands_through_its_block_and_its_process() { + let text = concat!( + "module m;\n", + " initial begin\n", + " if (a) begin\n", + " x = 1;\n", + " end\n", + " end\n", + "endmodule\n", + ); + let steps = steps(text, "x = 1"); + assert_eq!(steps.first().map(String::as_str), Some("x")); + assert!(steps.iter().any(|s| s == "x = 1;"), "the statement: {steps:?}"); + assert!(steps.iter().any(|s| s.starts_with("if (a) begin")), "the if: {steps:?}"); + assert!(steps.iter().any(|s| s.starts_with("initial begin")), "the process: {steps:?}"); + assert!(steps.iter().any(|s| s.starts_with("module m;")), "the module: {steps:?}"); + assert_eq!(steps.last().map(String::as_str), Some(text)); + } + + #[test] + fn every_step_strictly_contains_the_one_before_it() { + // The protocol's own requirement, and the thing the four sources of + // ranges could most easily break. + let text = concat!( + "module m;\n", + " always_comb begin\n", + " case (sel)\n", + " 2'd0: y = a;\n", + " default: y = b;\n", + " endcase\n", + " end\n", + "endmodule\n", + ); + let doc = doc_of(text); + for offset in 0..=text.len() as u32 { + let spans = spans(&doc, offset); + assert!(!spans.is_empty(), "every position gets a chain, at {offset}"); + for pair in spans.windows(2) { + let (inner, outer) = (pair[0], pair[1]); + assert!( + outer.0 <= inner.0 && outer.1 >= inner.1 && outer != inner, + "at {offset}: {outer:?} must strictly contain {inner:?} — {spans:?}" + ); + } + assert_eq!( + spans.last(), + Some(&(0, text.len() as u32)), + "the file closes every chain, at {offset}" + ); + } + } + + #[test] + fn a_case_item_is_a_step_of_its_own() { + let text = concat!( + "module m;\n", + " always_comb begin\n", + " case (sel)\n", + " 2'd0: y = a;\n", + " endcase\n", + " end\n", + "endmodule\n", + ); + let steps = steps(text, "y = a"); + assert!(steps.iter().any(|s| s == "2'd0: y = a;"), "{steps:?}"); + assert!(steps.iter().any(|s| s.starts_with("case (sel)")), "{steps:?}"); + } + + #[test] + fn a_generate_block_is_a_step_of_its_own() { + let text = concat!( + "module m;\n", + " generate\n", + " if (A) begin : g\n", + " wire a;\n", + " end\n", + " endgenerate\n", + "endmodule\n", + ); + let steps = steps(text, "wire a"); + assert!(steps.iter().any(|s| s == "wire a;"), "{steps:?}"); + assert!(steps.iter().any(|s| s.starts_with("begin : g")), "the block: {steps:?}"); + assert!(steps.iter().any(|s| s.starts_with("generate")), "the region: {steps:?}"); + } + + #[test] + fn several_positions_are_answered_position_for_position() { + let text = "module m;\n wire a;\nendmodule\n"; + let doc = doc_of(text); + let positions = doc.positions(); + let at = |needle: &str| positions.position(text.find(needle).expect("needle") as u32); + let asked = vec![at("endmodule"), at("wire"), at("module")]; + let chains = selection_ranges(&doc, &asked); + assert_eq!(chains.len(), 3); + for (chain, position) in chains.iter().zip(&asked) { + assert!( + chain.range.start <= *position && *position <= chain.range.end, + "each answer is about its own position: {chain:?} vs {position:?}" + ); + } + } + + #[test] + fn no_positions_asked_means_no_chains_answered() { + let doc = doc_of("module m;\nendmodule\n"); + assert!(selection_ranges(&doc, &[]).is_empty()); + } + + #[test] + fn an_empty_file_still_answers_one_degenerate_chain() { + let doc = doc_of(""); + let chains = selection_ranges(&doc, &[Position { line: 0, character: 0 }]); + assert_eq!(chains.len(), 1); + assert_eq!(chains[0].range.start, chains[0].range.end, "there is nothing to select"); + assert!(chains[0].parent.is_none(), "and nothing to expand to"); + } + + #[test] + fn a_file_that_does_not_lex_still_answers_the_file_range() { + // `Document::new` leaves `tokens` empty and the tree an error leaf, so + // this is the path where every source but the last one gives nothing. + let text = "module m;\n wire a; /* unterminated\n"; + let doc = doc_of(text); + assert!(doc.tokens.is_empty(), "the premise"); + let spans = spans(&doc, 12); + assert_eq!(spans.last(), Some(&(0, text.len() as u32))); + } + + #[test] + fn an_unclosed_scope_still_expands_through_what_did_close() { + // The mid-edit shape: the `begin` never closes, so the AST cannot + // offer the statement — the module's own pair still can. + let text = "module m;\n initial begin\n x = 1;\nendmodule\n"; + let doc = doc_of(text); + let offset = text.find("x = 1").expect("needle") as u32; + let spans = spans(&doc, offset); + assert!(spans.len() >= 2, "at least the token and the file: {spans:?}"); + assert_eq!(spans.last(), Some(&(0, text.len() as u32))); + } + + #[test] + fn a_position_past_the_end_of_the_file_clamps_into_it() { + let text = "module m;\nendmodule\n"; + let doc = doc_of(text); + let chains = selection_ranges(&doc, &[Position { line: 99, character: 99 }]); + assert_eq!(chains.len(), 1); + assert_eq!(chains[0].range.end, doc.positions().whole_document().end); + } + + #[test] + fn a_multibyte_line_keeps_the_columns_in_utf16() { + // The chain is computed in bytes and answered in UTF-16 units; an + // off-by-one here would select the wrong text in the editor only. + let text = "module m;\n // é 🎉\n wire a;\nendmodule\n"; + let steps = steps(text, "wire"); + assert_eq!(steps.first().map(String::as_str), Some("wire"), "{steps:?}"); + assert!(steps.iter().any(|s| s == "wire a;"), "{steps:?}"); + } + + #[test] + fn nesting_drops_a_range_that_does_not_contain_what_came_before() { + // The guard for the overlapping-sources case: two ranges that both + // cover the cursor but nest in neither direction. The wider-but-not- + // enclosing one must be dropped, never emitted as a parent. + let spans = vec![ + TextRange::new(4, 6), + TextRange::new(0, 8), + TextRange::new(5, 20), // covers 5, contains neither of the above + TextRange::new(0, 30), + ]; + let kept = nested(spans); + assert_eq!( + kept.iter().map(|s| (s.start, s.end)).collect::>(), + vec![(4, 6), (0, 8), (0, 30)] + ); + } + + /// The strict-nesting invariant, on the real corpus rather than + /// hand-written snippets. `every_step_strictly_contains_the_one_before_it` + /// above proves the invariant on files this crate's author wrote to + /// exercise it; a corpus file was written by nobody thinking about this + /// walk at all, and is exactly what turns up a construct the four + /// sources disagree about. Skipped when `corpus/` is not checked out, + /// like every other corpus test in this crate. + #[test] + fn every_step_strictly_nests_over_the_real_corpus() { + let corpus = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + if !corpus.is_dir() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + let extensions = ["sv", "v", "svh", "vh"]; + let mut files_checked = 0; + let mut positions_checked = 0; + for entry in walk(&corpus) { + let Some(ext) = entry.extension().and_then(|e| e.to_str()) else { continue }; + if !extensions.contains(&ext) { + continue; + } + let Ok(text) = std::fs::read_to_string(&entry) else { continue }; + if text.is_empty() { + continue; + } + files_checked += 1; + let doc = Document::new(Some(entry.clone()), text.clone(), &WorkspaceIndex::default()); + let converter = doc.positions(); + // A handful of evenly spaced offsets per file, not every byte: + // the corpus is 800+ files, and the per-offset invariant is + // already proven exhaustively on small files above. This is + // about *coverage of real syntax*, not exhaustiveness per file. + let len = text.len() as u32; + let stride = (len / 7).max(1); + let mut offset = 0; + while offset <= len { + positions_checked += 1; + let position = converter.position(offset); + let chains = selection_ranges(&doc, &[position]); + assert_eq!(chains.len(), 1, "{}: offset {offset}", entry.display()); + let mut step = Some(&chains[0]); + let mut previous: Option = None; + while let Some(current) = step { + if let Some(inner) = previous { + let widens = current.range.start <= inner.start + && current.range.end >= inner.end + && current.range != inner; + assert!( + widens, + "{}: offset {offset}: {:?} does not strictly contain {:?}", + entry.display(), + current.range, + inner + ); + } + previous = Some(current.range); + step = current.parent.as_deref(); + } + let whole = converter.whole_document(); + assert_eq!( + previous, + Some(whole), + "{}: offset {offset}: the file must close every chain", + entry.display() + ); + offset += stride; + } + } + assert!(files_checked > 100, "the corpus really is checked out: {files_checked} files"); + eprintln!("selection ranges: {files_checked} files, {positions_checked} positions, no panics, every step strictly nested"); + } + + /// Every regular file under `dir`, recursively — no filtering by anything + /// but extension, which the caller does. Errors reading a directory are + /// treated as "nothing here" rather than failing the whole sweep: a + /// symlink loop or a permission-denied subtree in a third-party corpus + /// checkout should not take the QA test down with it. + fn walk(dir: &std::path::Path) -> Vec { + let mut out = Vec::new(); + let Ok(entries) = std::fs::read_dir(dir) else { return out }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + out.extend(walk(&path)); + } else { + out.push(path); + } + } + out + } + + #[test] + fn nesting_drops_duplicates_and_empty_ranges() { + let spans = vec![ + TextRange::new(3, 3), + TextRange::new(2, 9), + TextRange::new(2, 9), + TextRange::new(0, 9), + ]; + let kept = nested(spans); + assert_eq!(kept.iter().map(|s| (s.start, s.end)).collect::>(), vec![(2, 9), (0, 9)]); + } +} diff --git a/crates/lucisv_server/src/server.rs b/crates/lucisv_server/src/server.rs index 20197fa..af0ab73 100644 --- a/crates/lucisv_server/src/server.rs +++ b/crates/lucisv_server/src/server.rs @@ -5,7 +5,7 @@ //! — Verilog files are small, every handler is milliseconds, and a worker pool //! would buy nothing yet. See `docs/features/lucisv-server/README.md`. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::error::Error; use lsp_server::{Connection, ExtractError, Message, Notification, Request, RequestId, Response}; @@ -15,25 +15,33 @@ use lsp_types::notification::{ ShowMessage, }; use lsp_types::request::{ - CallHierarchyIncomingCalls, CallHierarchyOutgoingCalls, CallHierarchyPrepare, - CodeActionRequest, Completion, DocumentHighlightRequest, DocumentLinkRequest, - DocumentSymbolRequest, ExecuteCommand, FoldingRangeRequest, Formatting, GotoDefinition, - HoverRequest, InlayHintRequest, InlineCompletionRequest, PrepareRenameRequest, RangeFormatting, - References, RegisterCapability, Rename, Request as _, SemanticTokensFullRequest, - SignatureHelpRequest, UnregisterCapability, WorkspaceSymbolRequest, + ApplyWorkspaceEdit, CallHierarchyIncomingCalls, CallHierarchyOutgoingCalls, + CallHierarchyPrepare, CodeActionRequest, Completion, DocumentDiagnosticRequest, + DocumentHighlightRequest, DocumentLinkRequest, DocumentSymbolRequest, ExecuteCommand, + FoldingRangeRequest, Formatting, GotoDefinition, HoverRequest, InlayHintRequest, + InlineCompletionRequest, PrepareRenameRequest, RangeFormatting, References, RegisterCapability, + Rename, Request as _, SelectionRangeRequest, SemanticTokensFullRequest, SignatureHelpRequest, + UnregisterCapability, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest, }; use lsp_types::{ - CallHierarchyIncomingCallsParams, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams, - CodeActionKind, CodeActionParams, CompletionParams, DidChangeConfigurationParams, - DidChangeTextDocumentParams, DidChangeWatchedFilesParams, DidCloseTextDocumentParams, - DidOpenTextDocumentParams, DidSaveTextDocumentParams, DocumentFormattingParams, - DocumentHighlightParams, DocumentLinkParams, DocumentRangeFormattingParams, - DocumentSymbolParams, DocumentSymbolResponse, ExecuteCommandParams, FoldingRangeParams, + ApplyWorkspaceEditParams, ApplyWorkspaceEditResponse, CallHierarchyIncomingCallsParams, + CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams, CodeActionKind, CodeActionParams, + CompletionParams, DidChangeConfigurationParams, DidChangeTextDocumentParams, + DidChangeWatchedFilesParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams, + DidSaveTextDocumentParams, DocumentDiagnosticParams, DocumentDiagnosticReport, + DocumentDiagnosticReportResult, DocumentFormattingParams, DocumentHighlightParams, + DocumentLinkParams, DocumentRangeFormattingParams, DocumentSymbolParams, + DocumentSymbolResponse, ExecuteCommandParams, FoldingRangeParams, FullDocumentDiagnosticReport, GotoDefinitionParams, GotoDefinitionResponse, HoverParams, InlayHintParams, - InlineCompletionParams, LogMessageParams, MessageType, Position, PublishDiagnosticsParams, - ReferenceParams, RegistrationParams, RenameParams, SemanticTokensParams, SemanticTokensResult, - ShowMessageParams, SignatureHelpParams, TextDocumentPositionParams, UnregistrationParams, Uri, - WorkspaceSymbolParams, WorkspaceSymbolResponse, + InlineCompletionParams, LogMessageParams, MessageType, Position, PreviousResultId, + PublishDiagnosticsParams, ReferenceParams, RegistrationParams, + RelatedFullDocumentDiagnosticReport, RelatedUnchangedDocumentDiagnosticReport, RenameParams, + SelectionRangeParams, SemanticTokensParams, SemanticTokensResult, ShowMessageParams, + SignatureHelpParams, TextDocumentPositionParams, UnchangedDocumentDiagnosticReport, + UnregistrationParams, Uri, WorkspaceDiagnosticParams, WorkspaceDiagnosticReport, + WorkspaceDiagnosticReportResult, WorkspaceDocumentDiagnosticReport, WorkspaceEdit, + WorkspaceFullDocumentDiagnosticReport, WorkspaceSymbolParams, WorkspaceSymbolResponse, + WorkspaceUnchangedDocumentDiagnosticReport, }; use serde::de::DeserializeOwned; use serde_json::Value; @@ -41,11 +49,12 @@ use serde_json::Value; use crate::state::Workspace; use crate::{ code_action, completion, diagnostics, folding, format, hierarchy, hover, includes, inlay, - inline, nav, pairs, ports, rename, settings, signature, symbols, tokens, watch, + inline, nav, pairs, ports, rename, selection, settings, signature, symbols, tokens, watch, }; /// What the client said it can do, read once at `initialize` because that is /// the only time those capabilities are sent. +#[derive(Default)] pub struct ClientAbilities { /// Whether the client can expand a completion item's tabstops. pub snippets: bool, @@ -53,6 +62,13 @@ pub struct ClientAbilities { /// registration. There is no static form of that capability, so a client /// that says nothing keeps the save-only staleness model. pub file_watching: bool, + /// Whether the client applies a `workspace/applyEdit` request. A client + /// that cannot gets a command's edit back as the request result instead, + /// which is what every client got before this was read. + pub apply_edit: bool, + /// Whether the client *pulls* diagnostics (LSP 3.17). One client is never + /// served both models: a pulling client is pushed nothing at all. + pub pull_diagnostics: bool, } /// Everything the server owns. @@ -74,6 +90,15 @@ pub struct Server { /// Numbers the requests made *of* the client. A repeated id is a protocol /// error, so this only ever counts up. request_ids: u32, + /// The `workspace/applyEdit` requests still waiting for an answer, by the + /// id they were sent with, each remembering the command that asked for it + /// so a refusal can be named. Nothing else the server asks of the client + /// is recorded here, which is exactly what makes its answer ignorable. + applying: HashMap, + /// Counts everything that can change what a pull request would answer: a + /// buffer's text, and the workspace index. It is the whole of a + /// diagnostic `resultId`; see `docs/features/pull-diagnostics/README.md`. + generation: u64, } impl Server { @@ -92,6 +117,8 @@ impl Server { watchers: None, registrations: 0, request_ids: 0, + applying: HashMap::new(), + generation: 0, }; server.report_scope(warnings); // The earliest legal moment: `main` builds this only after @@ -114,11 +141,7 @@ impl Server { self.connection.sender.send(Message::Response(response))?; } Message::Notification(notification) => self.notification(notification), - // The only thing asked *of* the client is (un)registering the - // file watchers, and there is nothing to do with the answer: - // a client that refuses simply keeps the save-only model, and - // it says so on its own log, not ours. - Message::Response(_) => {} + Message::Response(response) => self.response(response), } } Ok(()) @@ -281,11 +304,34 @@ impl Server { match ports::execute(&self.workspace, &p.command, &p.arguments) { Ok((edit, warnings)) => { self.report_scope(warnings); - to_value(edit) + self.deliver(&p.command, edit) } Err(message) => Err(Failure::Request(message)), } }), + // Pull diagnostics, LSP 3.17. Same parse+lint pass the push model + // publishes; only the timing and the caching differ. + DocumentDiagnosticRequest::METHOD => { + decode(request).and_then(|p: DocumentDiagnosticParams| { + let report = self.document_report(&p.text_document.uri, p.previous_result_id); + to_value(DocumentDiagnosticReportResult::Report(report)) + }) + } + WorkspaceDiagnosticRequest::METHOD => { + decode(request).and_then(|p: WorkspaceDiagnosticParams| { + let report = self.workspace_report(&p.previous_result_ids); + to_value(WorkspaceDiagnosticReportResult::Report(report)) + }) + } + // Expand-selection. One chain per position, in the order asked — + // a client sends one position per cursor, and a multi-cursor + // editor matches the answers up by index. + SelectionRangeRequest::METHOD => decode(request).and_then(|p: SelectionRangeParams| { + match self.workspace.document(&p.text_document.uri) { + Some(doc) => to_value(selection::selection_ranges(doc, &p.positions)), + None => Ok(Value::Null), + } + }), // Module hinting. A position that is not a module item answers // `null` rather than an empty list, so the editor's own word // completion is left in charge there. @@ -412,6 +458,109 @@ impl Server { } } + /// Deliver a command's `WorkspaceEdit` the way the client can take it. + /// + /// The protocol has no place for an edit in an `executeCommand` *result*: + /// a client applies what a server pushes with `workspace/applyEdit`, and + /// drops the result on the floor. So the edit is pushed and the result is + /// `null` — except for a client that never advertised `workspace.applyEdit`, + /// which gets the old return-the-edit behavior because for that one it is + /// the only behavior that could ever work. + /// + /// The push goes out *before* the command's own response, which the loop + /// sends when this returns. The protocol allows a server to request at any + /// time, and a client that waited for the command result before applying + /// the edit would deadlock on any server that does this — VS Code and + /// Neovim both apply it immediately. + fn deliver(&mut self, command: &str, edit: WorkspaceEdit) -> Result { + if !self.abilities.apply_edit { + return to_value(edit); + } + let params = ApplyWorkspaceEditParams { label: Some(format!("lucisv: {command}")), edit }; + let id = self.send_request(ApplyWorkspaceEdit::METHOD, params); + self.applying.insert(id, command.to_string()); + Ok(Value::Null) + } + + // ------------------------------------------------------------------ + // pull diagnostics + // ------------------------------------------------------------------ + + /// One buffer's diagnostics, or an unchanged report when nothing that + /// feeds them has moved since the client's last pull. + fn document_report(&self, uri: &Uri, previous: Option) -> DocumentDiagnosticReport { + let result_id = self.result_id(); + if previous.as_deref() == Some(result_id.as_str()) { + let unchanged = UnchangedDocumentDiagnosticReport { result_id }; + return DocumentDiagnosticReport::Unchanged(RelatedUnchangedDocumentDiagnosticReport { + related_documents: None, + unchanged_document_diagnostic_report: unchanged, + }); + } + let full = FullDocumentDiagnosticReport { + result_id: Some(result_id), + items: self.diagnostics_of(uri), + }; + DocumentDiagnosticReport::Full(RelatedFullDocumentDiagnosticReport { + related_documents: None, + full_document_diagnostic_report: full, + }) + } + + /// Every open buffer's diagnostics, in URI order so two pulls of the same + /// state read the same way. + /// + /// Open buffers are the whole scope: this server has never diagnosed a + /// file it was not shown, and pulling would be the wrong place to start — + /// linting the workspace on a keystroke-driven request is a rescan of + /// every file per pull. The limit is stated in the feature README. + fn workspace_report(&self, previous: &[PreviousResultId]) -> WorkspaceDiagnosticReport { + let result_id = self.result_id(); + let mut uris = self.workspace.open_uris(); + uris.sort(); + let items = uris + .into_iter() + .map(|uri| { + let known = previous.iter().any(|seen| seen.uri == uri && seen.value == result_id); + if known { + let unchanged = + UnchangedDocumentDiagnosticReport { result_id: result_id.clone() }; + return WorkspaceDocumentDiagnosticReport::Unchanged( + WorkspaceUnchangedDocumentDiagnosticReport { + uri, + version: None, + unchanged_document_diagnostic_report: unchanged, + }, + ); + } + let full = FullDocumentDiagnosticReport { + result_id: Some(result_id.clone()), + items: self.diagnostics_of(&uri), + }; + WorkspaceDocumentDiagnosticReport::Full(WorkspaceFullDocumentDiagnosticReport { + uri, + version: None, + full_document_diagnostic_report: full, + }) + }) + .collect(); + WorkspaceDiagnosticReport { items } + } + + /// What a report is stamped with: the generation everything was computed + /// against. Coarse on purpose — a change anywhere costs one extra full + /// report elsewhere, and a stale "unchanged" would cost a wrong squiggle. + fn result_id(&self) -> String { + self.generation.to_string() + } + + /// Everything the server has to say about a buffer — the one computation + /// both diagnostic models answer from. A buffer that is not open has + /// nothing said about it. + fn diagnostics_of(&self, uri: &Uri) -> Vec { + self.workspace.document(uri).map(diagnostics::all).unwrap_or_default() + } + // ------------------------------------------------------------------ // notifications // ------------------------------------------------------------------ @@ -502,6 +651,39 @@ impl Server { } } + // ------------------------------------------------------------------ + // responses to what we asked + // ------------------------------------------------------------------ + + /// What the client answered. + /// + /// Only a `workspace/applyEdit` answer is read. The (un)registration of + /// the file watchers is the other thing ever asked, and there is nothing + /// to do with *its* answer: a client that refuses simply keeps the + /// save-only staleness model, and it says so on its own log, not ours. Its + /// ids are never in `applying`, so they fall out here. + fn response(&mut self, response: Response) { + let Some(command) = self.applying.remove(&response.id) else { return }; + // A refusal is worth saying out loud: the user ran a command, watched + // nothing happen, and would otherwise have no idea why. An answer that + // does not parse is a refusal too — nothing was seen to be applied. + let reason = match response.response_result { + Ok(value) => match serde_json::from_value::(value) { + Ok(applied) if applied.applied => return, + Ok(applied) => applied.failure_reason, + Err(problem) => Some(problem.to_string()), + }, + Err(error) => Some(error.message), + }; + let message = match reason { + Some(reason) => { + format!("lucisv: {command} — the editor did not apply the edit: {reason}") + } + None => format!("lucisv: {command} — the editor did not apply the edit."), + }; + self.show_message(MessageType::ERROR, message); + } + // ------------------------------------------------------------------ // outgoing // ------------------------------------------------------------------ @@ -529,15 +711,16 @@ impl Server { self.send_request(RegisterCapability::METHOD, params); } - /// Ask the client something. The answer is ignored (see `run`), but the id - /// must still be unique — a repeated one is a protocol error. - fn send_request(&mut self, method: &str, params: impl serde::Serialize) { + /// Ask the client something, reporting the id it will answer on — a + /// repeated id is a protocol error, so this only ever counts up. + fn send_request(&mut self, method: &str, params: impl serde::Serialize) -> RequestId { let id = RequestId::from(format!("lucisv-{}", self.request_ids)); self.request_ids += 1; - let request = Request::new(id, method.to_string(), params); + let request = Request::new(id.clone(), method.to_string(), params); // A closed channel means the client is gone; there is nobody left to // report the failure to. let _ = self.connection.sender.send(Message::Request(request)); + id } /// Rescan the workspace and republish every open buffer against the new @@ -545,6 +728,9 @@ impl Server { /// new `lucisv.exclude`/`lucisv.filelist`, or a watched file changing on disk. fn reindex(&mut self) { let warnings = self.workspace.rebuild_index(); + // Every open buffer's diagnostics are computed against the index, so a + // pulling client's cached answers are all stale from here. + self.generation += 1; self.report_scope(warnings); for uri in self.workspace.open_uris() { self.publish(&uri); @@ -583,17 +769,34 @@ impl Server { fn set_document(&mut self, uri: Uri, text: String) { self.config_warnings.remove(&uri); self.workspace.set_document(uri, text); + self.generation += 1; } /// Publish everything known about a buffer — parse errors and lint /// warnings — in one notification. Two publishes for one version would /// leave only the second on screen, since LSP replaces rather than merges. fn publish(&self, uri: &Uri) { - let Some(doc) = self.workspace.document(uri) else { return }; - self.send_diagnostics(uri.clone(), diagnostics::all(doc)); + // `send_diagnostics` would drop this anyway for a pulling client; the + // early return is so the parse+lint pass is not run for nobody, once + // per open buffer, on every index rebuild. + if self.abilities.pull_diagnostics || self.workspace.document(uri).is_none() { + return; + } + self.send_diagnostics(uri.clone(), self.diagnostics_of(uri)); } + /// Push one buffer's diagnostics — unless the client pulls them. + /// + /// A client that advertised `textDocument.diagnostic` owns the timing and + /// the lifecycle of every diagnostic it shows: it asks when it wants them + /// and drops them when it closes the document, so a push would be a second + /// set of squiggles arriving on a schedule it did not choose. This is the + /// one gate that keeps the two models from ever running for one client — + /// the `didClose` clear goes through here too, for the same reason. fn send_diagnostics(&self, uri: Uri, diagnostics: Vec) { + if self.abilities.pull_diagnostics { + return; + } let params = PublishDiagnosticsParams { uri, diagnostics, version: None }; self.notify(PublishDiagnostics::METHOD, params); } @@ -721,8 +924,12 @@ mod tests { impl Session { fn new(roots: Vec, file_watching: bool) -> Session { + Session::with(roots, ClientAbilities { file_watching, ..Default::default() }) + } + + /// A session against a client that said exactly `abilities`. + fn with(roots: Vec, abilities: ClientAbilities) -> Session { let (server_end, client) = Connection::memory(); - let abilities = ClientAbilities { snippets: false, file_watching }; let server = Server::new(server_end, roots, abilities); Session { server, client } } @@ -731,6 +938,25 @@ mod tests { self.server.notification(Notification::new(method.to_string(), params)); } + /// Drive one request through the real dispatch, as the loop would. + fn request(&mut self, method: &str, params: impl serde::Serialize) -> Response { + let id = RequestId::from(format!("test-{method}")); + self.server.request(Request::new(id, method.to_string(), params)) + } + + /// A request's result, or the reason it was refused. + fn result(&mut self, method: &str, params: impl serde::Serialize) -> Value { + match self.request(method, params).response_result { + Ok(value) => value, + Err(error) => panic!("{method} failed: {error:?}"), + } + } + + /// Answer the last request the server made of us. + fn answer(&mut self, id: RequestId, result: impl serde::Serialize) { + self.server.response(Response::new_ok(id, result)); + } + /// Everything the server has said since the last drain. fn drain(&self) -> Vec { self.client.receiver.try_iter().collect() @@ -738,10 +964,31 @@ mod tests { /// The requests the server has made of the client, as (method, params). fn requests(&self) -> Vec<(String, Value)> { + self.sent().into_iter().map(|request| (request.method, request.params)).collect() + } + + /// The requests the server has made of the client, ids included. + fn sent(&self) -> Vec { self.drain() .into_iter() .filter_map(|message| match message { - Message::Request(request) => Some((request.method, request.params)), + Message::Request(request) => Some(request), + _ => None, + }) + .collect() + } + + /// What the server showed the user since the last drain, as + /// (type, message). + fn shown(&self) -> Vec<(MessageType, String)> { + self.drain() + .into_iter() + .filter_map(|message| match message { + Message::Notification(n) if n.method == ShowMessage::METHOD => { + let params: ShowMessageParams = + serde_json::from_value(n.params).expect("show message params"); + Some((params.typ, params.message)) + } _ => None, }) .collect() @@ -760,6 +1007,19 @@ mod tests { .count() } + /// The diagnostics the server pushed since the last drain. + fn published(&self) -> Vec { + self.drain() + .into_iter() + .filter_map(|message| match message { + Message::Notification(n) if n.method == PublishDiagnostics::METHOD => { + Some(serde_json::from_value(n.params).expect("publish params")) + } + _ => None, + }) + .collect() + } + fn open(&mut self, path: &Path, text: &str) -> Uri { let uri = path_to_uri(path).expect("uri"); self.notify( @@ -1059,4 +1319,450 @@ mod tests { session.notify(DidChangeWatchedFiles::METHOD, DidChangeWatchedFilesParams { changes }); assert_eq!(session.publishes(), 0); } + + // ------------------------------------------------------------------ + // `workspace/applyEdit` + // ------------------------------------------------------------------ + + const SUB: &str = "module sub (\n input logic clk,\n input logic rst\n);\nendmodule\n"; + const TOP: &str = "module top;\n logic clk, rst;\n sub u_sub (.clk(clk));\nendmodule\n"; + + /// A two-module workspace with `top.sv` open, and the arguments that ask + /// for the one port its instantiation is missing. + fn propagating(name: &str, abilities: ClientAbilities) -> (Tree, Session, Value) { + let tree = Tree::new(name); + tree.write("sub.sv", SUB); + tree.write("top.sv", TOP); + let mut session = Session::with(vec![tree.path.clone()], abilities); + let uri = session.open(&tree.path.join("top.sv"), TOP); + let _ = session.drain(); + let params = serde_json::json!({ + "command": ports::PROPAGATE_PORTS, + "arguments": [uri, { "line": 2, "character": 6 }], + }); + (tree, session, params) + } + + #[test] + fn a_command_pushes_its_edit_when_the_client_can_apply_one() { + // The bug this fixes: the edit used to be the request *result*, which + // the protocol does not define and every stock client drops. + let abilities = ClientAbilities { apply_edit: true, ..Default::default() }; + let (_tree, mut session, params) = propagating("applyedit", abilities); + + let result = session.result(ExecuteCommand::METHOD, params); + assert_eq!(result, Value::Null, "the edit is not the result any more"); + + let sent = session.sent(); + assert_eq!(sent.len(), 1, "{sent:#?}"); + assert_eq!(sent[0].method, ApplyWorkspaceEdit::METHOD); + assert_eq!( + sent[0].params["label"], + serde_json::json!(format!("lucisv: {}", ports::PROPAGATE_PORTS)), + "the undo stack needs a name for it" + ); + let changes = sent[0].params["edit"]["changes"].as_object().expect("changes"); + let edits = changes.values().next().expect("one file edited"); + assert_eq!(edits[0]["newText"], ", .rst(rst)", "{:#?}", sent[0].params); + } + + #[test] + fn a_client_that_cannot_apply_edits_still_gets_the_edit_back() { + // The documented fallback: for such a client, returning the edit is + // the only thing that could ever work. + let (_tree, mut session, params) = propagating("noapplyedit", ClientAbilities::default()); + + let result = session.result(ExecuteCommand::METHOD, params); + let changes = result["changes"].as_object().expect("the edit is the result"); + let edits = changes.values().next().expect("one file edited"); + assert_eq!(edits[0]["newText"], ", .rst(rst)"); + assert!(session.sent().is_empty(), "and nothing is pushed at it"); + } + + #[test] + fn an_edit_the_editor_refused_is_reported_to_the_user() { + let abilities = ClientAbilities { apply_edit: true, ..Default::default() }; + let (_tree, mut session, params) = propagating("refused", abilities); + session.result(ExecuteCommand::METHOD, params); + let sent = session.sent(); + let id = sent[0].id.clone(); + + session.answer( + id, + serde_json::json!({ "applied": false, "failureReason": "the file is read-only" }), + ); + let shown = session.shown(); + assert_eq!(shown.len(), 1, "{shown:#?}"); + assert_eq!(shown[0].0, MessageType::ERROR); + assert!(shown[0].1.contains(ports::PROPAGATE_PORTS), "{}", shown[0].1); + assert!(shown[0].1.contains("the file is read-only"), "{}", shown[0].1); + } + + #[test] + fn an_edit_the_editor_applied_is_said_nothing_about() { + let abilities = ClientAbilities { apply_edit: true, ..Default::default() }; + let (_tree, mut session, params) = propagating("applied", abilities); + session.result(ExecuteCommand::METHOD, params); + let id = session.sent()[0].id.clone(); + + session.answer(id.clone(), serde_json::json!({ "applied": true })); + assert!(session.shown().is_empty(), "success is silent"); + + // And the id is spent: a duplicate answer says nothing either. + session.answer(id, serde_json::json!({ "applied": false })); + assert!(session.shown().is_empty(), "an answer to nothing is ignored"); + } + + #[test] + fn a_malformed_apply_edit_answer_is_reported_as_a_refusal() { + // QA attack: "a response that does not parse is a refusal" is stated + // in the Assumptions but was only exercised through `Err` results and + // a well-typed `applied: false`. This drives the branch where the + // payload is `Ok` JSON that does not deserialize as + // `ApplyWorkspaceEditResponse` at all (missing the required `applied` + // field) — the honest-refusal path, not a panic or a silent success. + let abilities = ClientAbilities { apply_edit: true, ..Default::default() }; + let (_tree, mut session, params) = propagating("malformedapplyedit", abilities); + session.result(ExecuteCommand::METHOD, params); + let id = session.sent()[0].id.clone(); + + session.answer(id, serde_json::json!({ "notApplied": "whatever" })); + let shown = session.shown(); + assert_eq!(shown.len(), 1, "an unparseable answer must still surface: {shown:#?}"); + assert_eq!(shown[0].0, MessageType::ERROR); + assert!(shown[0].1.contains(ports::PROPAGATE_PORTS), "{}", shown[0].1); + } + + #[test] + fn a_response_with_a_jsonrpc_error_is_reported_too() { + // The `Err` half of `response_result` — a client that rejects the + // `applyEdit` request outright at the JSON-RPC level, rather than + // answering it with `applied: false`. + let abilities = ClientAbilities { apply_edit: true, ..Default::default() }; + let (_tree, mut session, params) = propagating("rpcerror", abilities); + session.result(ExecuteCommand::METHOD, params); + let id = session.sent()[0].id.clone(); + + session.server.response(Response::new_err(id, 1, "internal error".to_string())); + let shown = session.shown(); + assert_eq!(shown.len(), 1, "{shown:#?}"); + assert_eq!(shown[0].0, MessageType::ERROR); + assert!(shown[0].1.contains("internal error"), "{}", shown[0].1); + } + + #[test] + fn a_watcher_registration_answer_is_still_ignored() { + // The one response that was always ignored must stay ignored now that + // responses are read at all — including an error one. + let tree = Tree::new("registeranswer"); + let mut session = Session::new(vec![tree.path.clone()], true); + let id = session.sent()[0].id.clone(); + session.answer(id.clone(), Value::Null); + session.server.response(Response::new_err(id, 1, "no thanks".to_string())); + assert!(session.shown().is_empty(), "nothing to tell the user"); + } + + // ------------------------------------------------------------------ + // pull diagnostics + // ------------------------------------------------------------------ + + /// A client that pulls diagnostics rather than being pushed them. + fn pulling() -> ClientAbilities { + ClientAbilities { pull_diagnostics: true, ..Default::default() } + } + + /// A buffer with one parse error and one lint finding in it. + const BROKEN: &str = "module m;\n\twire ;\nendmodule\n"; + + fn document_pull(session: &mut Session, uri: &Uri, previous: Option<&str>) -> Value { + session.result( + DocumentDiagnosticRequest::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri }, + "identifier": diagnostics::SOURCE, + "previousResultId": previous, + }), + ) + } + + #[test] + fn a_pulling_client_is_never_pushed_diagnostics() { + // Never both models for one client: the second set of squiggles would + // arrive on a schedule the client did not choose. + let tree = Tree::new("pullnopush"); + let mut session = Session::with(vec![tree.path.clone()], pulling()); + let path = tree.path.join("m.sv"); + let uri = session.open(&path, BROKEN); + assert_eq!(session.publishes(), 0, "`didOpen` pushed nothing"); + + session.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri, "version": 2 }, + "contentChanges": [{ "text": BROKEN }], + }), + ); + assert_eq!(session.publishes(), 0, "nor did a change"); + + session.notify( + DidSaveTextDocument::METHOD, + serde_json::json!({ "textDocument": { "uri": uri } }), + ); + assert_eq!(session.publishes(), 0, "nor a save's republish"); + + session.notify( + DidCloseTextDocument::METHOD, + serde_json::json!({ "textDocument": { "uri": uri } }), + ); + assert_eq!(session.publishes(), 0, "and the close clears nothing it never drew"); + } + + #[test] + fn a_pushing_client_keeps_being_pushed() { + let tree = Tree::new("pushstays"); + let mut session = Session::new(vec![tree.path.clone()], false); + session.open(&tree.path.join("m.sv"), BROKEN); + assert_eq!(session.publishes(), 1, "unchanged from before this feature"); + } + + #[test] + fn a_pull_is_full_once_and_unchanged_until_something_moves() { + let tree = Tree::new("pullunchanged"); + let mut session = Session::with(vec![tree.path.clone()], pulling()); + let uri = session.open(&tree.path.join("m.sv"), BROKEN); + + let first = document_pull(&mut session, &uri, None); + assert_eq!(first["kind"], "full"); + assert!(!first["items"].as_array().expect("items").is_empty(), "{first:#?}"); + let result_id = first["resultId"].as_str().expect("a result id").to_string(); + + let again = document_pull(&mut session, &uri, Some(&result_id)); + assert_eq!(again["kind"], "unchanged", "nothing moved: {again:#?}"); + assert_eq!(again["resultId"], serde_json::json!(result_id), "and it stays namable"); + + // A buffer change moves it. + session.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri, "version": 2 }, + "contentChanges": [{ "text": "module m;\n wire a;\nendmodule\n" }], + }), + ); + let after = document_pull(&mut session, &uri, Some(&result_id)); + assert_eq!(after["kind"], "full", "the buffer changed: {after:#?}"); + assert!(after["items"].as_array().expect("items").is_empty(), "and it is clean now"); + assert_ne!(after["resultId"], serde_json::json!(result_id), "a new stamp"); + } + + #[test] + fn an_index_rebuild_moves_the_result_id_too() { + // `inter_file_dependencies: true` is a promise: a save rebuilds the + // index, and what the index says can change what a *different* buffer + // reports. A stale "unchanged" there would be a wrong squiggle. + let tree = Tree::new("pullreindex"); + let mut session = Session::with(vec![tree.path.clone()], pulling()); + let uri = session.open(&tree.path.join("m.sv"), BROKEN); + let stamp = document_pull(&mut session, &uri, None)["resultId"] + .as_str() + .expect("a result id") + .to_string(); + + session.notify( + DidSaveTextDocument::METHOD, + serde_json::json!({ "textDocument": { "uri": uri } }), + ); + let after = document_pull(&mut session, &uri, Some(&stamp)); + assert_eq!(after["kind"], "full", "the index moved: {after:#?}"); + } + + #[test] + fn a_pull_for_a_buffer_that_is_not_open_is_empty_rather_than_an_error() { + let tree = Tree::new("pullclosed"); + let mut session = Session::with(vec![tree.path.clone()], pulling()); + let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri"); + let report = document_pull(&mut session, &uri, None); + assert_eq!(report["kind"], "full"); + assert!(report["items"].as_array().expect("items").is_empty()); + } + + #[test] + fn the_workspace_pull_reports_every_open_buffer_and_honours_its_stamps() { + let tree = Tree::new("workspacepull"); + let mut session = Session::with(vec![tree.path.clone()], pulling()); + let first = session.open(&tree.path.join("a.sv"), BROKEN); + let second = session.open(&tree.path.join("b.sv"), "module b;\nendmodule\n"); + + let report = session.result( + WorkspaceDiagnosticRequest::METHOD, + serde_json::json!({ "identifier": diagnostics::SOURCE, "previousResultIds": [] }), + ); + let items = report["items"].as_array().expect("items").clone(); + assert_eq!(items.len(), 2, "{report:#?}"); + assert!(items.iter().all(|item| item["kind"] == "full"), "{report:#?}"); + let uris: Vec<&str> = items.iter().map(|item| item["uri"].as_str().unwrap_or("")).collect(); + assert!(uris.contains(&first.as_str()) && uris.contains(&second.as_str()), "{uris:?}"); + let mut sorted = uris.clone(); + sorted.sort_unstable(); + assert_eq!(uris, sorted, "URI order, so two pulls of one state read alike"); + let stamp = items[0]["resultId"].as_str().expect("a result id").to_string(); + + // Re-asked with what the client already holds, both come back unchanged. + let report = session.result( + WorkspaceDiagnosticRequest::METHOD, + serde_json::json!({ + "identifier": diagnostics::SOURCE, + "previousResultIds": [ + { "uri": first, "value": stamp }, + { "uri": second, "value": stamp }, + ], + }), + ); + let items = report["items"].as_array().expect("items"); + assert_eq!(items.len(), 2); + assert!(items.iter().all(|item| item["kind"] == "unchanged"), "{items:#?}"); + + // A stamp from another generation is not the one we hold. + let report = session.result( + WorkspaceDiagnosticRequest::METHOD, + serde_json::json!({ + "identifier": diagnostics::SOURCE, + "previousResultIds": [{ "uri": first, "value": "0" }], + }), + ); + let items = report["items"].as_array().expect("items"); + assert!(items.iter().all(|item| item["kind"] == "full"), "{items:#?}"); + } + + #[test] + fn an_empty_workspace_answers_a_well_formed_empty_report() { + // QA attack: no open buffers at all — does `workspace/diagnostic` + // still answer a well-formed (if empty) report, rather than an error + // or a missing field? + let tree = Tree::new("workspaceemptypull"); + let mut session = Session::with(vec![tree.path.clone()], pulling()); + let report = session.result( + WorkspaceDiagnosticRequest::METHOD, + serde_json::json!({ "identifier": diagnostics::SOURCE, "previousResultIds": [] }), + ); + assert_eq!(report["items"], serde_json::json!([]), "{report:#?}"); + } + + #[test] + fn a_previous_result_id_for_a_uri_that_is_since_closed_is_harmless() { + // QA attack: the client's `previousResultIds` can name a document it + // has since closed (it does not have to prune its own cache eagerly). + // That URI is no longer among the open buffers `workspace_report` + // walks, so it must simply be absent from the answer — not an error, + // not a phantom entry. + let tree = Tree::new("workspaceclosedstamp"); + let mut session = Session::with(vec![tree.path.clone()], pulling()); + let first = session.open(&tree.path.join("a.sv"), BROKEN); + let closed = session.open(&tree.path.join("b.sv"), "module b;\nendmodule\n"); + let stamp = session.result( + WorkspaceDiagnosticRequest::METHOD, + serde_json::json!({ "identifier": diagnostics::SOURCE, "previousResultIds": [] }), + )["items"][0]["resultId"] + .as_str() + .expect("a result id") + .to_string(); + + session.notify( + DidCloseTextDocument::METHOD, + serde_json::json!({ "textDocument": { "uri": closed } }), + ); + + let report = session.result( + WorkspaceDiagnosticRequest::METHOD, + serde_json::json!({ + "identifier": diagnostics::SOURCE, + "previousResultIds": [ + { "uri": first, "value": stamp }, + { "uri": closed, "value": stamp }, + ], + }), + ); + let items = report["items"].as_array().expect("items"); + assert_eq!(items.len(), 1, "the closed uri is gone, not phantom-reported: {items:#?}"); + assert_eq!(items[0]["uri"], first.as_str(), "{items:#?}"); + } + + #[test] + fn a_previous_result_id_for_a_uri_never_seen_is_ignored() { + // QA attack: a `previousResultIds` entry naming a document this + // server never opened (a client warm-starting from a stale cache, or + // simply a typo'd uri) must not confuse the match-up for the uris + // that *are* open. + let tree = Tree::new("workspaceneverseenstamp"); + let mut session = Session::with(vec![tree.path.clone()], pulling()); + let opened = session.open(&tree.path.join("a.sv"), BROKEN); + let never_seen = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri"); + + let report = session.result( + WorkspaceDiagnosticRequest::METHOD, + serde_json::json!({ + "identifier": diagnostics::SOURCE, + "previousResultIds": [{ "uri": never_seen, "value": "0" }], + }), + ); + let items = report["items"].as_array().expect("items"); + assert_eq!(items.len(), 1, "{items:#?}"); + assert_eq!(items[0]["uri"], opened.as_str(), "{items:#?}"); + assert_eq!(items[0]["kind"], "full"); + } + + #[test] + fn both_models_say_exactly_the_same_thing_about_a_buffer() { + // One computation, two deliveries. A second conversion path would be + // a second set of off-by-one bugs. + let tree = Tree::new("samediagnostics"); + let mut pushed = Session::new(vec![tree.path.clone()], false); + pushed.open(&tree.path.join("m.sv"), BROKEN); + let published = pushed.published(); + assert_eq!(published.len(), 1); + + let mut pulled = Session::with(vec![tree.path.clone()], pulling()); + let uri = pulled.open(&tree.path.join("m.sv"), BROKEN); + let report = document_pull(&mut pulled, &uri, None); + + assert_eq!( + report["items"], + serde_json::to_value(&published[0].diagnostics).expect("diagnostics"), + ); + } + + // ------------------------------------------------------------------ + // `textDocument/selectionRange` + // ------------------------------------------------------------------ + + #[test] + fn a_selection_range_request_answers_one_chain_per_position() { + let tree = Tree::new("selection"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n"); + let result = session.result( + SelectionRangeRequest::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri }, + "positions": [{ "line": 1, "character": 2 }, { "line": 0, "character": 0 }], + }), + ); + let chains = result.as_array().expect("one chain per position"); + assert_eq!(chains.len(), 2, "{result:#?}"); + assert!(chains[0]["parent"].is_object(), "the innermost step has a parent"); + } + + #[test] + fn a_selection_range_request_for_an_unopened_buffer_answers_null() { + let tree = Tree::new("selectionclosed"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri"); + let result = session.result( + SelectionRangeRequest::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri }, + "positions": [{ "line": 0, "character": 0 }], + }), + ); + assert_eq!(result, Value::Null); + } } diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index 3b93063..edc129c 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -2500,3 +2500,185 @@ endmodule let _ = std::fs::remove_dir_all(&dir); } + +/// A buffer with one parse error and one lint finding, for the diagnostics +/// sessions below. +const DIAGNOSTIC_SOURCE: &str = "module m;\n\twire ;\nendmodule\n"; + +#[test] +fn a_pulling_client_is_answered_and_never_pushed_over_the_wire() { + // What only an e2e test can check: that a client which advertised + // `textDocument.diagnostic` at `initialize` really is pushed nothing — + // the "never both models" rule is about the wire, not about a handler. + let dir = temp_dir("pull"); + let file = dir.join("m.sv"); + std::fs::write(&file, DIAGNOSTIC_SOURCE).expect("write"); + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", file.display()); + + let mut live = Live::start(); + live.send(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"diagnostic":{{}}}}}}}}}}"# + )); + let initialize = live.wait_for(|m| m["id"] == 1); + let provider = &initialize["result"]["capabilities"]["diagnosticProvider"]; + assert_eq!(provider["identifier"], "lucisv", "{initialize:#?}"); + assert_eq!(provider["interFileDependencies"], true, "{initialize:#?}"); + assert_eq!(provider["workspaceDiagnostics"], true, "{initialize:#?}"); + live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#); + + live.send(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(DIAGNOSTIC_SOURCE).expect("json") + )); + live.send(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/diagnostic","params":{{"textDocument":{{"uri":"{uri}"}},"identifier":"lucisv"}}}}"# + )); + // The next thing the server says is either the answer or a push it must + // never have sent — so this one wait proves both halves. + let full = live.wait_for(|m| m["id"] == 2 || m["method"] == "textDocument/publishDiagnostics"); + assert_eq!(full["id"], 2, "a pulling client must not be pushed diagnostics: {full:#?}"); + assert_eq!(full["result"]["kind"], "full"); + let items = full["result"]["items"].as_array().expect("items"); + assert_eq!(items.len(), 2, "the parse error and the lint warning: {full:#?}"); + assert!(items.iter().all(|item| item["source"] == "lucisv"), "{items:#?}"); + let result_id = full["result"]["resultId"].as_str().expect("a result id").to_string(); + + // Nothing moved, so the client's cached report still stands. + live.send(&format!( + r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/diagnostic","params":{{"textDocument":{{"uri":"{uri}"}},"identifier":"lucisv","previousResultId":"{result_id}"}}}}"# + )); + let unchanged = live.wait_for(|m| m["id"] == 3); + assert_eq!(unchanged["result"]["kind"], "unchanged", "{unchanged:#?}"); + + // An edit moves it, and the fixed buffer comes back clean. + live.send(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":2}},"contentChanges":[{{"text":{}}}]}}}}"#, + serde_json::to_string("module m;\n wire a;\nendmodule\n").expect("json") + )); + live.send(&format!( + r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/diagnostic","params":{{"textDocument":{{"uri":"{uri}"}},"identifier":"lucisv","previousResultId":"{result_id}"}}}}"# + )); + let after = live.wait_for(|m| m["id"] == 4 || m["method"] == "textDocument/publishDiagnostics"); + assert_eq!(after["id"], 4, "still no push: {after:#?}"); + assert_eq!(after["result"]["kind"], "full", "{after:#?}"); + assert_eq!(after["result"]["items"].as_array().map(Vec::len), Some(0), "{after:#?}"); + + // And the workspace report names the open buffer. + live.send( + r#"{"jsonrpc":"2.0","id":5,"method":"workspace/diagnostic","params":{"identifier":"lucisv","previousResultIds":[]}}"#, + ); + let workspace = live.wait_for(|m| m["id"] == 5); + let items = workspace["result"]["items"].as_array().expect("items"); + assert_eq!(items.len(), 1, "one open buffer: {workspace:#?}"); + assert_eq!(items[0]["uri"], uri.as_str(), "{workspace:#?}"); + assert_eq!(items[0]["kind"], "full", "{workspace:#?}"); + + live.finish(); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_command_pushes_its_edit_to_a_client_that_can_apply_one() { + // The bug §9a fixes, checked where it actually bit: on the wire, against + // a client that says what `vscode-languageclient` says. + let dir = temp_dir("applyedit"); + let sub = dir.join("sub.sv"); + std::fs::write(&sub, PORTS_SUB).expect("write"); + let top = dir.join("top.sv"); + std::fs::write(&top, PORTS_TOP).expect("write"); + let root = format!("file://{}", dir.display()); + let top_uri = format!("file://{}", top.display()); + + let mut live = Live::start(); + live.send(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"workspace":{{"applyEdit":true}}}}}}}}"# + )); + live.wait_for(|m| m["id"] == 1); + live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#); + live.send(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(PORTS_TOP).expect("json") + )); + live.send(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"workspace/executeCommand","params":{{"command":"lucisv.propagatePorts","arguments":["{top_uri}",{{"line":2,"character":6}}]}}}}"# + )); + + // The push, before the command's own answer. + let push = live.wait_for(|m| m["method"] == "workspace/applyEdit"); + assert_eq!(push["params"]["label"], "lucisv: lucisv.propagatePorts", "{push:#?}"); + let edits = push["params"]["edit"]["changes"][&top_uri].as_array().expect("edits"); + assert_eq!(edits[0]["newText"], ", .rst(rst)", "{push:#?}"); + + // Answer it the way an editor does, and the command answers `null`. + let id = serde_json::to_string(&push["id"]).expect("json"); + live.send(&format!(r#"{{"jsonrpc":"2.0","id":{id},"result":{{"applied":true}}}}"#)); + let done = live.wait_for(|m| m["id"] == 2); + assert!(done["result"].is_null(), "the edit is not the result any more: {done:#?}"); + + live.finish(); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn selection_ranges_round_trip_over_the_wire() { + // What only an e2e test can check: the capability is advertised, and the + // linked chain survives JSON encoding as `parent` objects rather than as + // a flattened list. + let dir = temp_dir("selection"); + let file = dir.join("m.sv"); + let source = "module m;\n initial begin\n x = 1;\n end\nendmodule\n"; + std::fs::write(&file, source).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":{{}}}}}}"# + )), + 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(source).expect("json") + )), + // Two cursors: the `x` of `x = 1;`, and the `endmodule` line. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/selectionRange","params":{{"textDocument":{{"uri":"{uri}"}},"positions":[{{"line":2,"character":4}},{{"line":4,"character":0}}]}}}}"# + )), + 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"]["selectionRangeProvider"], + serde_json::json!(true), + "{initialize:#?}" + ); + + let response = messages.iter().find(|m| m["id"] == 2).expect("selectionRange response"); + let chains = response["result"].as_array().expect("one chain per position"); + assert_eq!(chains.len(), 2, "{response:#?}"); + + // The `x`, then its statement, then the block, then the module, then the + // file — each step wider than the last, and the last one whole-file. + let mut step = &chains[0]; + let mut widths = Vec::new(); + loop { + widths.push(( + step["range"]["start"]["line"].as_u64().expect("line"), + step["range"]["end"]["line"].as_u64().expect("line"), + )); + match step.get("parent") { + Some(parent) if parent.is_object() => step = parent, + _ => break, + } + } + assert!(widths.len() >= 4, "token, statement, block, module, file: {widths:?}"); + assert_eq!(widths[0], (2, 2), "the innermost step is on the cursor's own line"); + assert_eq!(widths.last(), Some(&(0, 5)), "and the file closes it: {widths:?}"); + + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/features/apply-edit/README.md b/docs/features/apply-edit/README.md new file mode 100644 index 0000000..2d66b7a --- /dev/null +++ b/docs/features/apply-edit/README.md @@ -0,0 +1,215 @@ +# apply-edit + +## Goal + +Make the three port commands actually edit something in a stock editor. +`workspace/executeCommand` used to answer with the `WorkspaceEdit` that +`ports::execute` computed, as the request's *result*. The protocol defines no +such thing: an `executeCommand` result is `any | null`, and a client applies +what a server **pushes** at it with `workspace/applyEdit`. +`vscode-languageclient` (which `editors/vscode/extension.js` uses unmodified) +drops the result on the floor, and so does Neovim's built-in client — so +`lucisv.addPort`, `lucisv.removePort` and `lucisv.propagatePorts` invoked *as +commands* did nothing at all in every stock client. (The code-action path was +never affected: a code action carries its edit inline.) This round pushes the +edit, answers `null`, and reads the one client response the server can no +longer ignore. + +## Assumptions + +- **`workspace.applyEdit` is the gate.** A client that advertised it gets the + push and a `null` result. A client that did not gets exactly the old + behavior — the edit as the result — because for that one it is the only + thing that could ever work, and a silent no-op is worse than a + non-standard answer that some caller may yet read. Both VS Code and Neovim + advertise it; `editors/vscode/smoke.js` sends `capabilities: {}` and so + takes the fallback, which is why it still passes untouched. +- **The push goes out before the command's own response.** The loop sends a + request's response when the handler returns, and the handler sends the + `applyEdit` request during it. The protocol allows a server to make a + request at any time, and a client that waited for the command result before + applying the edit would deadlock against any server that does this — VS + Code and Neovim both apply immediately. Stated here because it is the + ordering a reader would otherwise wonder about. +- **A refusal is worth a popup.** `ApplyWorkspaceEditResponse.applied: false` + means the user ran a command, watched nothing happen, and has no other way + to find out why. It is shown as an ERROR naming the command, plus the + client's own `failureReason` when it sent one. Success says nothing. +- **A response that does not parse is a refusal.** Nothing was seen to be + applied, so the honest thing is to say so rather than assume the best. +- **Watcher (un)registration answers stay ignored.** Their ids are never in + the pending map, so they fall straight through the new handler — including + an error response, which is what a client that refuses to watch sends. The + behavior `docs/features/file-watching/README.md` documents is unchanged. +- **No retry, no timeout.** A client that never answers leaves one entry in + the pending map for the life of the session; three port commands per + session is not a leak worth a timer, and the server has no timers by + design. +- **The `report_scope(warnings)` behavior is unchanged** — the engine's + warnings are still surfaced exactly as before, whichever delivery path the + edit takes. + +## Handshakes + +### `lucisv_server::server` + +- `ClientAbilities` gains `apply_edit: bool` and derives `Default`, so a test + can name only the ability it cares about. `main.rs` fills it from + `InitializeParams.capabilities.workspace.apply_edit`. +- `Server` gains `applying: HashMap` — the outstanding + `workspace/applyEdit` requests, each remembering the command that asked. +- `Server::send_request` now **returns** the `RequestId` it sent on. The + watcher registration ignores it, exactly as it ignores the answer. +- `run`'s `Message::Response(_) => {}` becomes `self.response(response)`. +- `ExecuteCommand` goes through the new `Server::deliver`. + +### `ports` + +`ports::execute`'s signature is unchanged; only the doc comment's claim that +"the server does not push `workspace/applyEdit`" is now false, and is +rewritten. No engine behavior changed. + +### `editors/vscode` + +**No extension change.** `vscode-languageclient` applies `workspace/applyEdit` +requests itself; `extension.js` has no custom `executeCommand` handling and +needs none. Verified by reading, not assumed. + +## Status / TODO + +- [x] `workspace.applyEdit` read into `ClientAbilities` at initialize +- [x] `Server::deliver`: push the edit with a `label`, answer `null` +- [x] `Server::response`: match answers to outstanding requests, report a + refusal as an ERROR naming the command +- [x] Return-the-edit fallback kept for a client that cannot apply +- [x] Tests: pushed-and-null, fallback-returns-the-edit, refusal reported, + success silent, duplicate/unknown answer ignored, watcher answer still + ignored +- [ ] Not done, deliberately: no `$/progress` or timeout on an unanswered + `applyEdit` — see Assumptions. +- [ ] Not done, deliberately: `WorkspaceEdit` still carries plain `changes` + (no `documentChanges`, no snippet edits). That is TODO §9c's item, and + it would improve `addPort` cursor placement. + +## Work log + +### 2026-08-26 — dev agent, §9a + +- **`deliver` is a method on `Server`, not a free function**, because it has + to both send a request and remember its id; splitting it would have meant + returning a request for the caller to send, which is a shape with one user. +- **`send_request` returning the id** was the smallest change that let the + applyEdit path record it. The two watcher call sites ignore the value; a + `RequestId` is not `#[must_use]`, so this stays silent. +- **The pending map is keyed by `RequestId`, not by command**, so two + commands in flight cannot be confused and a duplicate answer to a spent id + does nothing. Pinned by + `an_edit_the_editor_applied_is_said_nothing_about`'s second half. +- **The `label`** is `lucisv: ` — it is what an editor shows on its + undo stack, so it names the thing the user would want to undo. +- Files touched: `crates/lucisv_server/src/server.rs`, + `crates/lucisv_server/src/main.rs`, `crates/lucisv_server/tests/e2e.rs`, and + `ports.rs`'s stale doc comment (it claimed the server does not push + `workspace/applyEdit`). `editors/vscode/extension.js` was read and + deliberately left alone. + +**Verification.** `cargo fmt`, `cargo clippy --all-targets` (zero warnings), +`cargo test --workspace`, `node editors/vscode/smoke.js` — all clean. 5 new +unit tests in `server.rs` (plus the watcher-answer guard), 1 in `main.rs`, and +one e2e session (`a_command_pushes_its_edit_to_a_client_that_can_apply_one`) +that pushes the edit at a real binary and answers it as an editor would. + +## QA log + +### 2026-08-26 — QA agent, §9a + +**Re-ran the dev's verification, clean.** `cargo fmt --all -- --check`, +`cargo clippy --all-targets --workspace` (zero warnings, forced a rebuild by +touching the changed files first so the check was not answered from a stale +cache), `cargo test --workspace` (3 full runs, no failures), `node +editors/vscode/smoke.js target/debug/lucisv-server` (exit 0) — all reproduced +independently. + +**Read the diff against the README's claims,** file:line references against +the working tree as it stood before this QA pass: + +- `server.rs`'s `ExecuteCommand` handler (around what is now line 304) calls + `self.report_scope(warnings)` unconditionally in the `Ok` arm, before + `self.deliver(...)` branches on the ability — confirmed **both** the push + and the fallback path surface engine warnings identically. +- **RequestId collision, checked and ruled out.** `applying` and the watcher + (un)registration ids are both minted by the same `send_request`, whose + counter (`self.request_ids`) is a single monotonically increasing `u32` + shared across every call site — two ids can never collide, so a watcher + answer can never land in `applying` and vice versa. This is structural, + not incidental: there is exactly one counter to break for a collision to + become possible. +- `ports.rs`'s doc comment rewrite matches the new behavior; no engine + behavior changed there, confirmed by reading `execute`'s body (untouched + except the comment). + +**Attacked the response-routing path** (`server.rs::response`, the +`ApplyWorkspaceEditResponse` deserialization). The existing tests covered +`Ok(applied: true)`, `Ok(applied: false, failureReason)`, a duplicate answer, +and a watcher answer — but not the two cases the doc comment explicitly +claims to handle: a response payload that is `Ok` JSON but does not +deserialize as `ApplyWorkspaceEditResponse` at all, and a JSON-RPC-level +`Err` response (a client that rejects the request outright rather than +answering it). Added both as tests in `server.rs`: + +- `a_malformed_apply_edit_answer_is_reported_as_a_refusal` — answers with + `{"notApplied": "whatever"}` (no `applied` field, which is required with no + default in `lsp_types::ApplyWorkspaceEditResponse`); asserts one ERROR + naming the command, not a panic and not silence. +- `a_response_with_a_jsonrpc_error_is_reported_too` — uses + `Response::new_err` directly; asserts the `error.message` reaches the + shown text. + +Both pass. Confirms the "a response that does not parse is a refusal" +assumption is real code, not just a comment. + +**Found and fixed one self-inflicted test bug while adding the above:** the +first draft of `a_malformed_apply_edit_answer_is_reported_as_a_refusal` named +its tree `propagating("malformed", ...)`, which collides with the *existing* +`Tree::new("malformed")` in +`a_malformed_watched_files_notification_is_dropped` — both resolve to the +same `std::env::temp_dir()` path (keyed only by pid + name), so running the +suite in parallel raced the two tests' filesystem setup and made +`ports::execute` fail to find `sub.sv` (`server.rs`, originally around line +1417 in this session's numbering). Not a server bug — a QA-test-authoring +bug. Renamed to `"malformedapplyedit"`; reran the full `lucisv_server` suite +three times back to back with no failures. Worth a general note for future +dev/QA agents: `Tree::new`'s temp path is name-keyed, not test-keyed, so a +tree name must be checked for uniqueness across the whole crate, not just +the tests being added. + +**Capability reading:** `apply_edit_support` reads +`params.capabilities.workspace.as_ref().and_then(|w| w.apply_edit)` — +verified this cannot panic on `InitializeParams::default()` or any partial +capability object; already covered by +`apply_edit_support_is_read_from_the_clients_own_capabilities`, re-ran it +directly. + +**CLAUDE.md compliance:** grepped the new/changed lines in `server.rs`, +`main.rs`, `ports.rs` for `.unwrap()`, `.expect()`, `panic!` outside +`#[cfg(test)]` — none found. Public items added (`ClientAbilities::apply_edit`) +carry doc comments. README has all seven required sections; TODO.md's +checkbox is checked with the item text unchanged and a `→` pointer added. + +**Verdict: no blocking findings.** The two new attack tests and the +tree-name-collision fix are the only changes made to this feature's code. + +## Review + +### 2026-08-26 — lead + +Reviewed the diff, the work log and the QA log; re-ran fmt/clippy/the full +workspace suite/smoke.js myself, all clean. The design is right: the gate is +the client's own `workspace.apply_edit` capability, the fallback is exactly +the old behavior for exactly the clients the old behavior could serve, and +the pending-map keyed by the one shared id counter makes response routing +collision-free by construction (QA verified the same). The `deliver` +doc comment's deadlock note is a good catch worth keeping. The no-timeout +decision is accepted: three commands per session cannot leak meaningfully, +and the server has no timers by design. `ports.rs`'s previously-false doc +comment is now true. Accepted as shipped. diff --git a/docs/features/lucisv-server/README.md b/docs/features/lucisv-server/README.md index bdd2002..0efe1ae 100644 --- a/docs/features/lucisv-server/README.md +++ b/docs/features/lucisv-server/README.md @@ -18,7 +18,9 @@ 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/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didChange`/`didSave`, full-text sync | +| `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didChange`/`didSave`, full-text sync — **only for a client that does not pull**. See `docs/features/pull-diagnostics/README.md` | +| `textDocument/diagnostic`, `workspace/diagnostic` | the same parse+lint pass | The 3.17 pull model, served to a client that advertised `textDocument.diagnostic` — which is then pushed nothing at all. `resultId` is one generation counter, bumped by a buffer change and by an index rebuild; the workspace report covers the **open buffers**. Same feature README | +| `textDocument/selectionRange` | `Document.tokens`, AST spans, `pairs::analyze` | Expand-selection: one strictly nesting chain per requested position, token → statement → block → item → file. No expression step. See `docs/features/selection-range/README.md` | | `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries | | `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md` | | `textDocument/definition` | `includes::IncludeGraph`, then `Semantics`, then `ExternalResolutions` | A cursor on an `` `include`` line jumps to the resolved file's first byte; otherwise the in-file symbol table, then the workspace overlay, whose `Ambiguous` answer returns every location. See `docs/features/include-nav/README.md` | diff --git a/docs/features/pull-diagnostics/README.md b/docs/features/pull-diagnostics/README.md new file mode 100644 index 0000000..8d773b4 --- /dev/null +++ b/docs/features/pull-diagnostics/README.md @@ -0,0 +1,288 @@ +# pull-diagnostics + +## Goal + +Serve diagnostics the modern way (LSP 3.17): the client asks +`textDocument/diagnostic` for the buffer it is showing and +`workspace/diagnostic` for the rest, when *it* decides — so the visible editor +is prioritised, nothing is computed for a buffer nobody is looking at, and the +client caches by `resultId` instead of re-drawing everything on every +keystroke. lucisv had only the push model (`textDocument/publishDiagnostics` +on every change). This round adds the pull model beside it, off the same +parse+lint pass, and makes sure **one client is never served both** — two sets +of squiggles for one file is the classic way to ship this feature wrong. + +## Assumptions + +- **The capability is the switch.** A client that sent + `textDocument.diagnostic` at initialize is a pulling client and is pushed + *nothing at all*, ever. A client that did not keeps today's push behavior + byte for byte. There is no setting: the protocol already asks the question. +- **The `didClose` clear is not pushed to a pulling client either.** In the + push model an empty publish is how a server erases what it drew, and that + stays. In the pull model the client owns the whole lifecycle of what it + pulled — it decides when to ask and drops a closed document's diagnostics + itself (`vscode-languageclient`'s diagnostic feature does exactly this) — + so a publish arriving at close would be the server's only push of the + session and would land in a channel the client is not reading for this + document. The gate therefore sits in `send_diagnostics`, which both callers + go through: one place, no way to leak a push. +- **`resultId` is a single generation counter, and nothing else.** It is + bumped in `set_document` (a buffer's text changed) and in `reindex` (the + workspace index changed). A pull whose `previousResultId` equals the + current generation is answered `unchanged`; anything else is a full report. + This is deliberately **coarser** than per-buffer versioning: editing file A + invalidates the client's cached stamp for file B, which costs one extra + full report — a cheap, correct answer. The error the coarse direction + cannot make is the expensive one: a stale `unchanged` is a wrong squiggle + left on screen. (The brief suggested `generation/doc-version`; the server + does not track document versions at all — full-text sync ignores them — so + the second half would have been a constant. One number, documented, beats a + format that implies a precision that is not there.) +- **`inter_file_dependencies: true` is honest.** A save rebuilds the + workspace index, and a buffer's diagnostics are computed against that index + (`resolve_external` in `state.rs`), so a save in file A really can change + what file B reports. That is exactly why `reindex` bumps the generation. +- **`workspace/diagnostic` reports the open buffers only.** This server has + never diagnosed a file it was not shown: `publish` is per open buffer, and + `reindex` republishes only open buffers. Linting the whole workspace on a + pull would be a parse of every in-scope file per request, on a request a + client may send after every keystroke. So the workspace report is the open + buffers, in URI order. **This is the honest limit of the feature**: a + client using workspace diagnostics as its only source sees findings for + files it has open, not for the project. Widening it is its own round, with + its own cost model (and probably `workDoneProgress`, TODO §9b). +- **No partial results, no streaming, and no + `workspace/diagnostic/refresh`.** Partial results are not advertised, so no + client will ask for them. A refresh request would let the server tell a + pulling client "ask again, the index moved"; it is not sent, so such a + client sees post-save changes at its own next pull. Stated because it is + the one place the pull model is *lazier* than the push model this replaces. +- **Both models answer from one function.** `Server::diagnostics_of` is the + single computation (`diagnostics::all`, i.e. parse errors, then the + missing-closer warnings, then lint), and `publish` and both pull handlers + all call it. A second conversion path would be a second set of off-by-one + bugs; pinned by `both_models_say_exactly_the_same_thing_about_a_buffer`. +- **A pull for a buffer that is not open is an empty full report**, not an + error: the client asked about a document this server knows nothing about, + and "no findings" is the true answer. + +## Handshakes + +### `lucisv_server::main` + +- `capabilities()` gains `diagnostic_provider: DiagnosticServerCapabilities::Options` + with `identifier: "lucisv"` (the same string every diagnostic's `source` + carries — one constant, `diagnostics::SOURCE`), `inter_file_dependencies: + true`, `workspace_diagnostics: true`. +- `pull_diagnostics_support(&InitializeParams)` reads + `text_document.diagnostic`; its two fields (dynamic registration, related + documents) are about things this server does not do, so the presence of the + capability is the whole of the statement. + +### `lucisv_server::server` + +- `ClientAbilities` gains `pull_diagnostics: bool`. +- `Server` gains `generation: u64`, bumped in `set_document` and `reindex`. +- New handlers: `DocumentDiagnosticRequest`, `WorkspaceDiagnosticRequest`. +- `send_diagnostics` is now the single gate on pushing anything. +- `diagnostics_of(uri)` is the one computation both models read. + +### `diagnostics` + +Unchanged. `diagnostics::all` and `diagnostics::SOURCE` are consumed as they +already were; nothing was added to that module. + +### `editors/*` + +No change. `vscode-languageclient` 9.x advertises the diagnostic capability +and drives the pull itself, so the VS Code extension switches models with no +edit — and `editors/vscode/smoke.js` sends `capabilities: {}`, so it stays on +the push model and keeps asserting what it always asserted. + +## Status / TODO + +- [x] `DiagnosticOptions` advertised, identifier pinned to the publish source +- [x] `textDocument/diagnostic`: full report with a `resultId`, `unchanged` + when the generation stands +- [x] `workspace/diagnostic`: open buffers in URI order, `previousResultIds` + honoured per file +- [x] Push suppressed for a pulling client — including the `didClose` clear +- [x] One computation behind both models +- [x] Tests: never-pushed, push-client-unchanged, full-then-unchanged-then- + full, reindex moves the stamp, unopened buffer, workspace report and + its stamps, both models identical +- [ ] Not done, deliberately: workspace diagnostics do not cover unopened + workspace files — see Assumptions. +- [ ] Not done, deliberately: no `workspace/diagnostic/refresh`, no partial + results, no `relatedDocuments`. + +## Work log + +### 2026-08-26 — dev agent, §9a + +- **The gate went into `send_diagnostics`, not into `publish`.** Both the + change-driven publish and the `didClose` clear go through it, so one `if` + covers every push the server can make. Putting it in `publish` would have + left the close path pushing to a pulling client. +- **One generation counter** instead of the suggested + `generation/doc-version` pair: the server does not track document versions + (`DidChangeTextDocumentParams.version` is ignored under full-text sync), so + the second component would always have been the same string. Recorded in + Assumptions as a deliberate deviation from the brief, with the failure mode + it cannot have. +- **URI order in the workspace report** because `open_uris()` comes off a + `HashMap` and would otherwise shuffle between two pulls of identical state, + which reads as churn to a human and makes a test flaky. +- **`version: None`** on the workspace reports: the protocol wants the + document version the diagnostics were computed for, and this server has + none to give. +- Files touched: `crates/lucisv_server/src/server.rs`, + `crates/lucisv_server/src/main.rs`, `crates/lucisv_server/tests/e2e.rs`, and + the capability table in `docs/features/lucisv-server/README.md` (the + `publishDiagnostics` row is now conditional). Nothing in `diagnostics.rs`, + `lint.rs` or any engine crate. + +**Verification.** `cargo fmt`, `cargo clippy --all-targets` (zero warnings), +`cargo test --workspace`, `node editors/vscode/smoke.js` (still on the push +model, unchanged) — all clean. 8 new unit tests in `server.rs`, 2 in `main.rs` +(the options, and the capability probe), and one e2e session +(`a_pulling_client_is_answered_and_never_pushed_over_the_wire`) whose central +assertion is that the *next thing the server says* after a pull request is the +answer and not a push. + +## QA log + +### 2026-08-26 — QA agent, §9a + +**Re-ran the dev's verification, clean.** `cargo fmt --all -- --check`, +`cargo clippy --all-targets --workspace` (zero warnings, rebuilt from a +touched source tree so this wasn't answered from cache), `cargo test +--workspace` (3 full runs, no failures), `node editors/vscode/smoke.js +target/debug/lucisv-server` (exit 0, still on the push model as claimed). + +**The stale-`unchanged` hunt — this was the main assignment.** Traced every +input `Server::diagnostics_of` reads (`diagnostics::all`: parse errors + +`pairs::missing_end_diagnostics` + `lint::diagnostics`, all three reading only +`doc.text`/`doc.tokens`/`doc.tree`/`doc.line_index`/`doc.semantics` — +confirmed by reading `diagnostics.rs`, `lint.rs`'s `context()`, and +`vlog_linter::registry::default_rules()`) against every event that can reach +the server without going through `set_document` (which bumps `generation`) +or `reindex` (same): + +- `DidChangeConfiguration` (`server.rs`'s `notification` handler): the + settings it can change are `line_length`, `indent`, `exclude`, `filelist`, + `inline_templates` (`settings.rs`). Checked each against what + `diagnostics_of` actually reads: `line_length`/`indent` only ever reach + `format.rs` (the formatting request), never the lint or parse-error path; + `inline_templates` is ghost-text only, read nowhere near diagnostics. + `exclude`/`filelist` *do* trigger `self.reindex()` when + `set_client_settings` reports a real change — which bumps `generation` + anyway, so even though this pair does not currently touch a single open + buffer's own diagnostics, the code already treats it as invalidating. + **No live bug**, but see the finding below. +- `lucisv.toml` picked up via file watchers (`DidChangeWatchedFiles`, + `watch::touches_scope`): any matched source file always routes to + `self.reindex()`, unconditionally bumping `generation` — including for a + file nobody has open. Coarser than necessary (an edit to an unrelated file + invalidates every open buffer's stamp) but never stale-in-the-dangerous- + direction. +- `reindex` paths generally (save, watched-file change, exclude/filelist + change, `didOpen` with no workspace root): all funnel through the one + `reindex()` method, which increments `generation` unconditionally before + doing anything else — verified by reading the method body, not just the + call sites. +- **`doc.external`** (`resolve_external`, the thing the README's own + Assumptions section cites as *why* `inter_file_dependencies: true` is + honest) is read only by `hover.rs` and `nav.rs` — grepped every non-test + use. **Diagnostics never read it.** So today, no lint rule or parse error + actually depends on the workspace index at all; the README's justification + for `inter_file_dependencies` describes a coupling that does not yet exist + in the diagnostics path (it exists for hover/definition). This is not + presently a correctness bug — bumping `generation` on `reindex` is the + *safe* direction regardless of whether anything currently needs it — but + the README's Assumptions text over-claims the *reason*. **Finding + (informational, not a defect):** the real invariant this feature depends on + is "every diagnostic-affecting input bumps `generation`," which today is + satisfied only because diagnostics happen to have no configurable/workspace- + dependent input at all. `lint.rs`'s own doc comment says as much + ("Selection (`--select`/`--ignore`) has no `lucisv.toml` key yet"). The + day a lint rule becomes configurable or cross-file-aware, whoever adds it + must also audit whether it needs to bump `generation` — nothing today + enforces that, and this feature's tests cannot catch a violation of an + invariant about code that doesn't exist yet. Flagged for the lead/dev to + decide whether to soften the Assumptions wording; not fixed directly since + it is a wording call, not a code defect. +- Conclusion: **no reproducible stale-`unchanged` sequence exists against + the current codebase.** I looked for one (attempted repro via a + `lineLength` push mid-session expecting it to be invisible to a pull + client — it is, but it is also invisible to a *push* client for the same + reason: line length never touched diagnostics before this feature either) + and could not construct one. + +**Push/pull exclusivity, verified structurally, not just by test.** Grepped +`server.rs` for every call site of `send_diagnostics` (the only place +`PublishDiagnosticsParams` is constructed): exactly two — `publish()` (open/ +change/reindex) and the `didClose` clear. Both funnel through +`send_diagnostics`, which is the single `if self.abilities.pull_diagnostics +{ return; }` gate. There is no third path that could bypass it. Existing +test `a_pulling_client_is_never_pushed_diagnostics` already exercises +didOpen/didChange/didSave/didClose; added no new test here since the +structural argument (one gate, two call sites, both covered) is stronger +than another sequence test would be. + +**`workspace/diagnostic` edge cases — added three tests** in `server.rs`, +all passing: + +- `an_empty_workspace_answers_a_well_formed_empty_report` — no open buffers + at all: `items` is `[]`, not an error, not a missing field. +- `a_previous_result_id_for_a_uri_that_is_since_closed_is_harmless` — a + `previousResultIds` entry for a URI the client closed after its last pull: + the closed URI is simply absent from the answer (it is not among + `open_uris()`), never phantom-reported, never an error. +- `a_previous_result_id_for_a_uri_never_seen_is_ignored` — a + `previousResultIds` entry for a URI this server never opened: ignored, + does not disturb the report for URIs that *are* open. + +**`applyEdit`-adjacent note:** `diagnostics_of`'s early-return +(`self.workspace.document(uri).map(...).unwrap_or_default()`) means a pull +for an unopened buffer is `Full` with empty `items` rather than `Unchanged` +— checked this always answers `Full` regardless of what `previousResultId` +the client sends for an unopened URI, which is correct (an unopened buffer's +"generation" was never established for that client, so there is nothing to +consider unchanged). + +**CLAUDE.md compliance:** no `unwrap()`/`expect()`/`panic!` in the new +non-test code in `server.rs`/`main.rs`; `ClientAbilities::pull_diagnostics` +and `Server::generation`/`applying` (shared with apply-edit) carry doc +comments; `DiagnosticServerCapabilities` construction and +`pull_diagnostics_support` read capabilities defensively +(`.as_ref()`/`.is_some_and()`), confirmed no panic on +`InitializeParams::default()` by the existing test. README has all seven +sections; TODO.md checkbox is checked with item text unchanged. + +**Verdict: no blocking findings.** One informational finding recorded above +(Assumptions text describes a coupling that isn't live code yet — cosmetic, +not a defect) for the lead to weigh in on. Three new edge-case tests added, +all passing; the exhaustive input trace found no stale-`unchanged` path. + +## Review + +### 2026-08-26 — lead + +Reviewed the diff, the work log and the QA log; re-ran all gates myself, +clean. One computation (`diagnostics_of`) behind both models, one push gate +(`send_diagnostics`), one generation counter as the whole `resultId` — the +boring shape CLAUDE.md asks for, and QA's exhaustive input trace confirms +the coarse counter cannot produce a stale `unchanged` today. + +On QA's informational finding (the Assumptions justify +`inter_file_dependencies: true` via the index, which the diagnostics path +does not read yet): accepted as written. Bumping on reindex is the safe +direction and the semantic-lint roadmap (§9's future rounds, cross-file +rules) is precisely what will make the index a real input; the README +already states the true invariant — *every diagnostic-affecting input bumps +`generation`* — and whoever adds a lint config key or a cross-file rule +inherits it. The `both_models_say_exactly_the_same_thing_about_a_buffer` +test is the right tripwire for divergence. No change requested. Accepted +as shipped. diff --git a/docs/features/selection-range/README.md b/docs/features/selection-range/README.md new file mode 100644 index 0000000..91f624e --- /dev/null +++ b/docs/features/selection-range/README.md @@ -0,0 +1,227 @@ +# selection-range + +## Goal + +`textDocument/selectionRange` — expand-selection, the keystroke (⌃⇧→ in VS +Code, `(expand_region)` shapes in Vim) that grows the selection one +syntactic step at a time: the identifier, then the statement, then the block, +then the module, then the file. Editors fall back to a word/bracket heuristic +without it, which in Verilog means expanding through `begin`/`end` never +works. Cheap for lucisv: every range the chain needs is already computed for +something else, so this is a new arrangement of existing answers, not new +analysis. + +## Assumptions + +- **Four sources of ranges, one chain.** For a byte offset the server + collects: the token that covers it (`Document.tokens`), the AST spans that + cover it (items and statements, walked top-down and pruned to the branch + that contains the offset), the matched scope pairs that cover it + (`pairs::analyze`, the rainbow's own matcher), and the whole file. They are + sorted by width and filtered down to what actually nests. +- **No expression step.** The brief allows skipping it, and it is skipped: + `ExprKind` has ~40 variants and walking them is a large, dull function + whose only user would be this. The visible cost is that inside + `a + b * (c - d)` the chain jumps from the token straight to the statement. + The token step covers the common "select the identifier" case, and adding + expressions later is additive — one more source of spans, no change to the + chain machinery. Recorded so nobody thinks it was overlooked. +- **The chain must strictly nest, and is filtered rather than trusted.** Two + ranges that both cover the cursor need not contain one another: a tolerant + parse can leave an item span overlapping a scope pair. LSP requires every + step to contain its child, so a range that does not enclose what was kept + before it is dropped. That filter is also what removes the duplicates the + four sources produce for the same construct (a `module` is an item span + *and* a scope pair). +- **Zero-width ranges are dropped.** A step that selects nothing is not a + step a user can see. The one exception is the degenerate chain in an empty + buffer, where the file range itself is empty. +- **Containment includes the end offset.** A cursor sitting just after a word + is treated as on that word — that is where the keystroke is usually + pressed. The consequence at a boundary between two adjacent constructs is + that both cover the cursor; the nesting filter then keeps whichever is + smaller and drops the other, which is a valid chain either way. +- **Every requested position is answered, in order.** A multi-cursor editor + matches answers to cursors by index, so a skipped position would silently + mis-associate every later one. A position that resolves to nothing else + still gets the one-step file chain. +- **A file that does not lex answers the file range.** `Document::new` leaves + `tokens` empty and the tree an error leaf there, so three of the four + sources give nothing — and the fourth is enough to satisfy the protocol. +- **The walk is per-request and bounded.** It descends only into the node + that covers the offset, so it visits the cursor's ancestors and their + immediate siblings' spans, not the file. Recursion depth is bounded by the + parser's own nesting limit (`docs/features/recursion-limit/README.md`): a + tree this walks is a tree the parser built. + +## Handshakes + +### `lucisv_server::selection` (new module) + +```rust +pub fn selection_ranges(doc: &Document, positions: &[Position]) -> Vec; +``` + +Pure function over one `Document`, in the shape `folding.rs` and `pairs.rs` +already have: no `Workspace`, no client, unit-testable on a string. + +### `lucisv_server::main` + +`capabilities()` gains `selection_range_provider: +SelectionRangeProviderCapability::Simple(true)`. Nothing is configurable and +every position is answered, so there are no options to send. + +### `lucisv_server::server` + +One handler on `SelectionRangeRequest::METHOD`, answering `null` for a +document that is not open — the same shape `foldingRange` and +`documentSymbol` already use. + +### `vlog_parser::ast` + +Consumed read-only: `Item`/`ItemKind`, `Stmt`/`StmtKind`, `GenBlock`, +`GenElse`, `GenIf`, and the `span` fields on all of them. No change requested +of the parser. The walk duplicates the shape of `vlog_linter::visit`, which +is `pub(crate)` there and therefore not reusable; the copy here is ~60 lines +and prunes by offset, which the linter's does not. + +### `editors/*` + +No change: both VS Code and Neovim bind expand-selection to this request out +of the box. + +## Status / TODO + +- [x] `crates/lucisv_server/src/selection.rs`: token, AST, scope-pair and + file sources; nesting filter; linked-chain construction +- [x] `selection_range_provider` advertised +- [x] `textDocument/selectionRange` handled, `null` for an unopened buffer +- [x] Tests: 14 unit tests in `selection.rs` (including an exhaustive + "every step strictly contains its child, at every offset of a file" + sweep) and 2 in `server.rs` +- [ ] Not done, deliberately: no expression-level step — see Assumptions. +- [ ] Not done, deliberately: no port/parameter-list step. `AnsiPort` and + `ParamPort` carry spans, so it is a two-line addition when someone + wants it; today the chain inside a header goes token → module. + +## Work log + +### 2026-08-26 — dev agent, §9a + +- **Collect-then-filter, rather than build the chain while walking.** The + walk cannot know whether a scope pair will land between two of its own + spans, and a tolerant parse can produce spans that overlap rather than + nest. Throwing every covering range into one list and keeping what nests is + both shorter and provably correct — the invariant is checked in one place, + and `every_step_strictly_contains_the_one_before_it` sweeps every offset of + a nested file to prove it. +- **Scope pairs are kept even though the AST usually covers the same + constructs.** They are what still works when the parse went wrong, which is + exactly the buffer a user is mid-edit in + (`an_unclosed_scope_still_expands_through_what_did_close`). +- **The AST walk was copied, not shared.** `vlog_linter::visit` is + `pub(crate)`; making it public is a change to another crate for one caller, + which the brief forbids and CLAUDE.md discourages. The copy is smaller than + the original because it prunes on the offset. +- Files touched: `crates/lucisv_server/src/selection.rs` (new), + `crates/lucisv_server/src/main.rs`, `crates/lucisv_server/src/server.rs`, + `crates/lucisv_server/tests/e2e.rs`, and the capability table in + `docs/features/lucisv-server/README.md`. + +**Verification.** `cargo fmt`, `cargo clippy --all-targets` (zero warnings), +`cargo test --workspace`, `node editors/vscode/smoke.js` — all clean. 14 unit +tests in `selection.rs`, 2 in `server.rs`, and one e2e session +(`selection_ranges_round_trip_over_the_wire`) proving the chain survives JSON +encoding as nested `parent` objects. + +## QA log + +### 2026-08-26 — QA agent, §9a + +**Re-ran the dev's verification, clean.** `cargo fmt --all -- --check`, +`cargo clippy --all-targets --workspace` (zero warnings), `cargo test +--workspace` (3 full runs, no failures), `node editors/vscode/smoke.js +target/debug/lucisv-server` (exit 0). + +**The strictness claim, checked, not just trusted.** +`every_step_strictly_contains_the_one_before_it` (`selection.rs`) does assert +`outer != inner` in addition to containment, at every offset `0..=text.len()` +of a nested fixture — it is a real strictness sweep, not a containment-only +check with a misleading name. + +**Invariants from the assignment, checked one by one against existing +tests** (all present, all passing, no gaps found that needed a new test): + +- Multi-position order: `several_positions_are_answered_position_for_position` + asks three positions out of source order and checks each answer against + its own position by index. +- Position past EOF: `a_position_past_the_end_of_the_file_clamps_into_it`. +- UTF-16 / surrogate-pair-adjacent columns: `a_multibyte_line_keeps_the_ + columns_in_utf16` uses `é` (2-byte UTF-8, 1 UTF-16 unit) **and** `🎉` + (4-byte UTF-8, a UTF-16 *surrogate pair*) on the same line before the + target token — this is the specific case the assignment called out, and + it is already exercised, not just the single-BMP-character case. +- Empty file: `an_empty_file_still_answers_one_degenerate_chain`. +- A file that fails to parse: `a_file_that_does_not_lex_still_answers_the_ + file_range` (confirms `doc.tokens.is_empty()` as the premise, then checks + the fallback) and `an_unclosed_scope_still_expands_through_what_did_close` + (a tolerant *partial* parse — checks the scope-pair source still supplies + a step when the AST cannot). +- Capability reading: `selection_range_provider` is `Simple(true)`, no + conditional read of client capabilities at all — nothing to break here. + +**Went beyond the assignment's list: a corpus sweep.** Every hand-written +test above uses a handcrafted fixture designed to exercise one specific +construct — none of them can catch a real-world construct the four span +sources disagree about in a way nobody thought to write a test for. Added +`every_step_strictly_nests_over_the_real_corpus` to `selection.rs`: walks +every `.sv`/`.v`/`.svh`/`.vh` file under `corpus/` (skipped gracefully if not +checked out, matching this crate's other corpus tests), samples 8 evenly +spaced offsets per file, and asserts the same strict-nesting-plus-whole-file- +closure invariant the hand-written sweep proves on small fixtures. Result: +**860 files, 6,880 positions, zero panics, invariant held everywhere**, +runtime ~1.6s (fits comfortably in the default `cargo test` budget, not +`#[ignore]`d). This is real coverage of syntax nobody wrote a fixture for — +generate-for loops, deeply nested casex/casez, `ifdef`-gated regions, etc. +— that the four hand-picked test files cannot reach. + +**Two positions I could not distinguish as bugs vs. accepted design, +recorded rather than "fixed":** + +- `covers()`'s inclusive end (`span.start <= offset && offset <= span.end`) + means a cursor at the exact boundary between two adjacent siblings sees + both as covering it; the nesting filter then keeps whichever is smaller. + This is explicitly called out in the Assumptions as intentional and + provably safe (the filter guarantees strict nesting regardless of which + one wins), so not re-litigated. +- The AST walk in `items`/`statement` is a hand-copy of + `vlog_linter::visit`'s shape rather than a shared function, per the + Assumptions' stated reason (`visit` is `pub(crate)` in another crate). + Confirmed by reading `vlog_linter/src/visit.rs`'s visibility — it is + indeed `pub(crate)`, so the stated constraint is real, not just asserted. + +**CLAUDE.md compliance:** `selection.rs`'s only `pub` item +(`selection_ranges`) has a doc comment; no `unwrap()`/`expect()`/`panic!` +outside `#[cfg(test)]` in `selection.rs`, or in the touched parts of +`server.rs`/`main.rs`. README has all seven sections; TODO.md checkbox is +checked with item text unchanged. + +**Verdict: no blocking findings.** This is the most heavily self-tested of +the three features already (14 unit tests, an exhaustive small-file sweep); +the corpus sweep added here is a genuine widening of coverage, not a +response to a suspected bug, and it found none. + +## Review + +### 2026-08-26 — lead + +Reviewed the diff, the work log and the QA log; re-ran all gates myself, +clean. `nested()`'s sort-then-keep-what-strictly-contains is the right +five-line answer to the overlapping-sources problem, and the fallback chain +for an empty/unlexable buffer honors the protocol's one-answer-per-position +requirement without a special case in the dispatch. Skipping the expression +step was the correct scope call — the token step already gives "select the +identifier", and forty `ExprKind` arms is a follow-up, not a blocker. QA's +860-file corpus sweep (6,880 positions, invariant held everywhere) is +exactly the kind of evidence this repo's rounds are supposed to produce. +Accepted as shipped. diff --git a/editors/vscode/package.json b/editors/vscode/package.json index 42bd7ed..c366130 100644 --- a/editors/vscode/package.json +++ b/editors/vscode/package.json @@ -2,7 +2,7 @@ "name": "lucisv", "displayName": "lucisv — Verilog/SystemVerilog", "description": "Formatting, diagnostics, navigation and semantic highlighting for Verilog and SystemVerilog, served by the lucisv language server.", - "version": "0.7.2", + "version": "0.8.0", "publisher": "guoliangchen", "author": "Guoliang Chen", "license": "MIT",