From 4733b630ee603660f3314c22a8f10a09418c6fe5 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Wed, 18 Nov 2026 15:59:51 +0800 Subject: [PATCH 1/4] feat(lsp): support codeAction context/grouping, signatureHelp, inlayHint refresh/resolve and workspace/applyEdit --- rust/contracts/rust-core-api.md | 65 ++- rust/crates/core/src/protocol/command.rs | 4 + .../crates/core/src/runtime/dispatcher/lsp.rs | 15 + rust/crates/core/src/runtime/request_trace.rs | 1 + rust/crates/editor/src/preferences.rs | 6 +- rust/crates/lsp-client/src/client.rs | 1 + .../lsp-client/src/client/capabilities.rs | 86 +++ rust/crates/lsp-client/src/client/json_rpc.rs | 3 +- .../crates/lsp-client/src/client/lifecycle.rs | 28 +- rust/crates/lsp-client/src/client/requests.rs | 326 ++++++++++- rust/crates/lsp-client/src/client/results.rs | 541 ++++++++++++++++-- .../lsp-client/src/client/server_messages.rs | 72 +++ .../lsp-client/src/client/validation.rs | 2 + rust/crates/lsp-client/src/tests.rs | 327 +++++++++++ rust/crates/lsp-client/src/types.rs | 17 +- rust/crates/lsp-engine/src/documents.rs | 4 + rust/crates/lsp-engine/src/engine.rs | 2 + rust/crates/lsp-engine/src/events.rs | 44 ++ rust/crates/lsp-engine/src/function_calls.rs | 2 + rust/crates/lsp-engine/src/host_requests.rs | 100 ++++ rust/crates/lsp-engine/src/lib.rs | 12 +- rust/crates/lsp-engine/src/lifecycle.rs | 3 + rust/crates/lsp-engine/src/operations.rs | 45 ++ rust/crates/lsp-engine/src/provider_events.rs | 3 + rust/crates/lsp-engine/src/requests.rs | 33 ++ rust/crates/lsp-engine/src/server_messages.rs | 23 +- rust/crates/lsp-engine/src/state.rs | 4 + rust/crates/lsp-engine/src/tests.rs | 203 +++++++ rust/fixtures/editor/ide-essentials-v1.json | 1 + .../fixtures/lsp/editor-actions-hints-v1.json | 214 +++++++ 30 files changed, 2116 insertions(+), 71 deletions(-) create mode 100644 rust/fixtures/lsp/editor-actions-hints-v1.json diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 8983559a..07d3c9dc 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -699,6 +699,7 @@ or removing a command fails until the table changes in the same commit. | `lsp.functionProvider` | Select a registered function provider strictly inside one workspace | | `lsp.configureFunctionRelay` | Replace the enabled plugins and live workspace contexts Core's plugin-to-plugin function relay checks calls against | | `lsp.hostResponse` | Answer one host-service request a plugin backend sent | +| `lsp.applyEditResponse` | Answer one server-initiated `workspace/applyEdit` request with whether the host applied it | | `lsp.hostNotify` | Send one host notification to a plugin backend that negotiated it | | `lsp.pluginServerRequest` | Send one request of a plugin backend to the plugin's own language server, under the plugin's declared session policy | | `lsp.pluginServerNotify` | Send one notification of a plugin backend to the plugin's own language server | @@ -3445,21 +3446,28 @@ explicit `plugin.function.*` error. callee does not register the function within 30 seconds. `lsp.request` accepts a semantic `operation` plus -the operation-specific URI, position, range, diagnostics, item, action, or +the operation-specific URI, position, range, diagnostics, item, action, hint, or command fields, and returns `{ operationId }`. Supported operations include -completion and resolve, hover, definition/declaration/type-definition, references, +completion and resolve, hover, signature help (`signatureHelp`), definition/declaration/type-definition, references, implementation, rename, formatting, range formatting, document symbols, code actions and resolve, execute command, -inlay hints, full-document semantic tokens, folding ranges, document links +inlay hints and resolve (`inlayHints`, `resolveInlayHint`), full-document semantic tokens, folding ranges, document links (`documentLinks`, result `{ links: [{ range, target, tooltip }] }`; `target` is null until a server supplies it, and entries without a range are dropped), workspace symbols (`workspaceSymbols`, see below), code lens, and provider virtual documents. For code actions, `diagnostics` contains the original `LspClientDiagnostic` objects returned by Core: nullable integer `severity`, `tags`, and `relatedInformation` remain intact, and every range uses zero-based `line` / -`utf16Column` positions. A platform's display severity or marker projection is +`utf16Column` positions. Optional `codeActionContext` accepts `{ only?: string[], triggerKind?: 1 | 2 }` +(`1` invoked, `2` automatic). Disabled actions are omitted, titles are normalized +to single-line bounded text (512 bytes), each action carries a deterministic +`group` (`"quickfix"`, `"refactor"`, `"source"`, or `"other"`), and Core sorts +actions stably with `isPreferred` first and then `quickfix`, `refactor`, `source`, +`other` (up to 256 actions). `resolveCodeAction` strips Core-only `group` before +sending `codeAction/resolve`. A platform's display severity or marker projection is not a diagnostic request model. Non-LSP markers may request actions with a range -and an empty diagnostic context. The round-trip fixture is -`rust/fixtures/lsp/diagnostic-code-actions-v1.json`. +and an empty diagnostic context. The round-trip fixtures are +`rust/fixtures/lsp/diagnostic-code-actions-v1.json` and +`rust/fixtures/lsp/editor-actions-hints-v1.json`. Deadline cancellations are written by a separate session-owned worker. The deadline monitor never writes to stdin. A background write that exceeds @@ -3492,6 +3500,7 @@ typed events. Hosts should use `waitEvents` so idle sessions do not poll. Event types include `stateChanged`, `featuresChanged`, `diagnostics`, `requestCompleted`, `requestProgress`, `functionsChanged`, `hostRequest`, +`workspaceApplyEdit`, `inlayHintsRefresh`, `semanticTokensRefresh`, `serverInfoChanged`, and `log`. Every request completes at most once with either `result` or a structured runtime error containing provider/session, stage, optional method/document/request, stable code, and @@ -5575,7 +5584,41 @@ The `featuresChanged` event carries `completionOptions: `completionProvider` and its dynamic `textDocument/completion` registrations (empty arrays when none are declared). The event is re-sent when registrations change them. Hosts use it, not a hard-coded list, to send -`completionContext.triggerKind = 2`. +`completionContext.triggerKind = 2`. Whenever `signatureHelp` is offered, +`featuresChanged` likewise carries `signatureHelpOptions: +{ triggerCharacters: string[], retriggerCharacters: string[] }`, aggregated across +`signatureHelpProvider` and dynamic `textDocument/signatureHelp` registrations. + +Operation `signatureHelp` (`textDocument/signatureHelp`) requires `uri` and +`position` and accepts optional `signatureHelpContext` (`triggerKind` `1`..`3`, +one-character `triggerCharacter` when `triggerKind = 2`, `isRetrigger`, and +`activeSignatureHelp`, which may be a previously normalized Core `SignatureHelp` +result). Its normalized result is `{ signatureHelp: null }` when no signature is active, or +`{ signatureHelp: { signatures, activeSignature, activeParameter } }` (capped at 32 signatures, +128 parameters per signature, 512-character single-line labels, and 2048-byte +documentation). Each parameter is normalized from either a substring label or +UTF-16 `[start, end]` offsets into +`{ label, utf16Start, utf16End, byteStart, byteEnd, documentation, isMarkdown }`, +and `activeSignature` / `activeParameter` are clamped into range. + +Operation `inlayHints` (`textDocument/inlayHint`) sorts hints stably by +`(line, utf16Column)`, trims labels to single-line text of at most 48 characters +(with `…`), caps tooltips at 2048 bytes, and keeps at most 8 hints per line and +512 hints per viewport request. When the server advertises `inlayHintProvider.resolveProvider`, +`featuresChanged` includes `inlayHintResolve` and `resolveInlayHint` (`inlayHint/resolve`) +resolves a single hint (`{ hint }`). Core advertises `workspace.inlayHint.refreshSupport` +and forwards `workspace/inlayHint/refresh` as the `inlayHintsRefresh` event after +acknowledging the request with JSON-RPC `null`. + +When a language server sends `workspace/applyEdit`, Core validates its edit payload, +immediately replies `{ applied: false, failureReason }` for non-file URIs, snippet +edits, or `create`/`rename`/`delete` resource operations, and otherwise emits a +`workspaceApplyEdit` runtime event with `result: { applyEditId, label, changes }` +(mapping target file paths to UTF-16 text edits). After validating workspace +boundaries and applying or rejecting the edit via `lsp.planWorkspaceEdit` and +`lsp.applyTextEdits`, the host answers with `lsp.applyEditResponse` +(`{ sessionId, applyEditId, applied, failureReason? }`). If the server cancels the +pending request or the session shuts down first, Core settles the JSON-RPC call cleanly. Operation `documentSymbols` (`textDocument/documentSymbol`) needs only the document `uri` and is offered, as the `documentSymbols` feature, when the server @@ -7245,10 +7288,10 @@ replacement fails atomically. Invalid requests return `invalid_request` with sta `source_too_large`, `source_too_large_or_invalid`, `replacement_too_large`, `too_many_matches`. Source, query and replacement are never included in errors or diagnostic logs. -`editor.preferences.resolve` accepts optional `lineNumbers`, `whitespace`, `cursorStyle` -(`line`, `block`, `underline`), `cursorBlink` and `autoSaveDelayMilliseconds`. It returns -actual values and minimum/maximum delay. Defaults: true, false, line, true, 1500 ms; -unknown styles resolve to line and delay clamps to 250–60,000 ms. +`editor.preferences.resolve` accepts optional `lineNumbers`, `whitespace`, `inlayHints`, +`cursorStyle` (`line`, `block`, `underline`), `cursorBlink` and `autoSaveDelayMilliseconds`. +It returns actual values and minimum/maximum delay. Defaults: true, false, true, line, +true, 1500 ms; unknown styles resolve to line and delay clamps to 250–60,000 ms. `editor.recent.reduce` accepts `entries`, optional `event:{kind,path,name,line,column}`, `query` and `onlyEdited`. It returns bounded `entries` and filtered `results`. Paths are diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 299e966e..48dc9f9f 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -703,6 +703,8 @@ pub enum LspCommand { ConfigureFunctionRelay, /// Answers a plugin backend's host-service request (`lsp.hostResponse`). HostResponse, + /// Answers a language server's `workspace/applyEdit` request (`lsp.applyEditResponse`). + ApplyEditResponse, /// Sends a plugin backend one host notification (`lsp.hostNotify`). HostNotify, /// Sends a plugin-owned language server one request of its backend (`lsp.pluginServerRequest`). @@ -1426,6 +1428,7 @@ impl CoreCommand { "lsp.functionProvider" => Some(Self::Lsp(LspCommand::FunctionProvider)), "lsp.configureFunctionRelay" => Some(Self::Lsp(LspCommand::ConfigureFunctionRelay)), "lsp.hostResponse" => Some(Self::Lsp(LspCommand::HostResponse)), + "lsp.applyEditResponse" => Some(Self::Lsp(LspCommand::ApplyEditResponse)), "lsp.hostNotify" => Some(Self::Lsp(LspCommand::HostNotify)), "lsp.pluginServerRequest" => Some(Self::Lsp(LspCommand::PluginServerRequest)), "lsp.pluginServerNotify" => Some(Self::Lsp(LspCommand::PluginServerNotify)), @@ -1743,6 +1746,7 @@ mod tests { "lsp.functionRequest", "lsp.configureFunctionRelay", "lsp.hostResponse", + "lsp.applyEditResponse", "lsp.hostNotify", "lsp.pluginServerRequest", "lsp.pluginServerNotify", diff --git a/rust/crates/core/src/runtime/dispatcher/lsp.rs b/rust/crates/core/src/runtime/dispatcher/lsp.rs index cfb5f206..06ceaa21 100644 --- a/rust/crates/core/src/runtime/dispatcher/lsp.rs +++ b/rust/crates/core/src/runtime/dispatcher/lsp.rs @@ -372,6 +372,21 @@ pub(super) fn dispatch(command: LspCommand, id: Option, payload: Value) Err(error) => CoreResponse::failure(id, error), } } + LspCommand::ApplyEditResponse => { + match serde_json::from_value::(payload) + .map_err(|error| { + CoreError::new( + ErrorCode::InvalidRequest, + "Invalid workspace apply-edit response", + ) + .with_details(error.to_string()) + }) + .and_then(lithe_lsp_engine::apply_edit_response) + { + Ok(()) => CoreResponse::success(id, json!({})), + Err(error) => CoreResponse::failure(id, error), + } + } LspCommand::HostNotify => { match serde_json::from_value::(payload) .map_err(|error| { diff --git a/rust/crates/core/src/runtime/request_trace.rs b/rust/crates/core/src/runtime/request_trace.rs index 22290f37..8acf5a9b 100644 --- a/rust/crates/core/src/runtime/request_trace.rs +++ b/rust/crates/core/src/runtime/request_trace.rs @@ -185,6 +185,7 @@ pub(crate) fn is_hot(method: &str) -> bool { | "lsp.waitEvents" | "lsp.cancelOperation" | "lsp.hostResponse" + | "lsp.applyEditResponse" | "lsp.hostNotify" | "debug.receive" | "debug.transport.handle" diff --git a/rust/crates/editor/src/preferences.rs b/rust/crates/editor/src/preferences.rs index bc9a0021..9d702454 100644 --- a/rust/crates/editor/src/preferences.rs +++ b/rust/crates/editor/src/preferences.rs @@ -9,6 +9,7 @@ use serde_json::{json, Value}; struct Stored { line_numbers: Option, whitespace: Option, + inlay_hints: Option, cursor_style: Option, cursor_blink: Option, auto_save_delay_milliseconds: Option, @@ -27,6 +28,7 @@ pub fn resolve_command(payload: Value) -> Result { Ok(json!({ "lineNumbers":stored.line_numbers.unwrap_or(true), "whitespace":stored.whitespace.unwrap_or(false), + "inlayHints":stored.inlay_hints.unwrap_or(true), "cursorStyle":style, "cursorBlink":stored.cursor_blink.unwrap_or(true), "autoSaveDelayMilliseconds":stored.auto_save_delay_milliseconds.unwrap_or(1500).clamp(250,60_000), @@ -43,14 +45,16 @@ mod tests { let value = resolve_command(json!({})).unwrap(); assert_eq!(value["lineNumbers"], true); assert_eq!(value["whitespace"], false); + assert_eq!(value["inlayHints"], true); assert_eq!(value["cursorStyle"], "line"); assert_eq!(value["cursorBlink"], true); assert_eq!(value["autoSaveDelayMilliseconds"], 1500); } #[test] fn corrupted_values_are_bounded_without_replacing_valid_choices() { - let value = resolve_command(json!({"lineNumbers":false,"cursorStyle":"unknown","cursorBlink":false,"autoSaveDelayMilliseconds":1})).unwrap(); + let value = resolve_command(json!({"lineNumbers":false,"inlayHints":false,"cursorStyle":"unknown","cursorBlink":false,"autoSaveDelayMilliseconds":1})).unwrap(); assert_eq!(value["lineNumbers"], false); + assert_eq!(value["inlayHints"], false); assert_eq!(value["cursorStyle"], "line"); assert_eq!(value["cursorBlink"], false); assert_eq!(value["autoSaveDelayMilliseconds"], 250); diff --git a/rust/crates/lsp-client/src/client.rs b/rust/crates/lsp-client/src/client.rs index 1a2c3587..d293b7ef 100644 --- a/rust/crates/lsp-client/src/client.rs +++ b/rust/crates/lsp-client/src/client.rs @@ -134,6 +134,7 @@ mod formatting_and_completion_tests { command: None, formatting_options: options, include_declaration: None, + ..Default::default() } } diff --git a/rust/crates/lsp-client/src/client/capabilities.rs b/rust/crates/lsp-client/src/client/capabilities.rs index 2cdd97e7..6b9f1743 100644 --- a/rust/crates/lsp-client/src/client/capabilities.rs +++ b/rust/crates/lsp-client/src/client/capabilities.rs @@ -79,6 +79,12 @@ pub(crate) fn feature_names_from_capabilities(capabilities: &Value) -> Vec Vec Option { + if !state + .server_capabilities + .iter() + .any(|feature| feature == "signatureHelp") + { + return None; + } + let collect = |key: &str| { + let mut values: Vec = Vec::new(); + for options in state.signature_help_providers.values() { + for value in options + .get(key) + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .filter(|value| !value.is_empty()) + { + insert_unique(&mut values, value); + } + } + values + }; + Some(json!({ + "triggerCharacters": collect("triggerCharacters"), + "retriggerCharacters": collect("retriggerCharacters"), + })) +} + /// Completion trigger and all-commit characters the session's providers declared. /// /// Returns `{ "triggerCharacters": [...], "allCommitCharacters": [...] }`, each @@ -327,6 +412,7 @@ pub(crate) fn feature_name_for_method(method: &str) -> Option<&'static str> { "textDocument/implementation" => Some("implementation"), "textDocument/references" => Some("references"), "textDocument/hover" => Some("hover"), + "textDocument/signatureHelp" => Some("signatureHelp"), "textDocument/completion" => Some("completion"), "textDocument/rename" => Some("rename"), "textDocument/formatting" => Some("formatting"), diff --git a/rust/crates/lsp-client/src/client/json_rpc.rs b/rust/crates/lsp-client/src/client/json_rpc.rs index 5517c2c5..69bc7118 100644 --- a/rust/crates/lsp-client/src/client/json_rpc.rs +++ b/rust/crates/lsp-client/src/client/json_rpc.rs @@ -68,7 +68,8 @@ pub fn json_rpc_error_with_data( })) } -pub(crate) fn json_rpc_error(id: &Value, code: i64, message: &str) -> Result { +/// Encodes a standard JSON-RPC error response to request `id`. +pub fn json_rpc_error(id: &Value, code: i64, message: &str) -> Result { encode_json_rpc(json!({ "jsonrpc": "2.0", "id": id, diff --git a/rust/crates/lsp-client/src/client/lifecycle.rs b/rust/crates/lsp-client/src/client/lifecycle.rs index 6add9cf8..073b9f58 100644 --- a/rust/crates/lsp-client/src/client/lifecycle.rs +++ b/rust/crates/lsp-client/src/client/lifecycle.rs @@ -58,6 +58,17 @@ pub fn client_initialize_for_plugin( "dynamicRegistration": true, "contentFormat": ["markdown", "plaintext"] }, + "signatureHelp": { + "dynamicRegistration": true, + "signatureInformation": { + "documentationFormat": ["markdown", "plaintext"], + "parameterInformation": { + "labelOffsetSupport": true + }, + "activeParameterSupport": true + }, + "contextSupport": true + }, "definition": { "dynamicRegistration": true }, "declaration": { "dynamicRegistration": true }, "typeDefinition": { "dynamicRegistration": true }, @@ -70,7 +81,18 @@ pub fn client_initialize_for_plugin( "dynamicRegistration": true, "hierarchicalDocumentSymbolSupport": true }, - "inlayHint": { "dynamicRegistration": true }, + "inlayHint": { + "dynamicRegistration": true, + "resolveSupport": { + "properties": [ + "tooltip", + "textEdits", + "label.tooltip", + "label.location", + "label.command" + ] + } + }, "semanticTokens": { "dynamicRegistration": true, "requests": { "full": true, "range": false }, @@ -110,7 +132,9 @@ pub fn client_initialize_for_plugin( } } }, - "workspace": { "semanticTokens": { "refreshSupport": true }, + "workspace": { + "semanticTokens": { "refreshSupport": true }, + "inlayHint": { "refreshSupport": true }, "applyEdit": true, "configuration": true, "workspaceFolders": true, diff --git a/rust/crates/lsp-client/src/client/requests.rs b/rust/crates/lsp-client/src/client/requests.rs index 1cd92982..93c02088 100644 --- a/rust/crates/lsp-client/src/client/requests.rs +++ b/rust/crates/lsp-client/src/client/requests.rs @@ -46,6 +46,11 @@ pub(crate) fn feature_request_params(request: &ClientFeatureRequest) -> Result Ok(json!({ + "textDocument": text_document, + "position": lsp_position_json(required_position(request)?), + "context": signature_help_context_json(request.signature_help_context.as_ref())? + })), "textDocument/references" => Ok(json!({ "textDocument": text_document, "position": lsp_position_json(required_position(request)?), @@ -82,13 +87,10 @@ pub(crate) fn feature_request_params(request: &ClientFeatureRequest) -> Result Ok(json!({ "textDocument": text_document, "range": lsp_range_json(required_range(request)?), - "context": { - "diagnostics": request - .diagnostics - .iter() - .map(lsp_diagnostic_json) - .collect::>() - } + "context": code_action_context_json( + &request.diagnostics, + request.code_action_context.as_ref(), + )? })), "completionItem/resolve" => request.completion_item.clone().ok_or_else(|| { CoreError::new( @@ -96,12 +98,8 @@ pub(crate) fn feature_request_params(request: &ClientFeatureRequest) -> Result request.code_action.clone().ok_or_else(|| { - CoreError::new( - ErrorCode::InvalidRequest, - "This LSP request requires a code action.", - ) - }), + "codeAction/resolve" => code_action_resolve_json(request.code_action.as_ref()), + "inlayHint/resolve" => inlay_hint_resolve_json(request.inlay_hint.as_ref()), "workspace/executeCommand" => request.command.clone().ok_or_else(|| { CoreError::new( ErrorCode::InvalidRequest, @@ -214,3 +212,305 @@ fn lsp_range_response_json(range: LspRangeResponse) -> Value { } }) } + +fn code_action_context_json( + diagnostics: &[LspClientDiagnostic], + supplied: Option<&Value>, +) -> Result { + let mut context = json!({ + "diagnostics": diagnostics.iter().map(lsp_diagnostic_json).collect::>() + }); + let Some(supplied) = supplied.filter(|value| !value.is_null()) else { + return Ok(context); + }; + let invalid = || CoreError::new(ErrorCode::InvalidRequest, "Invalid code action context"); + let object = supplied.as_object().ok_or_else(invalid)?; + for (key, value) in object { + match key.as_str() { + "only" => { + let items = value.as_array().ok_or_else(invalid)?; + if items.is_empty() || items.len() > 32 { + return Err(invalid()); + } + let mut kinds = Vec::with_capacity(items.len()); + for item in items { + let kind = item + .as_str() + .filter(|kind| !kind.trim().is_empty() && kind.len() <= 128) + .ok_or_else(invalid)?; + kinds.push(kind); + } + context["only"] = json!(kinds); + } + "triggerKind" => { + let kind = value.as_u64().ok_or_else(invalid)?; + if !matches!(kind, 1 | 2) { + return Err(invalid()); + } + context["triggerKind"] = json!(kind); + } + _ => return Err(invalid().with_details(key.clone())), + } + } + Ok(context) +} + +fn signature_help_context_json(supplied: Option<&Value>) -> Result { + let Some(supplied) = supplied.filter(|value| !value.is_null()) else { + return Ok(json!({ + "triggerKind": 1, + "isRetrigger": false + })); + }; + let invalid = || CoreError::new(ErrorCode::InvalidRequest, "Invalid signature help context"); + let object = supplied.as_object().ok_or_else(invalid)?; + for key in object.keys() { + if !matches!( + key.as_str(), + "triggerKind" | "triggerCharacter" | "isRetrigger" | "activeSignatureHelp" + ) { + return Err(invalid().with_details(key.clone())); + } + } + let kind = object + .get("triggerKind") + .and_then(Value::as_u64) + .filter(|kind| (1..=3).contains(kind)) + .ok_or_else(|| { + CoreError::new( + ErrorCode::InvalidRequest, + "Invalid signature help trigger kind", + ) + })?; + let is_retrigger = match object.get("isRetrigger") { + Some(Value::Bool(value)) => *value, + None => false, + Some(_) => return Err(invalid()), + }; + let mut context = json!({ + "triggerKind": kind, + "isRetrigger": is_retrigger + }); + if let Some(character_value) = object.get("triggerCharacter").filter(|v| !v.is_null()) { + let character = character_value + .as_str() + .filter(|text| text.chars().count() == 1) + .ok_or_else(|| { + CoreError::new( + ErrorCode::InvalidRequest, + "Signature help trigger character must be a single character", + ) + })?; + context["triggerCharacter"] = json!(character); + } else if kind == 2 { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Signature help trigger character is required", + )); + } + if let Some(active) = object.get("activeSignatureHelp").filter(|v| !v.is_null()) { + context["activeSignatureHelp"] = + sanitize_active_signature_help(active).ok_or_else(invalid)?; + } + Ok(context) +} + +fn sanitize_active_signature_help(active: &Value) -> Option { + let object = active.as_object()?; + let signatures = object.get("signatures")?.as_array()?; + let mut mapped_signatures = Vec::with_capacity(signatures.len().min(32)); + for signature in signatures.iter().take(32) { + let sig_obj = signature.as_object()?; + let label = sig_obj.get("label")?.as_str()?; + let mut mapped_sig = json!({ "label": label }); + if let Some(doc) = sig_obj.get("documentation").filter(|v| !v.is_null()) { + if let Some(text) = doc.as_str() { + let is_markdown = sig_obj + .get("isMarkdown") + .and_then(Value::as_bool) + .unwrap_or(false); + if is_markdown { + mapped_sig["documentation"] = json!({ "kind": "markdown", "value": text }); + } else { + mapped_sig["documentation"] = json!(text); + } + } else if doc.is_object() { + mapped_sig["documentation"] = doc.clone(); + } + } + if let Some(parameters) = sig_obj.get("parameters").and_then(Value::as_array) { + let mut mapped_params = Vec::with_capacity(parameters.len().min(128)); + for param in parameters.iter().take(128) { + let Some(param_obj) = param.as_object() else { + continue; + }; + let label_value = if let (Some(start), Some(end)) = ( + param_obj.get("utf16Start").and_then(Value::as_u64), + param_obj.get("utf16End").and_then(Value::as_u64), + ) { + json!([start, end]) + } else if let Some(label_value) = param_obj.get("label") { + if label_value.is_string() || label_value.is_array() { + label_value.clone() + } else { + continue; + } + } else { + continue; + }; + let mut mapped_param = json!({ "label": label_value }); + if let Some(doc) = param_obj.get("documentation").filter(|v| !v.is_null()) { + if let Some(text) = doc.as_str() { + let is_markdown = param_obj + .get("isMarkdown") + .and_then(Value::as_bool) + .unwrap_or(false); + if is_markdown { + mapped_param["documentation"] = + json!({ "kind": "markdown", "value": text }); + } else { + mapped_param["documentation"] = json!(text); + } + } else if doc.is_object() { + mapped_param["documentation"] = doc.clone(); + } + } + mapped_params.push(mapped_param); + } + mapped_sig["parameters"] = json!(mapped_params); + } + if let Some(active_param) = sig_obj.get("activeParameter").and_then(Value::as_u64) { + mapped_sig["activeParameter"] = json!(active_param); + } + mapped_signatures.push(mapped_sig); + } + let mut out = json!({ "signatures": mapped_signatures }); + if let Some(active_sig) = object.get("activeSignature").and_then(Value::as_u64) { + out["activeSignature"] = json!(active_sig); + } + if let Some(active_param) = object.get("activeParameter").and_then(Value::as_u64) { + out["activeParameter"] = json!(active_param); + } + Some(out) +} + +fn code_action_resolve_json(action: Option<&Value>) -> Result { + let action = action.ok_or_else(|| { + CoreError::new( + ErrorCode::InvalidRequest, + "This LSP request requires a code action.", + ) + })?; + let object = action.as_object().ok_or_else(|| { + CoreError::new( + ErrorCode::InvalidRequest, + "Code action payload must be an object.", + ) + })?; + if object.get("title").and_then(Value::as_str).is_none() { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Code action payload requires a title.", + )); + } + let mut cleaned = serde_json::Map::new(); + for (key, value) in object { + if key == "group" { + continue; + } + if value.is_null() + && matches!( + key.as_str(), + "kind" | "edit" | "command" | "data" | "diagnostics" | "disabled" + ) + { + continue; + } + cleaned.insert(key.clone(), value.clone()); + } + Ok(Value::Object(cleaned)) +} + +fn inlay_hint_resolve_json(hint: Option<&Value>) -> Result { + let hint = hint.ok_or_else(|| { + CoreError::new( + ErrorCode::InvalidRequest, + "This LSP request requires an inlay hint.", + ) + })?; + let object = hint.as_object().ok_or_else(|| { + CoreError::new( + ErrorCode::InvalidRequest, + "Inlay hint payload must be an object.", + ) + })?; + let position = object + .get("position") + .and_then(lsp_wire_position_from_any) + .ok_or_else(|| { + CoreError::new( + ErrorCode::InvalidRequest, + "Inlay hint payload requires a position.", + ) + })?; + let label = object.get("label").ok_or_else(|| { + CoreError::new( + ErrorCode::InvalidRequest, + "Inlay hint payload requires a label.", + ) + })?; + if !label.is_string() && !label.is_array() { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Inlay hint label must be a string or label part array.", + )); + } + let mut mapped = serde_json::Map::new(); + mapped.insert("position".to_string(), position); + mapped.insert("label".to_string(), label.clone()); + if let Some(kind) = object.get("kind").and_then(Value::as_i64) { + mapped.insert("kind".to_string(), json!(kind)); + } + if let Some(padding_left) = object.get("paddingLeft").and_then(Value::as_bool) { + mapped.insert("paddingLeft".to_string(), json!(padding_left)); + } + if let Some(padding_right) = object.get("paddingRight").and_then(Value::as_bool) { + mapped.insert("paddingRight".to_string(), json!(padding_right)); + } + if let Some(tooltip) = object.get("tooltip").filter(|v| !v.is_null()) { + mapped.insert("tooltip".to_string(), tooltip.clone()); + } + if let Some(edits) = object.get("textEdits").and_then(Value::as_array) { + let converted: Vec = edits + .iter() + .filter_map(lsp_wire_text_edit_from_any) + .collect(); + if !converted.is_empty() { + mapped.insert("textEdits".to_string(), json!(converted)); + } + } + if let Some(data) = object.get("data").filter(|v| !v.is_null()) { + mapped.insert("data".to_string(), data.clone()); + } + Ok(Value::Object(mapped)) +} + +fn lsp_wire_position_from_any(value: &Value) -> Option { + let line = value.get("line")?.as_i64()?; + let character = value + .get("character") + .or_else(|| value.get("utf16Column"))? + .as_i64()?; + Some(json!({ "line": line, "character": character })) +} + +fn lsp_wire_text_edit_from_any(value: &Value) -> Option { + let range = value.get("range")?; + let start = lsp_wire_position_from_any(range.get("start")?)?; + let end = lsp_wire_position_from_any(range.get("end")?)?; + let new_text = value.get("newText")?.as_str()?; + Some(json!({ + "range": { "start": start, "end": end }, + "newText": new_text + })) +} diff --git a/rust/crates/lsp-client/src/client/results.rs b/rust/crates/lsp-client/src/client/results.rs index 87a2357b..e7b56e6c 100644 --- a/rust/crates/lsp-client/src/client/results.rs +++ b/rust/crates/lsp-client/src/client/results.rs @@ -20,6 +20,9 @@ pub(crate) fn lsp_feature_result_for_method( Some("textDocument/hover") => Some(json!({ "hover": parse_hover(result) })), + Some("textDocument/signatureHelp") => Some(json!({ + "signatureHelp": parse_signature_help(result) + })), Some("textDocument/rename") => Some(json!({ "changes": parse_workspace_edit(result) })), @@ -35,6 +38,11 @@ pub(crate) fn lsp_feature_result_for_method( Some("textDocument/inlayHint") => Some(json!({ "hints": parse_inlay_hints(result) })), + Some("inlayHint/resolve") => parse_inlay_hint(result).map(|hint| { + json!({ + "hint": hint + }) + }), Some("textDocument/foldingRange") => Some(json!({ "ranges": parse_folding_ranges(result) })), @@ -202,39 +210,338 @@ fn hover_contents(value: &Value) -> Option<(String, bool)> { } } +const MAX_SIGNATURES: usize = 32; +const MAX_PARAMETERS: usize = 128; +const MAX_SIGNATURE_LABEL_CHARS: usize = 512; +const MAX_SIGNATURE_DOC_BYTES: usize = 2048; + +const MAX_INLAY_HINTS_PER_VIEWPORT: usize = 512; +const MAX_INLAY_HINTS_PER_LINE: usize = 8; +const MAX_INLAY_HINT_LABEL_CHARS: usize = 48; +const MAX_INLAY_HINT_TOOLTIP_BYTES: usize = 2048; + +const MAX_CODE_ACTIONS: usize = 256; +const MAX_CODE_ACTION_TITLE_BYTES: usize = 512; +const MAX_APPLY_EDIT_LABEL_BYTES: usize = 256; + +fn parse_signature_help(result: &Value) -> Option { + if result.is_null() { + return None; + } + let raw_signatures = result.get("signatures")?.as_array()?; + if raw_signatures.is_empty() { + return None; + } + let fallback_active_param = result.get("activeParameter").and_then(Value::as_u64); + let mut signatures = Vec::with_capacity(raw_signatures.len().min(MAX_SIGNATURES)); + for signature in raw_signatures.iter().take(MAX_SIGNATURES) { + if let Some(parsed) = parse_signature_information(signature, fallback_active_param) { + signatures.push(parsed); + } + } + if signatures.is_empty() { + return None; + } + let requested_active = result + .get("activeSignature") + .and_then(Value::as_u64) + .unwrap_or(0) as usize; + let active_signature = requested_active.min(signatures.len() - 1); + let active_parameter = signatures[active_signature] + .get("activeParameter") + .cloned() + .unwrap_or(Value::Null); + Some(json!({ + "signatures": signatures, + "activeSignature": active_signature, + "activeParameter": active_parameter + })) +} + +#[derive(Clone, Copy)] +struct LabelBoundary { + raw_u16: usize, + norm_byte: usize, + norm_u16: usize, +} + +fn normalize_single_line_with_boundaries( + raw: &str, + max_chars: usize, +) -> (String, Vec) { + let mut normalized = String::new(); + let mut boundaries = Vec::new(); + let mut chars = raw.char_indices().peekable(); + let mut raw_u16 = 0_usize; + let mut norm_u16 = 0_usize; + let mut emitted_chars = 0_usize; + let mut truncated = false; + let char_limit = if raw.chars().count() > max_chars { + truncated = true; + max_chars.saturating_sub(1) + } else { + max_chars + }; + + while let Some((_, ch)) = chars.next() { + boundaries.push(LabelBoundary { + raw_u16, + norm_byte: normalized.len(), + norm_u16, + }); + if ch == '\r' && chars.peek().is_some_and(|(_, next)| *next == '\n') { + raw_u16 += 1; + let _ = chars.next(); + boundaries.push(LabelBoundary { + raw_u16, + norm_byte: normalized.len(), + norm_u16, + }); + raw_u16 += 1; + if emitted_chars < char_limit { + normalized.push(' '); + norm_u16 += 1; + emitted_chars += 1; + } + continue; + } + raw_u16 += ch.len_utf16(); + let out_ch = if ch == '\r' || ch == '\n' || ch == '\t' || ch.is_control() { + ' ' + } else { + ch + }; + if emitted_chars < char_limit { + normalized.push(out_ch); + norm_u16 += out_ch.len_utf16(); + emitted_chars += 1; + } + } + boundaries.push(LabelBoundary { + raw_u16, + norm_byte: normalized.len(), + norm_u16, + }); + if truncated { + normalized.push('…'); + } + (normalized, boundaries) +} + +fn parse_signature_information( + signature: &Value, + fallback_active_param: Option, +) -> Option { + let raw_label = signature.get("label")?.as_str()?; + let (label, boundaries) = + normalize_single_line_with_boundaries(raw_label, MAX_SIGNATURE_LABEL_CHARS); + if label.trim().is_empty() { + return None; + } + let (documentation, is_markdown) = + bounded_documentation(signature.get("documentation"), MAX_SIGNATURE_DOC_BYTES); + let mut parameters = Vec::new(); + let mut search_from_byte = 0_usize; + if let Some(raw_params) = signature.get("parameters").and_then(Value::as_array) { + for param in raw_params.iter().take(MAX_PARAMETERS) { + if let Some(parsed) = + parse_parameter_information(param, &label, &boundaries, &mut search_from_byte) + { + parameters.push(parsed); + } + } + } + let active_parameter = + if parameters.is_empty() || signature.get("activeParameter").is_some_and(Value::is_null) { + None + } else { + let raw_active = signature + .get("activeParameter") + .and_then(Value::as_u64) + .or(fallback_active_param) + .unwrap_or(0) as usize; + Some(raw_active.min(parameters.len() - 1)) + }; + Some(json!({ + "label": label, + "documentation": documentation, + "isMarkdown": is_markdown, + "parameters": parameters, + "activeParameter": active_parameter + })) +} + +fn parse_parameter_information( + param: &Value, + signature_label: &str, + boundaries: &[LabelBoundary], + search_from_byte: &mut usize, +) -> Option { + let label_field = param.get("label")?; + let (param_label, offsets) = match label_field { + Value::Array(pair) if pair.len() == 2 => { + let start_u16 = pair[0].as_u64()? as usize; + let end_u16 = pair[1].as_u64()? as usize; + if start_u16 > end_u16 { + return None; + } + let start_idx = boundaries + .binary_search_by_key(&start_u16, |b| b.raw_u16) + .ok()?; + let end_idx = boundaries + .binary_search_by_key(&end_u16, |b| b.raw_u16) + .ok()?; + let start_b = boundaries[start_idx].norm_byte; + let end_b = boundaries[end_idx].norm_byte; + let start_norm_u16 = boundaries[start_idx].norm_u16; + let end_norm_u16 = boundaries[end_idx].norm_u16; + if start_b < end_b && end_b <= signature_label.len() { + *search_from_byte = end_b; + ( + signature_label[start_b..end_b].to_string(), + Some((start_norm_u16, end_norm_u16, start_b, end_b)), + ) + } else { + (String::new(), None) + } + } + Value::String(raw_sub) => { + let (norm_sub, _) = normalize_single_line_with_boundaries(raw_sub, 128); + if norm_sub.is_empty() { + return None; + } + let found_byte = signature_label + .get(*search_from_byte..) + .and_then(|tail| tail.find(&norm_sub).map(|rel| *search_from_byte + rel)) + .or_else(|| signature_label.find(&norm_sub)); + if let Some(start_b) = found_byte { + let end_b = start_b + norm_sub.len(); + *search_from_byte = end_b; + let start_u16 = signature_label[..start_b].encode_utf16().count(); + let end_u16 = start_u16 + signature_label[start_b..end_b].encode_utf16().count(); + (norm_sub, Some((start_u16, end_u16, start_b, end_b))) + } else { + (norm_sub, None) + } + } + _ => return None, + }; + let (documentation, is_markdown) = + bounded_documentation(param.get("documentation"), MAX_SIGNATURE_DOC_BYTES); + let (utf16_start, utf16_end, byte_start, byte_end) = match offsets { + Some((us, ue, bs, be)) => (Some(us), Some(ue), Some(bs), Some(be)), + None => (None, None, None, None), + }; + Some(json!({ + "label": param_label, + "utf16Start": utf16_start, + "utf16End": utf16_end, + "byteStart": byte_start, + "byteEnd": byte_end, + "documentation": documentation, + "isMarkdown": is_markdown + })) +} + +fn bounded_documentation(value: Option<&Value>, max_bytes: usize) -> (Option, bool) { + let Some(value) = value else { + return (None, false); + }; + let (raw, is_markdown) = match value { + Value::String(text) => (text.as_str(), false), + Value::Object(object) => { + let Some(text) = object.get("value").and_then(Value::as_str) else { + return (None, false); + }; + let is_markdown = object + .get("kind") + .and_then(Value::as_str) + .is_some_and(|kind| kind == "markdown"); + (text, is_markdown) + } + _ => return (None, false), + }; + let trimmed = raw.trim(); + if trimmed.is_empty() { + return (None, false); + } + (Some(truncate_utf8_bytes(trimmed, max_bytes)), is_markdown) +} + +fn truncate_utf8_bytes(text: &str, max_bytes: usize) -> String { + if text.len() <= max_bytes { + return text.to_string(); + } + let ellipsis = '…'; + let budget = max_bytes.saturating_sub(ellipsis.len_utf8()); + let mut end = 0; + for (idx, ch) in text.char_indices() { + if idx + ch.len_utf8() > budget { + break; + } + end = idx + ch.len_utf8(); + } + let mut out = text[..end].to_string(); + out.push(ellipsis); + out +} + fn parse_inlay_hints(result: &Value) -> Vec { - result - .as_array() - .map(|values| { - values - .iter() - .filter_map(|hint| { - Some(LspInlayHintResponse { - position: parse_lsp_position(hint.get("position")?)?, - label: parse_inlay_hint_label(hint.get("label")?)?, - kind: hint.get("kind").and_then(Value::as_i64), - tooltip: completion_documentation(hint.get("tooltip")), - padding_left: hint - .get("paddingLeft") - .and_then(Value::as_bool) - .unwrap_or(false), - padding_right: hint - .get("paddingRight") - .and_then(Value::as_bool) - .unwrap_or(false), - text_edits: hint - .get("textEdits") - .and_then(Value::as_array) - .map(|edits| { - edits.iter().filter_map(parse_lsp_text_edit_value).collect() - }) - .unwrap_or_default(), - data: hint.get("data").cloned(), - }) - }) - .collect() - }) - .unwrap_or_default() + let Some(values) = result.as_array() else { + return Vec::new(); + }; + let mut hints: Vec = values.iter().filter_map(parse_inlay_hint).collect(); + hints.sort_by_key(|hint| (hint.position.line, hint.position.utf16_column)); + let mut culled = Vec::with_capacity(hints.len().min(MAX_INLAY_HINTS_PER_VIEWPORT)); + let mut current_line: Option = None; + let mut line_count = 0_usize; + for hint in hints { + if current_line == Some(hint.position.line) { + if line_count >= MAX_INLAY_HINTS_PER_LINE { + continue; + } + line_count += 1; + } else { + current_line = Some(hint.position.line); + line_count = 1; + } + culled.push(hint); + if culled.len() >= MAX_INLAY_HINTS_PER_VIEWPORT { + break; + } + } + culled +} + +fn parse_inlay_hint(hint: &Value) -> Option { + let raw_label = parse_inlay_hint_label(hint.get("label")?)?; + let (label, _) = normalize_single_line_with_boundaries(&raw_label, MAX_INLAY_HINT_LABEL_CHARS); + if label.trim().is_empty() { + return None; + } + let tooltip = completion_documentation(hint.get("tooltip")) + .map(|text| truncate_utf8_bytes(text.trim(), MAX_INLAY_HINT_TOOLTIP_BYTES)) + .filter(|text| !text.is_empty()); + Some(LspInlayHintResponse { + position: parse_lsp_position(hint.get("position")?)?, + label, + kind: hint.get("kind").and_then(Value::as_i64), + tooltip, + padding_left: hint + .get("paddingLeft") + .and_then(Value::as_bool) + .unwrap_or(false), + padding_right: hint + .get("paddingRight") + .and_then(Value::as_bool) + .unwrap_or(false), + text_edits: hint + .get("textEdits") + .and_then(Value::as_array) + .map(|edits| edits.iter().filter_map(parse_lsp_text_edit_value).collect()) + .unwrap_or_default(), + data: hint.get("data").filter(|value| !value.is_null()).cloned(), + }) } fn parse_inlay_hint_label(value: &Value) -> Option { @@ -448,11 +755,61 @@ fn parse_code_actions(result: &Value) -> Vec { let Some(values) = result.as_array() else { return Vec::new(); }; - values.iter().filter_map(parse_code_action).collect() + let mut actions: Vec = values.iter().filter_map(parse_code_action).collect(); + actions.sort_by_key(|action| { + let preferred = action + .get("isPreferred") + .and_then(Value::as_bool) + .unwrap_or(false); + let group_rank = match action.get("group").and_then(Value::as_str) { + Some("quickfix") => 0_u8, + Some("refactor") => 1_u8, + Some("source") => 2_u8, + _ => 3_u8, + }; + (!preferred, group_rank) + }); + actions.truncate(MAX_CODE_ACTIONS); + actions +} + +fn code_action_group(kind: Option<&str>) -> &'static str { + let Some(kind) = kind else { + return "other"; + }; + if kind == "quickfix" || kind.starts_with("quickfix.") { + "quickfix" + } else if kind == "refactor" || kind.starts_with("refactor.") { + "refactor" + } else if kind == "source" || kind.starts_with("source.") { + "source" + } else { + "other" + } } fn parse_code_action(action: &Value) -> Option { - let title = action.get("title").and_then(Value::as_str)?; + if action.get("disabled").is_some_and(|value| !value.is_null()) { + return None; + } + let raw_title = action.get("title").and_then(Value::as_str)?; + let single_line_title: String = raw_title + .chars() + .map(|ch| { + if ch == '\r' || ch == '\n' || ch == '\t' || ch.is_control() { + ' ' + } else { + ch + } + }) + .collect(); + let trimmed_title = single_line_title.trim(); + if trimmed_title.is_empty() { + return None; + } + let title = truncate_utf8_bytes(trimmed_title, MAX_CODE_ACTION_TITLE_BYTES); + let kind = action.get("kind").and_then(Value::as_str); + let group = code_action_group(kind); let command = if action.get("command").and_then(Value::as_str).is_some() { parse_lsp_command(action) } else { @@ -460,12 +817,13 @@ fn parse_code_action(action: &Value) -> Option { }; Some(json!({ "title": title, - "kind": action.get("kind").and_then(Value::as_str), + "kind": kind, + "group": group, "isPreferred": action .get("isPreferred") .and_then(Value::as_bool) .unwrap_or(false), - "edit": action.get("edit").map(|edit| json!({ + "edit": action.get("edit").filter(|edit| !edit.is_null()).map(|edit| json!({ "changes": parse_workspace_edit(edit) })), "command": command, @@ -485,6 +843,110 @@ fn parse_lsp_command(value: &Value) -> Option { })) } +/// Validates and normalizes server-initiated `workspace/applyEdit` parameters. +/// +/// Outer `Err` rejects malformed JSON-RPC parameters (`-32602`). Inner `Err` +/// reports a valid `ApplyWorkspaceEditParams` that carries unsupported resource +/// operations or non-file URIs so the client replies `{ applied: false, failureReason }`. +pub(crate) fn parse_workspace_apply_edit( + params: Option<&Value>, +) -> Result, &'static str> { + let params = params + .and_then(Value::as_object) + .ok_or("Invalid workspace/applyEdit parameters")?; + let edit = params + .get("edit") + .and_then(Value::as_object) + .ok_or("workspace/applyEdit requires an edit object")?; + let label = params + .get("label") + .and_then(Value::as_str) + .map(str::trim) + .filter(|label| !label.is_empty()) + .map(|label| truncate_utf8_bytes(label, MAX_APPLY_EDIT_LABEL_BYTES)); + + let mut changes: serde_json::Map = serde_json::Map::new(); + if let Some(entries) = edit.get("changes") { + let Some(entries) = entries.as_object() else { + return Ok(Err("Workspace edit changes must be an object.")); + }; + for (uri, edits) in entries { + let Some(path) = file_path_for_uri(uri) else { + return Ok(Err("Workspace edit targets a non-file URI.")); + }; + let Some(raw_edits) = edits.as_array() else { + return Ok(Err("Workspace text edits must be an array.")); + }; + let mut parsed = Vec::with_capacity(raw_edits.len()); + for item in raw_edits { + if item.get("snippet").is_some() { + return Ok(Err("Snippet workspace edits are not supported.")); + } + let Some(edit_value) = parse_lsp_text_edit_value(item) else { + return Ok(Err("Workspace text edit is malformed.")); + }; + parsed.push(edit_value); + } + append_file_edits(&mut changes, path, parsed); + } + } + if let Some(document_changes) = edit.get("documentChanges") { + let Some(document_changes) = document_changes.as_array() else { + return Ok(Err("Workspace documentChanges must be an array.")); + }; + for change in document_changes { + let Some(change_obj) = change.as_object() else { + return Ok(Err("Workspace documentChange entry must be an object.")); + }; + if change_obj.get("kind").is_some() { + return Ok(Err( + "Resource create, rename, and delete operations are not supported.", + )); + } + let Some(uri) = change_obj + .get("textDocument") + .and_then(|document| document.get("uri")) + .and_then(Value::as_str) + else { + return Ok(Err("Workspace documentChange requires a textDocument URI.")); + }; + let Some(path) = file_path_for_uri(uri) else { + return Ok(Err("Workspace edit targets a non-file URI.")); + }; + let Some(raw_edits) = change_obj.get("edits").and_then(Value::as_array) else { + return Ok(Err("Workspace documentChange requires an edits array.")); + }; + let mut parsed = Vec::with_capacity(raw_edits.len()); + for item in raw_edits { + if item.get("snippet").is_some() { + return Ok(Err("Snippet workspace edits are not supported.")); + } + let Some(edit_value) = parse_lsp_text_edit_value(item) else { + return Ok(Err("Workspace text edit is malformed.")); + }; + parsed.push(edit_value); + } + append_file_edits(&mut changes, path, parsed); + } + } + Ok(Ok(json!({ + "label": label, + "changes": changes + }))) +} + +fn append_file_edits( + changes: &mut serde_json::Map, + path: String, + mut edits: Vec, +) { + if let Some(Value::Array(existing)) = changes.get_mut(&path) { + existing.append(&mut edits); + } else { + changes.insert(path, Value::Array(edits)); + } +} + fn parse_workspace_edit(result: &Value) -> serde_json::Map { let mut changes = serde_json::Map::new(); if let Some(entries) = result.get("changes").and_then(Value::as_object) { @@ -498,11 +960,14 @@ fn parse_workspace_edit(result: &Value) -> serde_json::Map { .collect::>() }) .unwrap_or_default(); - changes.insert(file_path_from_uri(uri), json!(parsed)); + append_file_edits(&mut changes, file_path_from_uri(uri), parsed); } } if let Some(document_changes) = result.get("documentChanges").and_then(Value::as_array) { for change in document_changes { + if change.get("kind").is_some() { + continue; + } let Some(uri) = change .get("textDocument") .and_then(|document| document.get("uri")) @@ -520,7 +985,7 @@ fn parse_workspace_edit(result: &Value) -> serde_json::Map { .collect::>() }) .unwrap_or_default(); - changes.insert(file_path_from_uri(uri), json!(parsed)); + append_file_edits(&mut changes, file_path_from_uri(uri), parsed); } } changes diff --git a/rust/crates/lsp-client/src/client/server_messages.rs b/rust/crates/lsp-client/src/client/server_messages.rs index 0a5073d2..354d12a9 100644 --- a/rust/crates/lsp-client/src/client/server_messages.rs +++ b/rust/crates/lsp-client/src/client/server_messages.rs @@ -197,6 +197,61 @@ pub fn client_apply_server_message_for_plugin( error: None, }); } + "workspace/inlayHint/refresh" => { + if let Some(id) = request_id { + responses.push(json_rpc_result(id, Value::Null)?); + } + events.push(LspClientEvent { + kind: "inlayHintsRefresh".to_string(), + request_id: None, + method: Some(method.to_string()), + uri: None, + version: None, + diagnostics: None, + result: None, + error: None, + }); + } + "workspace/applyEdit" if request_id.is_some() => { + let id = request_id.expect("guarded above"); + if state.shutdown_requested { + responses.push(json_rpc_result( + id, + json!({ + "applied": false, + "failureReason": "Language server session is shutting down." + }), + )?); + } else { + match parse_workspace_apply_edit(message.get("params")) { + Err(invalid) => { + responses.push(json_rpc_error(id, -32602, invalid)?); + } + Ok(Err(reason)) => { + responses.push(json_rpc_result( + id, + json!({ + "applied": false, + "failureReason": reason + }), + )?); + } + Ok(Ok(mut payload)) => { + payload["id"] = id.clone(); + events.push(LspClientEvent { + kind: "workspaceApplyEdit".to_string(), + request_id: None, + method: Some(method.to_string()), + uri: None, + version: None, + diagnostics: None, + result: Some(payload), + error: None, + }); + } + } + } + } "workspace/configuration" => { if let Some(id) = request_id { let item_count = message @@ -446,6 +501,22 @@ pub fn client_apply_server_message_for_plugin( .completion_providers .insert(String::new(), options.clone()); } + match result + .get("capabilities") + .and_then(|c| c.get("signatureHelpProvider")) + { + Some(Value::Bool(true)) => { + state + .signature_help_providers + .insert(String::new(), json!({})); + } + Some(options) if options.is_object() => { + state + .signature_help_providers + .insert(String::new(), options.clone()); + } + _ => {} + } if let Some(options) = result .get("capabilities") .and_then(|c| c.get("semanticTokensProvider")) @@ -466,6 +537,7 @@ pub fn client_apply_server_message_for_plugin( state.server_capabilities.clear(); state.semantic_token_providers.clear(); state.completion_providers.clear(); + state.signature_help_providers.clear(); state.text_document_sync = LspTextDocumentSyncKind::Full; state.open_documents.clear(); state.diagnostics.clear(); diff --git a/rust/crates/lsp-client/src/client/validation.rs b/rust/crates/lsp-client/src/client/validation.rs index 0a073120..1c1b8215 100644 --- a/rust/crates/lsp-client/src/client/validation.rs +++ b/rust/crates/lsp-client/src/client/validation.rs @@ -77,6 +77,7 @@ pub(crate) fn validate_lsp_method(method: &str) -> Result<(), CoreError> { match method { "textDocument/completion" | "textDocument/hover" + | "textDocument/signatureHelp" | "textDocument/definition" | "textDocument/declaration" | "textDocument/typeDefinition" @@ -87,6 +88,7 @@ pub(crate) fn validate_lsp_method(method: &str) -> Result<(), CoreError> { | "textDocument/rangeFormatting" | "textDocument/documentSymbol" | "textDocument/inlayHint" + | "inlayHint/resolve" | "textDocument/semanticTokens/full" | "textDocument/foldingRange" | "textDocument/documentLink" diff --git a/rust/crates/lsp-client/src/tests.rs b/rust/crates/lsp-client/src/tests.rs index b437a9d2..b99a1ff5 100644 --- a/rust/crates/lsp-client/src/tests.rs +++ b/rust/crates/lsp-client/src/tests.rs @@ -269,6 +269,7 @@ fn client_core_tracks_documents_and_feature_requests() { command: None, formatting_options: None, include_declaration: None, + ..Default::default() }) .unwrap(); assert_eq!( @@ -310,6 +311,7 @@ fn client_references_request_passes_include_declaration() { command: None, formatting_options: None, include_declaration, + ..Default::default() }) .unwrap(); let message: Value = serde_json::from_str(&requested.messages[0]).unwrap(); @@ -734,6 +736,7 @@ fn client_core_preserves_class_completion_namespace_and_import_edits() { command: None, formatting_options: None, include_declaration: None, + ..Default::default() }) .unwrap(); let completed = client_apply_server_message(ClientApplyServerMessageRequest { @@ -784,6 +787,7 @@ fn client_core_preserves_class_completion_namespace_and_import_edits() { command: None, formatting_options: None, include_declaration: None, + ..Default::default() }) .unwrap(); let resolved = client_apply_server_message(ClientApplyServerMessageRequest { @@ -1117,6 +1121,7 @@ fn client_core_shapes_feature_responses_for_host_models() { command: None, formatting_options: None, include_declaration: None, + ..Default::default() }) .unwrap(); let completed = client_apply_server_message(ClientApplyServerMessageRequest { @@ -1171,6 +1176,7 @@ fn client_core_shapes_feature_responses_for_host_models() { command: None, formatting_options: None, include_declaration: None, + ..Default::default() }) .unwrap(); let renamed = client_apply_server_message(ClientApplyServerMessageRequest { @@ -1214,6 +1220,7 @@ fn client_core_shapes_feature_responses_for_host_models() { command: None, formatting_options: None, include_declaration: None, + ..Default::default() }) .unwrap(); let formatted = client_apply_server_message(ClientApplyServerMessageRequest { @@ -1294,6 +1301,7 @@ fn client_core_shapes_feature_responses_for_host_models() { command: None, formatting_options: None, include_declaration: None, + ..Default::default() }) .unwrap(); let code_action_request: Value = serde_json::from_str(&code_actions.messages[0]).unwrap(); @@ -1378,6 +1386,7 @@ fn client_core_shapes_feature_responses_for_host_models() { command: None, formatting_options: None, include_declaration: None, + ..Default::default() }) .unwrap(); let code_action_resolve_request: Value = @@ -1446,6 +1455,7 @@ fn client_core_shapes_feature_responses_for_host_models() { command: None, formatting_options: None, include_declaration: None, + ..Default::default() }) .unwrap(); let completion_resolve_request: Value = @@ -1500,6 +1510,7 @@ fn client_core_shapes_feature_responses_for_host_models() { })), formatting_options: None, include_declaration: None, + ..Default::default() }) .unwrap(); let execute_request: Value = serde_json::from_str(&execute_command.messages[0]).unwrap(); @@ -1547,6 +1558,7 @@ fn client_requests_and_normalizes_document_links() { command: None, formatting_options: None, include_declaration: None, + ..Default::default() }) .unwrap(); let request_json: Value = serde_json::from_str(&request.messages[0]).unwrap(); @@ -1610,6 +1622,7 @@ fn client_requests_and_normalizes_workspace_symbols_without_a_document() { command: None, formatting_options: None, include_declaration: None, + ..Default::default() }) .unwrap(); let request_json: Value = serde_json::from_str(&request.messages[0]).unwrap(); @@ -1696,6 +1709,7 @@ fn client_core_requests_and_shapes_inlay_hints_folding_ranges_and_code_lenses() command: None, formatting_options: None, include_declaration: None, + ..Default::default() }) .unwrap(); let request_json: Value = serde_json::from_str(&inlay_request.messages[0]).unwrap(); @@ -1751,6 +1765,7 @@ fn client_core_requests_and_shapes_inlay_hints_folding_ranges_and_code_lenses() command: None, formatting_options: None, include_declaration: None, + ..Default::default() }) .unwrap(); let request_json: Value = serde_json::from_str(&folding_request.messages[0]).unwrap(); @@ -1796,6 +1811,7 @@ fn client_core_requests_and_shapes_inlay_hints_folding_ranges_and_code_lenses() command: None, formatting_options: None, include_declaration: None, + ..Default::default() }) .unwrap(); let code_lens_response = client_apply_server_message(ClientApplyServerMessageRequest { @@ -1854,6 +1870,7 @@ fn navigation_locations_preserve_uris_without_fabricating_virtual_file_paths() { command: None, formatting_options: None, include_declaration: None, + ..Default::default() }) .unwrap(); let response = client_apply_server_message(ClientApplyServerMessageRequest { @@ -2287,3 +2304,313 @@ fn client_completion_rejects_invalid_trigger_context() { )); } } + +#[test] +fn client_editor_actions_signature_help_inlay_hints_and_apply_edit_match_fixture() { + let fixture: Value = serde_json::from_str(include_str!( + "../../../fixtures/lsp/editor-actions-hints-v1.json" + )) + .unwrap(); + let uri = fixture["uri"].as_str().unwrap(); + + let initialized = client_initialize(ClientInitializeRequest { + state: LspClientState::default(), + root_uri: "file:///workspace".into(), + process_id: None, + initialization_options: None, + }) + .unwrap(); + let init_req: Value = serde_json::from_str(&initialized.messages[0]).unwrap(); + assert_eq!( + init_req["params"]["capabilities"]["textDocument"]["signatureHelp"]["signatureInformation"] + ["parameterInformation"]["labelOffsetSupport"], + json!(true) + ); + assert_eq!( + init_req["params"]["capabilities"]["textDocument"]["signatureHelp"]["contextSupport"], + json!(true) + ); + assert_eq!( + init_req["params"]["capabilities"]["workspace"]["inlayHint"]["refreshSupport"], + json!(true) + ); + + let ready = client_apply_server_message(ClientApplyServerMessageRequest { + state: initialized.state, + message: json!({ + "jsonrpc": "2.0", + "id": init_req["id"], + "result": { + "capabilities": { + "codeActionProvider": { "resolveProvider": true }, + "signatureHelpProvider": { + "triggerCharacters": ["(", ","], + "retriggerCharacters": [","] + }, + "inlayHintProvider": { "resolveProvider": true } + } + } + }) + .to_string(), + }) + .unwrap(); + assert!(ready + .state + .server_capabilities + .contains(&"signatureHelp".to_string())); + assert!(ready + .state + .server_capabilities + .contains(&"inlayHintResolve".to_string())); + assert_eq!( + signature_help_options(&ready.state), + Some(json!({ + "triggerCharacters": ["(", ","], + "retriggerCharacters": [","] + })) + ); + + let opened = client_open_document(ClientOpenDocumentRequest { + state: ready.state, + uri: uri.to_string(), + language_id: "rust".into(), + text: "fn main() {}\n".into(), + }) + .unwrap(); + + // 1. Code actions: context forwarding, disabled filtering, deterministic group sort, and resolve. + let ca_req = client_feature_request(ClientFeatureRequest { + state: opened.state, + uri: uri.to_string(), + method: "textDocument/codeAction".into(), + range: Some(LspRange { + start: LspPosition { + line: 0, + utf16_column: 0, + }, + end: LspPosition { + line: 0, + utf16_column: 5, + }, + }), + code_action_context: Some(fixture["codeActions"]["context"].clone()), + ..Default::default() + }) + .unwrap(); + let ca_wire: Value = serde_json::from_str(&ca_req.messages[0]).unwrap(); + assert_eq!( + ca_wire["params"]["context"]["only"], + json!(["quickfix", "refactor"]) + ); + assert_eq!(ca_wire["params"]["context"]["triggerKind"], json!(1)); + + let ca_done = client_apply_server_message(ClientApplyServerMessageRequest { + state: ca_req.state, + message: json!({ + "jsonrpc": "2.0", + "id": ca_wire["id"], + "result": fixture["codeActions"]["serverResult"] + }) + .to_string(), + }) + .unwrap(); + let actions = ca_done.events[0].result.as_ref().unwrap()["actions"] + .as_array() + .unwrap(); + let actual_summary: Vec = actions + .iter() + .map(|item| { + json!({ + "title": item["title"], + "group": item["group"], + "isPreferred": item["isPreferred"] + }) + }) + .collect(); + assert_eq!( + json!(actual_summary), + fixture["codeActions"]["expectedTitlesAndGroups"] + ); + + let resolve_ca_req = client_feature_request(ClientFeatureRequest { + state: ca_done.state, + uri: uri.to_string(), + method: "codeAction/resolve".into(), + code_action: Some(actions[2].clone()), + ..Default::default() + }) + .unwrap(); + let resolve_ca_wire: Value = serde_json::from_str(&resolve_ca_req.messages[0]).unwrap(); + assert!(resolve_ca_wire["params"].get("group").is_none()); + assert_eq!( + resolve_ca_wire["params"]["data"], + json!({ "id": "extract-1" }) + ); + + // 2. Signature help: trigger context, string & UTF-16 [start, end] offsets, clamping, and retrigger round-trip. + let sig_req = client_feature_request(ClientFeatureRequest { + state: resolve_ca_req.state, + uri: uri.to_string(), + method: "textDocument/signatureHelp".into(), + position: Some(LspPosition { + line: 0, + utf16_column: 8, + }), + signature_help_context: Some(fixture["signatureHelp"]["triggerContext"].clone()), + ..Default::default() + }) + .unwrap(); + let sig_wire: Value = serde_json::from_str(&sig_req.messages[0]).unwrap(); + assert_eq!(sig_wire["params"]["context"]["triggerKind"], json!(2)); + assert_eq!( + sig_wire["params"]["context"]["triggerCharacter"], + json!("(") + ); + + let sig_done = client_apply_server_message(ClientApplyServerMessageRequest { + state: sig_req.state, + message: json!({ + "jsonrpc": "2.0", + "id": sig_wire["id"], + "result": fixture["signatureHelp"]["serverResult"] + }) + .to_string(), + }) + .unwrap(); + let sig_value = &sig_done.events[0].result.as_ref().unwrap()["signatureHelp"]; + assert_eq!(sig_value, &fixture["signatureHelp"]["expectedResult"]); + + let retrigger_req = client_feature_request(ClientFeatureRequest { + state: sig_done.state, + uri: uri.to_string(), + method: "textDocument/signatureHelp".into(), + position: Some(LspPosition { + line: 0, + utf16_column: 9, + }), + signature_help_context: Some(json!({ + "triggerKind": 3, + "isRetrigger": true, + "activeSignatureHelp": sig_value + })), + ..Default::default() + }) + .unwrap(); + let retrigger_wire: Value = serde_json::from_str(&retrigger_req.messages[0]).unwrap(); + assert_eq!( + retrigger_wire["params"]["context"]["activeSignatureHelp"]["signatures"][1]["parameters"] + [0]["label"], + json!([3, 14]) + ); + + // 3. Inlay hints: sorting, per-line 8-hint culling, 48-char truncation, resolve, and refresh. + let hints_req = client_feature_request(ClientFeatureRequest { + state: retrigger_req.state, + uri: uri.to_string(), + method: "textDocument/inlayHint".into(), + range: Some(LspRange { + start: LspPosition { + line: 0, + utf16_column: 0, + }, + end: LspPosition { + line: 10, + utf16_column: 0, + }, + }), + ..Default::default() + }) + .unwrap(); + let hints_wire: Value = serde_json::from_str(&hints_req.messages[0]).unwrap(); + let hints_done = client_apply_server_message(ClientApplyServerMessageRequest { + state: hints_req.state, + message: json!({ + "jsonrpc": "2.0", + "id": hints_wire["id"], + "result": fixture["inlayHints"]["serverResult"] + }) + .to_string(), + }) + .unwrap(); + let hints = hints_done.events[0].result.as_ref().unwrap()["hints"] + .as_array() + .unwrap(); + assert_eq!( + hints.len(), + fixture["inlayHints"]["expectedCount"].as_u64().unwrap() as usize + ); + assert_eq!( + hints[0]["label"], + fixture["inlayHints"]["expectedFirstLabel"] + ); + assert_eq!( + hints[8]["label"], + fixture["inlayHints"]["expectedTruncatedEighthOnLine2"] + ); + + let resolve_hint_req = client_feature_request(ClientFeatureRequest { + state: hints_done.state, + uri: uri.to_string(), + method: "inlayHint/resolve".into(), + inlay_hint: Some(hints[0].clone()), + ..Default::default() + }) + .unwrap(); + let resolve_hint_wire: Value = serde_json::from_str(&resolve_hint_req.messages[0]).unwrap(); + assert_eq!( + resolve_hint_wire["params"]["position"]["character"], + json!(8) + ); + + let refreshed = client_apply_server_message(ClientApplyServerMessageRequest { + state: resolve_hint_req.state, + message: json!({ + "jsonrpc": "2.0", + "id": "srv-refresh-1", + "method": "workspace/inlayHint/refresh" + }) + .to_string(), + }) + .unwrap(); + assert_eq!(refreshed.events[0].kind, "inlayHintsRefresh"); + let refresh_reply: Value = serde_json::from_str(&refreshed.messages[0]).unwrap(); + assert_eq!(refresh_reply["result"], Value::Null); + + // 4. Server-initiated workspace/applyEdit: accepted vs resource operation rejection. + let accepted_edit = client_apply_server_message(ClientApplyServerMessageRequest { + state: refreshed.state, + message: json!({ + "jsonrpc": "2.0", + "id": "srv-edit-1", + "method": "workspace/applyEdit", + "params": fixture["workspaceApplyEdit"]["acceptedRequest"] + }) + .to_string(), + }) + .unwrap(); + assert!(accepted_edit.messages.is_empty()); + assert_eq!(accepted_edit.events[0].kind, "workspaceApplyEdit"); + assert_eq!( + accepted_edit.events[0].result.as_ref().unwrap()["label"], + json!("Apply quick fix") + ); + + let rejected_edit = client_apply_server_message(ClientApplyServerMessageRequest { + state: accepted_edit.state, + message: json!({ + "jsonrpc": "2.0", + "id": "srv-edit-2", + "method": "workspace/applyEdit", + "params": fixture["workspaceApplyEdit"]["rejectedResourceRequest"] + }) + .to_string(), + }) + .unwrap(); + assert!(rejected_edit.events.is_empty()); + let reject_reply: Value = serde_json::from_str(&rejected_edit.messages[0]).unwrap(); + assert_eq!(reject_reply["result"]["applied"], json!(false)); + assert_eq!( + reject_reply["result"]["failureReason"], + fixture["workspaceApplyEdit"]["expectedRejectedFailureReason"] + ); +} diff --git a/rust/crates/lsp-client/src/types.rs b/rust/crates/lsp-client/src/types.rs index 186d00eb..db61a5d1 100644 --- a/rust/crates/lsp-client/src/types.rs +++ b/rust/crates/lsp-client/src/types.rs @@ -120,6 +120,10 @@ pub struct LspClientState { /// trigger and commit characters are read from them. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub completion_providers: BTreeMap, + /// `signatureHelpProvider` options by registration id: the static + /// capability under the empty id, dynamic registrations under their own ids. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub signature_help_providers: BTreeMap, /// Full semantic-token registrations, including the server-owned legends. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub semantic_token_providers: BTreeMap, @@ -189,6 +193,7 @@ impl Default for LspClientState { shutdown_requested: false, server_capabilities: Vec::new(), completion_providers: BTreeMap::new(), + signature_help_providers: BTreeMap::new(), semantic_token_providers: BTreeMap::new(), text_document_sync: LspTextDocumentSyncKind::Full, text_document_save_include_text: None, @@ -331,7 +336,7 @@ pub struct ClientShutdownRequest { pub state: LspClientState, } -#[derive(Debug, Clone, Deserialize)] +#[derive(Debug, Clone, Default, Deserialize)] #[serde(rename_all = "camelCase")] /// Generic feature request translated into one provider-neutral JSON-RPC call. pub struct ClientFeatureRequest { @@ -357,15 +362,25 @@ pub struct ClientFeatureRequest { /// Diagnostics in `range`, sent as the `codeAction` context. #[serde(default)] pub diagnostics: Vec, + /// Optional `codeAction` filter and trigger context (`only`, `triggerKind`). + #[serde(default)] + pub code_action_context: Option, /// LSP completion trigger context; validated by the shared request mapper. #[serde(default)] pub completion_context: Option, + /// LSP signature-help trigger context (`triggerKind`, `triggerCharacter`, + /// `isRetrigger`, `activeSignatureHelp`). + #[serde(default)] + pub signature_help_context: Option, /// Item to complete for `completionItem/resolve`. #[serde(default)] pub completion_item: Option, /// Action to complete for `codeAction/resolve`. #[serde(default)] pub code_action: Option, + /// Hint to complete for `inlayHint/resolve`. + #[serde(default)] + pub inlay_hint: Option, /// Command to run for `workspace/executeCommand`. #[serde(default)] pub command: Option, diff --git a/rust/crates/lsp-engine/src/documents.rs b/rust/crates/lsp-engine/src/documents.rs index 5777e6ca..ccfa944b 100644 --- a/rust/crates/lsp-engine/src/documents.rs +++ b/rust/crates/lsp-engine/src/documents.rs @@ -367,7 +367,11 @@ fn is_stale_sensitive_method(method: &str) -> bool { method, "textDocument/completion" | "textDocument/hover" + | "textDocument/signatureHelp" + | "textDocument/codeAction" + | "codeAction/resolve" | "textDocument/inlayHint" + | "inlayHint/resolve" | "textDocument/foldingRange" | "textDocument/codeLens" | "codeLens/resolve" diff --git a/rust/crates/lsp-engine/src/engine.rs b/rust/crates/lsp-engine/src/engine.rs index cfc01a72..11de9eda 100644 --- a/rust/crates/lsp-engine/src/engine.rs +++ b/rust/crates/lsp-engine/src/engine.rs @@ -255,6 +255,8 @@ impl LspEngine { relay_write_deadline: None, host_requests: BTreeMap::new(), next_host_request_id: 1, + apply_edit_requests: BTreeMap::new(), + next_apply_edit_id: 1, detailed_diagnostics: false, requested_diagnostics: false, rejected_plugin_diagnostics: false, diff --git a/rust/crates/lsp-engine/src/events.rs b/rust/crates/lsp-engine/src/events.rs index bf2c7a6a..3c2f5360 100644 --- a/rust/crates/lsp-engine/src/events.rs +++ b/rust/crates/lsp-engine/src/events.rs @@ -111,6 +111,7 @@ pub(crate) fn enqueue_request_completed( error, capabilities: None, completion_options: None, + signature_help_options: None, server_info: None, level: None, message: None, @@ -151,6 +152,7 @@ pub(crate) fn push_diagnostics_event( error: None, capabilities: None, completion_options: None, + signature_help_options: None, server_info: None, level: None, message: None, @@ -188,6 +190,42 @@ pub(crate) fn push_semantic_tokens_refresh_event( error: None, capabilities: None, completion_options: None, + signature_help_options: None, + server_info: None, + level: None, + message: None, + detail: None, + }, + ); +} + +pub(crate) fn push_inlay_hints_refresh_event(session: &RuntimeSession, state: &mut SessionState) { + let sequence = take_sequence(state); + enqueue_runtime_event( + session, + state, + LspRuntimeEvent { + kind: "inlayHintsRefresh".to_string(), + channel: None, + plugin_id: None, + role: None, + event: None, + fields: None, + catalog_level: None, + sequence, + provider_id: session.provider_id.clone(), + session_id: session.id.clone(), + state: None, + operation_id: None, + method: None, + uri: None, + version: None, + diagnostics: None, + result: None, + error: None, + capabilities: None, + completion_options: None, + signature_help_options: None, server_info: None, level: None, message: None, @@ -202,6 +240,7 @@ pub(crate) fn push_features_event( capabilities: Vec, ) { let completion_options = lithe_lsp_client::completion_options(&state.client); + let signature_help_options = lithe_lsp_client::signature_help_options(&state.client); let sequence = take_sequence(state); enqueue_runtime_event( session, @@ -227,6 +266,7 @@ pub(crate) fn push_features_event( error: None, capabilities: Some(capabilities), completion_options, + signature_help_options, server_info: None, level: None, message: None, @@ -265,6 +305,7 @@ pub(crate) fn push_server_info_event( error: None, capabilities: None, completion_options: None, + signature_help_options: None, server_info: Some(info), level: None, message: None, @@ -393,6 +434,7 @@ pub(crate) fn push_classified_log_event( error, capabilities: None, completion_options: None, + signature_help_options: None, server_info: None, level: Some(level.to_string()), message: Some(message.to_string()), @@ -548,11 +590,13 @@ pub(crate) fn clear_runtime_state(session: &RuntimeSession, state: &mut SessionS state.client.shutdown_requested = false; state.client.server_capabilities.clear(); state.client.completion_providers.clear(); + state.client.signature_help_providers.clear(); state.client.open_documents.clear(); state.client.pending_requests.clear(); state.pending.clear(); state.request_by_operation.clear(); state.function_by_operation.clear(); + state.apply_edit_requests.clear(); clear_function_registry(session, state); state.client.vcs_provider = None; state.client.toolchain_providers.clear(); diff --git a/rust/crates/lsp-engine/src/function_calls.rs b/rust/crates/lsp-engine/src/function_calls.rs index 28971d3f..9b7c4550 100644 --- a/rust/crates/lsp-engine/src/function_calls.rs +++ b/rust/crates/lsp-engine/src/function_calls.rs @@ -129,6 +129,7 @@ pub(crate) fn push_function_progress_locked( error: None, capabilities: None, completion_options: None, + signature_help_options: None, server_info: None, level: None, message: None, @@ -167,6 +168,7 @@ pub(crate) fn push_functions_event( error: None, capabilities: None, completion_options: None, + signature_help_options: None, server_info: None, level: None, message: None, diff --git a/rust/crates/lsp-engine/src/host_requests.rs b/rust/crates/lsp-engine/src/host_requests.rs index 7cf7d5e8..4b14a20a 100644 --- a/rust/crates/lsp-engine/src/host_requests.rs +++ b/rust/crates/lsp-engine/src/host_requests.rs @@ -66,6 +66,7 @@ pub(crate) fn cancel_host_request_locked( error: None, capabilities: None, completion_options: None, + signature_help_options: None, server_info: None, level: None, message: None, @@ -129,6 +130,105 @@ pub(crate) fn forward_host_request_locked( error: None, capabilities: None, completion_options: None, + signature_help_options: None, + server_info: None, + level: None, + message: None, + detail: None, + }, + ); + Ok(Vec::new()) +} + +const MAX_PENDING_APPLY_EDIT_REQUESTS: usize = 32; + +/// Cancels a pending server-initiated `workspace/applyEdit` request on `$/cancelRequest`. +pub(crate) fn cancel_apply_edit_request_locked( + state: &mut SessionState, + params: Option<&Value>, + outbound: &mut Vec, +) -> Result { + let Some(server_id) = params.and_then(|params| params.get("id")) else { + return Ok(false); + }; + let Some(apply_edit_id) = state + .apply_edit_requests + .iter() + .find(|(_, pending)| *pending == server_id) + .map(|(apply_edit_id, _)| apply_edit_id.clone()) + else { + return Ok(false); + }; + let server_id = state + .apply_edit_requests + .remove(&apply_edit_id) + .unwrap_or(Value::Null); + outbound.push(json_rpc_error(&server_id, -32800, "Request cancelled")?); + Ok(true) +} + +/// Forwards a validated `workspace/applyEdit` request from the language server +/// to the host as `workspaceApplyEdit`, or declines it immediately when the +/// session is not ready or has reached the pending apply-edit cap. +pub(crate) fn forward_apply_edit_locked( + session: &RuntimeSession, + state: &mut SessionState, + request: Value, +) -> Result, CoreError> { + let server_id = request.get("id").cloned().unwrap_or(Value::Null); + if state.lifecycle != LspLifecycleState::Ready || !state.client.initialized { + return Ok(vec![json_rpc_result( + &server_id, + json!({ + "applied": false, + "failureReason": "Language server session is not ready." + }), + )?]); + } + if state.apply_edit_requests.len() >= MAX_PENDING_APPLY_EDIT_REQUESTS { + return Ok(vec![json_rpc_result( + &server_id, + json!({ + "applied": false, + "failureReason": "Too many workspace edits are awaiting application." + }), + )?]); + } + let apply_edit_id = format!("apply-edit-{}", state.next_apply_edit_id); + state.next_apply_edit_id += 1; + state + .apply_edit_requests + .insert(apply_edit_id.clone(), server_id); + let sequence = take_sequence(state); + enqueue_runtime_event( + session, + state, + LspRuntimeEvent { + kind: "workspaceApplyEdit".to_string(), + channel: None, + plugin_id: None, + role: None, + event: None, + fields: None, + catalog_level: None, + sequence, + provider_id: session.provider_id.clone(), + session_id: session.id.clone(), + state: None, + operation_id: None, + method: Some("workspace/applyEdit".to_string()), + uri: None, + version: None, + diagnostics: None, + result: Some(json!({ + "applyEditId": apply_edit_id, + "label": request.get("label").cloned().unwrap_or(Value::Null), + "changes": request.get("changes").cloned().unwrap_or_else(|| json!({})), + })), + error: None, + capabilities: None, + completion_options: None, + signature_help_options: None, server_info: None, level: None, message: None, diff --git a/rust/crates/lsp-engine/src/lib.rs b/rust/crates/lsp-engine/src/lib.rs index ea3203be..f2ebfb8e 100644 --- a/rust/crates/lsp-engine/src/lib.rs +++ b/rust/crates/lsp-engine/src/lib.rs @@ -1,8 +1,8 @@ //! Stateful language-server sessions coordinating client state and child processes. use lithe_lsp_client::{ - client_apply_server_message_for_plugin, client_initialize_for_plugin, json_rpc_error_with_code, - json_rpc_error_with_data, json_rpc_notification, json_rpc_result, + client_apply_server_message_for_plugin, client_initialize_for_plugin, json_rpc_error, + json_rpc_error_with_code, json_rpc_error_with_data, json_rpc_notification, json_rpc_result, }; mod logging; mod scan_settings; @@ -252,6 +252,14 @@ pub fn plugin_host_response(request: PluginHostResponse) -> Result<(), CoreError .host_response(request) } +/// Answers one server-initiated `workspaceApplyEdit` event with whether the host +/// applied the workspace edit. +pub fn apply_edit_response(request: ApplyEditResponseRequest) -> Result<(), CoreError> { + engine() + .session(&request.session_id)? + .apply_edit_response(request) +} + /// Sends one host notification to a plugin backend. pub fn plugin_host_notify( request: PluginHostNotification, diff --git a/rust/crates/lsp-engine/src/lifecycle.rs b/rust/crates/lsp-engine/src/lifecycle.rs index 80fa4894..7f5bd8b5 100644 --- a/rust/crates/lsp-engine/src/lifecycle.rs +++ b/rust/crates/lsp-engine/src/lifecycle.rs @@ -26,6 +26,7 @@ impl RuntimeSession { None, ); clear_function_registry(self, &mut state); + state.apply_edit_requests.clear(); clear_runtime_diagnostics(self, &mut state); transition_locked(self, &mut state, LspLifecycleState::Stopping, None); plugin_operations::abandon(&self.startup_attempt); @@ -790,6 +791,7 @@ pub(crate) fn push_cleanup_fact( error: Some(error), capabilities: None, completion_options: None, + signature_help_options: None, server_info: None, level: Some("warning".to_string()), message: Some("Engine process cleanup failed".to_string()), @@ -836,6 +838,7 @@ pub(crate) fn transition_locked( error, capabilities: None, completion_options: None, + signature_help_options: None, server_info: None, level: None, message: None, diff --git a/rust/crates/lsp-engine/src/operations.rs b/rust/crates/lsp-engine/src/operations.rs index c925718b..dd8365eb 100644 --- a/rust/crates/lsp-engine/src/operations.rs +++ b/rust/crates/lsp-engine/src/operations.rs @@ -514,6 +514,44 @@ impl RuntimeSession { self.send_messages_or_fail(&outbound_order, vec![message], "hostResponse") } + /// Sends the language server the host's answer to one `workspaceApplyEdit` + /// runtime event (`lsp.applyEditResponse`). + pub(crate) fn apply_edit_response( + &self, + response: ApplyEditResponseRequest, + ) -> Result<(), CoreError> { + let outbound_order = self.lock_outbound_order()?; + let message = { + let mut state = self.lock_state()?; + let server_id = state + .apply_edit_requests + .remove(&response.apply_edit_id) + .ok_or_else(|| { + CoreError::new( + ErrorCode::InvalidRequest, + "No workspace/applyEdit request with this ID is waiting for an answer.", + ) + })?; + if response.applied { + state.hover_cache.clear(); + } + let mut payload = json!({ "applied": response.applied }); + if !response.applied { + if let Some(reason) = response + .failure_reason + .as_deref() + .map(str::trim) + .filter(|reason| !reason.is_empty()) + { + payload["failureReason"] = + json!(lithe_plugin_rpc::bounded_host_message(reason)); + } + } + json_rpc_result(&server_id, payload)? + }; + self.send_messages_or_fail(&outbound_order, vec![message], "applyEditResponse") + } + /// Writes one host notification to a ready plugin-owned backend. /// Returns `false`, writing nothing, when the backend negotiated no /// plugin-function protocol version. @@ -782,9 +820,12 @@ impl RuntimeSession { query: request.query, range: request.range, diagnostics: request.diagnostics, + code_action_context: request.code_action_context, completion_context: request.completion_context, + signature_help_context: request.signature_help_context, completion_item: request.completion_item, code_action: request.code_action, + inlay_hint: request.inlay_hint, command: request.command, formatting_options: request.formatting_options, include_declaration: request.include_declaration, @@ -910,6 +951,7 @@ pub(crate) fn semantic_method(operation: LspSemanticOperation) -> &'static str { match operation { LspSemanticOperation::Completion => "textDocument/completion", LspSemanticOperation::Hover => "textDocument/hover", + LspSemanticOperation::SignatureHelp => "textDocument/signatureHelp", LspSemanticOperation::Definition => "textDocument/definition", LspSemanticOperation::Declaration => "textDocument/declaration", LspSemanticOperation::TypeDefinition => "textDocument/typeDefinition", @@ -924,6 +966,7 @@ pub(crate) fn semantic_method(operation: LspSemanticOperation) -> &'static str { LspSemanticOperation::ResolveCodeAction => "codeAction/resolve", LspSemanticOperation::ExecuteCommand => "workspace/executeCommand", LspSemanticOperation::InlayHints => "textDocument/inlayHint", + LspSemanticOperation::ResolveInlayHint => "inlayHint/resolve", LspSemanticOperation::FoldingRanges => "textDocument/foldingRange", LspSemanticOperation::DocumentLinks => "textDocument/documentLink", LspSemanticOperation::WorkspaceSymbols => "workspace/symbol", @@ -936,6 +979,7 @@ fn semantic_capability(operation: LspSemanticOperation) -> Option<&'static str> match operation { LspSemanticOperation::Completion => Some("completion"), LspSemanticOperation::Hover => Some("hover"), + LspSemanticOperation::SignatureHelp => Some("signatureHelp"), LspSemanticOperation::Definition => Some("definition"), LspSemanticOperation::Declaration => Some("declaration"), LspSemanticOperation::TypeDefinition => Some("typeDefinition"), @@ -950,6 +994,7 @@ fn semantic_capability(operation: LspSemanticOperation) -> Option<&'static str> LspSemanticOperation::ResolveCodeAction => Some("codeActionResolve"), LspSemanticOperation::ExecuteCommand => Some("executeCommand"), LspSemanticOperation::InlayHints => Some("inlayHints"), + LspSemanticOperation::ResolveInlayHint => Some("inlayHintResolve"), LspSemanticOperation::FoldingRanges => Some("foldingRanges"), LspSemanticOperation::DocumentLinks => Some("documentLinks"), LspSemanticOperation::WorkspaceSymbols => Some("workspaceSymbols"), diff --git a/rust/crates/lsp-engine/src/provider_events.rs b/rust/crates/lsp-engine/src/provider_events.rs index 9baed433..8085b6b4 100644 --- a/rust/crates/lsp-engine/src/provider_events.rs +++ b/rust/crates/lsp-engine/src/provider_events.rs @@ -51,6 +51,7 @@ pub(crate) fn push_build_progress_locked( error: None, capabilities: None, completion_options: None, + signature_help_options: None, server_info: None, level: None, message: None, @@ -91,6 +92,7 @@ pub(crate) fn push_vcs_provider_event( error: None, capabilities: None, completion_options: None, + signature_help_options: None, server_info: None, level: None, message: None, @@ -131,6 +133,7 @@ pub(crate) fn push_negotiated_provider_event( error: None, capabilities: None, completion_options: None, + signature_help_options: None, server_info: None, level: None, message: None, diff --git a/rust/crates/lsp-engine/src/requests.rs b/rust/crates/lsp-engine/src/requests.rs index 2b0a1099..f99ce8b3 100644 --- a/rust/crates/lsp-engine/src/requests.rs +++ b/rust/crates/lsp-engine/src/requests.rs @@ -189,6 +189,8 @@ pub enum LspSemanticOperation { Completion, /// `textDocument/hover`. Hover, + /// `textDocument/signatureHelp`. + SignatureHelp, /// `textDocument/definition`. Definition, /// `textDocument/declaration`. @@ -217,6 +219,8 @@ pub enum LspSemanticOperation { ExecuteCommand, /// `textDocument/inlayHint`. InlayHints, + /// `inlayHint/resolve` for a previously returned inlay hint. + ResolveInlayHint, /// `textDocument/foldingRange`. FoldingRanges, /// `textDocument/documentLink`: clickable ranges such as URLs and file references. @@ -250,13 +254,23 @@ pub struct SemanticRequest { pub(crate) range: Option, #[serde(default)] pub(crate) diagnostics: Vec, + /// Optional LSP `CodeActionContext` filter and trigger kind (`only`, `triggerKind`). + #[serde(default)] + pub code_action_context: Option, /// LSP completion trigger context; validated by the shared request mapper. #[serde(default)] pub completion_context: Option, + /// Optional LSP `SignatureHelpContext` (`triggerKind`, `triggerCharacter`, + /// `isRetrigger`, `activeSignatureHelp`). + #[serde(default)] + pub signature_help_context: Option, #[serde(default)] pub(crate) completion_item: Option, #[serde(default)] pub(crate) code_action: Option, + /// Normalized or raw hint payload for `resolveInlayHint`. + #[serde(default)] + pub inlay_hint: Option, #[serde(default)] pub(crate) command: Option, /// Optional LSP `FormattingOptions` (`tabSize`, `insertSpaces`, ...) for @@ -577,6 +591,10 @@ pub struct LspRuntimeEvent { /// `{ triggerCharacters, allCommitCharacters }`, from `completionProvider`. #[serde(skip_serializing_if = "Option::is_none")] pub completion_options: Option, + /// On `featuresChanged` while `signatureHelp` is offered: the session's + /// `{ triggerCharacters, retriggerCharacters }`, from `signatureHelpProvider`. + #[serde(skip_serializing_if = "Option::is_none")] + pub signature_help_options: Option, #[serde(skip_serializing_if = "Option::is_none")] pub(crate) server_info: Option, #[serde(skip_serializing_if = "Option::is_none")] @@ -665,3 +683,18 @@ pub struct SetDetailedDiagnosticsRequest { /// True sends verbose tracing, false sends off; default sessions start disabled. pub enabled: bool, } + +/// Host outcome answering one `workspaceApplyEdit` runtime event (`lsp.applyEditResponse`). +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ApplyEditResponseRequest { + /// Session that emitted the `workspaceApplyEdit` event. + pub session_id: String, + /// Opaque `applyEditId` from the `workspaceApplyEdit` event result. + pub apply_edit_id: String, + /// Whether the host validated and applied every target in the edit. + pub applied: bool, + /// Optional bounded technical reason reported to the language server when `applied` is false. + #[serde(default)] + pub failure_reason: Option, +} diff --git a/rust/crates/lsp-engine/src/server_messages.rs b/rust/crates/lsp-engine/src/server_messages.rs index a7c12dba..3f6f760e 100644 --- a/rust/crates/lsp-engine/src/server_messages.rs +++ b/rust/crates/lsp-engine/src/server_messages.rs @@ -26,7 +26,7 @@ impl RuntimeSession { } else { None }; - let (known_pending, pending_before, old_capabilities, old_completion) = { + let (known_pending, pending_before, old_capabilities, old_completion, old_signature_help) = { let state = self.lock_state()?; let pending = response_id .as_ref() @@ -38,6 +38,7 @@ impl RuntimeSession { pending, state.client.server_capabilities.clone(), lithe_lsp_client::completion_options(&state.client), + lithe_lsp_client::signature_help_options(&state.client), ) }; // A response whose request has timed out, been cancelled, or belongs @@ -379,6 +380,14 @@ impl RuntimeSession { } if event.kind == "semanticTokensRefresh" { push_semantic_tokens_refresh_event(self, &mut state); + } else if event.kind == "inlayHintsRefresh" { + push_inlay_hints_refresh_event(self, &mut state); + } else if event.kind == "workspaceApplyEdit" { + outbound.extend(forward_apply_edit_locked( + self, + &mut state, + event.result.unwrap_or_default(), + )?); } else if event.kind == "functionsChanged" { let result = event.result.unwrap_or_default(); let removed: Vec = result @@ -440,6 +449,15 @@ impl RuntimeSession { && event.method.as_deref() == Some(lithe_lsp_client::plugin_logging::METHOD) { receive_plugin_diagnostic(self, &mut state, event.result.as_ref()); + } else if event.kind == "notification" + && event.method.as_deref() == Some("$/cancelRequest") + && cancel_apply_edit_request_locked( + &mut state, + event.result.as_ref(), + &mut outbound, + )? + { + // The server cancelled one of its pending workspace/applyEdit requests. } else if event.kind == "notification" && self.plugin_id.is_some() && event.method.as_deref() == Some("$/cancelRequest") @@ -468,7 +486,8 @@ impl RuntimeSession { } } if (state.client.server_capabilities != old_capabilities - || lithe_lsp_client::completion_options(&state.client) != old_completion) + || lithe_lsp_client::completion_options(&state.client) != old_completion + || lithe_lsp_client::signature_help_options(&state.client) != old_signature_help) && state.lifecycle == LspLifecycleState::Ready { let capabilities = state.client.server_capabilities.clone(); diff --git a/rust/crates/lsp-engine/src/state.rs b/rust/crates/lsp-engine/src/state.rs index 3a228919..d2db5183 100644 --- a/rust/crates/lsp-engine/src/state.rs +++ b/rust/crates/lsp-engine/src/state.rs @@ -90,6 +90,10 @@ pub(crate) struct SessionState { /// the opaque ID the host sees, with the backend's own JSON-RPC ID. pub(crate) host_requests: BTreeMap, pub(crate) next_host_request_id: u64, + /// Server-initiated `workspace/applyEdit` requests awaiting `lsp.applyEditResponse`, + /// keyed by the opaque `applyEditId` exposed to the host. + pub(crate) apply_edit_requests: BTreeMap, + pub(crate) next_apply_edit_id: u64, /// Trace is opt-in and serialized with protocol writes through outbound_order. pub(crate) detailed_diagnostics: bool, /// Desired trace setting retained until the initialize handshake permits notifications. diff --git a/rust/crates/lsp-engine/src/tests.rs b/rust/crates/lsp-engine/src/tests.rs index 190cfbe6..dc1911d4 100644 --- a/rust/crates/lsp-engine/src/tests.rs +++ b/rust/crates/lsp-engine/src/tests.rs @@ -351,9 +351,12 @@ impl Harness { new_name: None, range: None, diagnostics: Vec::new(), + code_action_context: None, completion_context: None, + signature_help_context: None, completion_item: None, code_action: None, + inlay_hint: None, command: None, formatting_options: None, include_declaration: None, @@ -2294,9 +2297,12 @@ fn dynamic_capability_registration_and_unregistration_change_availability() { new_name: None, range: None, diagnostics: Vec::new(), + code_action_context: None, completion_context: None, + signature_help_context: None, completion_item: None, code_action: None, + inlay_hint: None, command: None, formatting_options: None, include_declaration: None, @@ -2363,9 +2369,12 @@ fn dynamic_capability_registration_and_unregistration_change_availability() { new_name: None, range: None, diagnostics: Vec::new(), + code_action_context: None, completion_context: None, + signature_help_context: None, completion_item: None, code_action: None, + inlay_hint: None, command: None, formatting_options: None, include_declaration: None, @@ -2495,9 +2504,12 @@ fn workspace_execute_command_does_not_require_an_open_document() { new_name: None, range: None, diagnostics: Vec::new(), + code_action_context: None, completion_context: None, + signature_help_context: None, completion_item: None, code_action: None, + inlay_hint: None, command: Some(json!({ "title": "Apply fix", "command": "source.fix", @@ -5994,9 +6006,12 @@ fn anything_that_can_change_what_the_server_knows_forgets_kept_hovers() { new_name: None, range: None, diagnostics: Vec::new(), + code_action_context: None, completion_context: None, + signature_help_context: None, completion_item: None, code_action: None, + inlay_hint: None, command: Some(json!({ "title": "Fix", "command": "source.fix" })), formatting_options: None, include_declaration: None, @@ -6109,3 +6124,191 @@ fn an_edit_to_the_hovered_document_asks_again_at_its_new_version() { harness.sync(HOVER_URI, "package main\nfunc main() { println() }\n"); harness.hover_asks_server(1, 6, "an edit changes the hovered text"); } + +#[test] +fn session_signature_help_inlay_hints_refresh_and_workspace_apply_edit_round_trip() { + let mut harness = Harness::start(|_| {}); + harness.server.complete_initialize(json!({ + "signatureHelpProvider": { + "triggerCharacters": ["("], + "retriggerCharacters": [","] + }, + "inlayHintProvider": { "resolveProvider": true }, + "codeActionProvider": { "resolveProvider": true } + })); + harness.await_state(LspLifecycleState::Ready); + + let initial_features = harness + .await_event(|event| event.kind == "featuresChanged") + .clone(); + let capabilities = initial_features.capabilities.as_ref().unwrap(); + assert!(capabilities.contains(&"signatureHelp".to_string())); + assert!(capabilities.contains(&"inlayHints".to_string())); + assert!(capabilities.contains(&"inlayHintResolve".to_string())); + assert_eq!( + initial_features.signature_help_options, + Some(json!({ + "triggerCharacters": ["("], + "retriggerCharacters": [","] + })) + ); + + // Dynamic registration adding a trigger character re-emits featuresChanged. + let initial_seq = initial_features.sequence; + harness.server.send(json!({ + "jsonrpc": "2.0", + "id": "reg-sig-1", + "method": "client/registerCapability", + "params": { + "registrations": [{ + "id": "sig-extra", + "method": "textDocument/signatureHelp", + "registerOptions": { + "triggerCharacters": ["<"] + } + }] + } + })); + let updated_features = harness + .await_event(|event| event.kind == "featuresChanged" && event.sequence > initial_seq) + .clone(); + assert_eq!( + updated_features.signature_help_options, + Some(json!({ + "triggerCharacters": ["(", "<"], + "retriggerCharacters": [","] + })) + ); + + let uri = "file:///workspace/main.go"; + harness.sync(uri, "package main\nfunc main() { add(1, 2) }\n"); + + // Stale cancellation on document edit for signatureHelp. + let stale_op = harness.request_at(LspSemanticOperation::SignatureHelp, uri, 1, 18); + let _stale_req_id = harness + .server + .await_request("textDocument/signatureHelp") + .unwrap(); + harness.sync(uri, "package main\nfunc main() { add(10, 2) }\n"); + let stale_done = harness + .await_event(|event| { + event.kind == "requestCompleted" && event.operation_id.as_deref() == Some(&stale_op) + }) + .clone(); + assert_eq!( + stale_done.error.as_ref().map(|err| err.code.as_str()), + Some("staleDocumentVersion") + ); + + // Normal signatureHelp completion. + let sig_op = harness.request_at(LspSemanticOperation::SignatureHelp, uri, 1, 19); + let sig_req_id = harness + .server + .await_request_at("textDocument/signatureHelp", 1) + .unwrap(); + harness.server.send(json!({ + "jsonrpc": "2.0", + "id": sig_req_id, + "result": { + "signatures": [{ + "label": "add(a int, b int)", + "parameters": [{ "label": [4, 9] }, { "label": [11, 16] }] + }], + "activeSignature": 0, + "activeParameter": 0 + } + })); + let sig_done = harness + .await_event(|event| { + event.kind == "requestCompleted" && event.operation_id.as_deref() == Some(&sig_op) + }) + .clone(); + assert_eq!( + sig_done.result.as_ref().unwrap()["signatureHelp"]["signatures"][0]["parameters"][0] + ["label"], + json!("a int") + ); + + // workspace/inlayHint/refresh emits inlayHintsRefresh and replies null. + harness.server.send(json!({ + "jsonrpc": "2.0", + "id": "refresh-hints-1", + "method": "workspace/inlayHint/refresh" + })); + harness.await_event(|event| event.kind == "inlayHintsRefresh"); + assert!(harness.server.messages().iter().any(|msg| { + msg.get("id") == Some(&json!("refresh-hints-1")) && msg.get("result") == Some(&Value::Null) + })); + + // Server-initiated workspace/applyEdit -> host applyEditResponse round-trip. + harness.server.send(json!({ + "jsonrpc": "2.0", + "id": "srv-apply-1", + "method": "workspace/applyEdit", + "params": { + "label": "Add import", + "edit": { + "changes": { + "file:///workspace/main.go": [{ + "range": { + "start": { "line": 0, "character": 12 }, + "end": { "line": 0, "character": 12 } + }, + "newText": "\nimport \"fmt\"" + }] + } + } + } + })); + let apply_event = harness + .await_event(|event| event.kind == "workspaceApplyEdit") + .clone(); + let apply_edit_id = apply_event.result.as_ref().unwrap()["applyEditId"] + .as_str() + .unwrap() + .to_string(); + harness + .session() + .apply_edit_response(ApplyEditResponseRequest { + session_id: harness.session_id.clone(), + apply_edit_id, + applied: true, + failure_reason: None, + }) + .unwrap(); + assert!(harness.server.messages().iter().any(|msg| { + msg.get("id") == Some(&json!("srv-apply-1")) + && msg.get("result") == Some(&json!({ "applied": true })) + })); + + // Server $/cancelRequest cancels a pending workspace/applyEdit with -32800. + harness.server.send(json!({ + "jsonrpc": "2.0", + "id": "srv-apply-2", + "method": "workspace/applyEdit", + "params": { + "edit": { "changes": {} } + } + })); + let second_seq = apply_event.sequence; + harness.await_event(|event| event.kind == "workspaceApplyEdit" && event.sequence > second_seq); + harness.server.send(json!({ + "jsonrpc": "2.0", + "method": "$/cancelRequest", + "params": { "id": "srv-apply-2" } + })); + let deadline = Instant::now() + Duration::from_secs(5); + while Instant::now() < deadline { + if harness.server.messages().iter().any(|msg| { + msg.get("id") == Some(&json!("srv-apply-2")) + && msg.pointer("/error/code") == Some(&json!(-32800)) + }) { + break; + } + thread::sleep(Duration::from_millis(2)); + } + assert!(harness.server.messages().iter().any(|msg| { + msg.get("id") == Some(&json!("srv-apply-2")) + && msg.pointer("/error/code") == Some(&json!(-32800)) + })); +} diff --git a/rust/fixtures/editor/ide-essentials-v1.json b/rust/fixtures/editor/ide-essentials-v1.json index 723f4ddd..fd5e1ad1 100644 --- a/rust/fixtures/editor/ide-essentials-v1.json +++ b/rust/fixtures/editor/ide-essentials-v1.json @@ -58,6 +58,7 @@ "expected": { "lineNumbers": true, "whitespace": false, + "inlayHints": true, "cursorStyle": "line", "cursorBlink": true, "autoSaveDelayMilliseconds": 1500, diff --git a/rust/fixtures/lsp/editor-actions-hints-v1.json b/rust/fixtures/lsp/editor-actions-hints-v1.json new file mode 100644 index 00000000..6b9f043b --- /dev/null +++ b/rust/fixtures/lsp/editor-actions-hints-v1.json @@ -0,0 +1,214 @@ +{ + "schemaVersion": 1, + "uri": "file:///workspace/main.rs", + "codeActions": { + "context": { + "only": ["quickfix", "refactor"], + "triggerKind": 1 + }, + "serverResult": [ + { + "title": "Organize imports", + "kind": "source.organizeImports", + "command": { + "title": "Organize imports", + "command": "workspace.organizeImports", + "arguments": ["file:///workspace/main.rs"] + } + }, + { + "title": "Disabled refactor", + "kind": "refactor.extract", + "disabled": { + "reason": "Selection is empty" + } + }, + { + "title": "Extract\nhelper", + "kind": "refactor.extract", + "data": { + "id": "extract-1" + } + }, + { + "title": "Remove unused binding", + "kind": "quickfix.unused", + "edit": { + "changes": { + "file:///workspace/main.rs": [ + { + "range": { + "start": { "line": 2, "character": 4 }, + "end": { "line": 2, "character": 12 } + }, + "newText": "_unused" + } + ] + } + } + }, + { + "title": "Initialize binding", + "kind": "refactor.rewrite", + "isPreferred": true, + "edit": { + "changes": { + "file:///workspace/main.rs": [ + { + "range": { + "start": { "line": 2, "character": 12 }, + "end": { "line": 2, "character": 12 } + }, + "newText": " = 0" + } + ] + } + } + } + ], + "expectedTitlesAndGroups": [ + { "title": "Initialize binding", "group": "refactor", "isPreferred": true }, + { "title": "Remove unused binding", "group": "quickfix", "isPreferred": false }, + { "title": "Extract helper", "group": "refactor", "isPreferred": false }, + { "title": "Organize imports", "group": "source", "isPreferred": false } + ] + }, + "signatureHelp": { + "triggerContext": { + "triggerKind": 2, + "triggerCharacter": "(", + "isRetrigger": false + }, + "serverResult": { + "signatures": [ + { + "label": "add(int, int) -> int", + "documentation": "Adds two integers.", + "parameters": [ + { "label": "int", "documentation": "Left operand" }, + { "label": "int", "documentation": { "kind": "markdown", "value": "**Right** operand" } } + ] + }, + { + "label": "日志(🧪 msg: str, 值: i32)", + "documentation": { "kind": "markdown", "value": "记录结构化日志" }, + "parameters": [ + { "label": [3, 14] }, + { "label": [16, 22] } + ] + } + ], + "activeSignature": 99, + "activeParameter": 99 + }, + "expectedResult": { + "signatures": [ + { + "label": "add(int, int) -> int", + "documentation": "Adds two integers.", + "isMarkdown": false, + "activeParameter": 1, + "parameters": [ + { + "label": "int", + "utf16Start": 4, + "utf16End": 7, + "byteStart": 4, + "byteEnd": 7, + "documentation": "Left operand", + "isMarkdown": false + }, + { + "label": "int", + "utf16Start": 9, + "utf16End": 12, + "byteStart": 9, + "byteEnd": 12, + "documentation": "**Right** operand", + "isMarkdown": true + } + ] + }, + { + "label": "日志(🧪 msg: str, 值: i32)", + "documentation": "记录结构化日志", + "isMarkdown": true, + "activeParameter": 1, + "parameters": [ + { + "label": "🧪 msg: str", + "utf16Start": 3, + "utf16End": 14, + "byteStart": 7, + "byteEnd": 20, + "documentation": null, + "isMarkdown": false + }, + { + "label": "值: i32", + "utf16Start": 16, + "utf16End": 22, + "byteStart": 22, + "byteEnd": 30, + "documentation": null, + "isMarkdown": false + } + ] + } + ], + "activeSignature": 1, + "activeParameter": 1 + } + }, + "inlayHints": { + "serverResult": [ + { "position": { "line": 2, "character": 30 }, "label": ": h9" }, + { "position": { "line": 2, "character": 2 }, "label": ": h1", "paddingRight": true }, + { "position": { "line": 1, "character": 8 }, "label": [{ "value": "count" }, { "value": ": usize" }], "kind": 1, "tooltip": { "kind": "markdown", "value": "`usize` parameter" } }, + { "position": { "line": 2, "character": 6 }, "label": ": h2" }, + { "position": { "line": 2, "character": 10 }, "label": ": h3" }, + { "position": { "line": 2, "character": 14 }, "label": ": h4" }, + { "position": { "line": 2, "character": 18 }, "label": ": h5" }, + { "position": { "line": 2, "character": 22 }, "label": ": h6" }, + { "position": { "line": 2, "character": 26 }, "label": ": h7" }, + { "position": { "line": 2, "character": 28 }, "label": ": very_long_type_name_exceeding_forty_eight_characters_limit" }, + { "position": { "line": 2, "character": 1 }, "label": " " } + ], + "expectedCount": 9, + "expectedFirstLabel": "count: usize", + "expectedTruncatedEighthOnLine2": ": very_long_type_name_exceeding_forty_eight_cha…" + }, + "workspaceApplyEdit": { + "acceptedRequest": { + "label": "Apply quick fix", + "edit": { + "documentChanges": [ + { + "textDocument": { "uri": "file:///workspace/main.rs", "version": 1 }, + "edits": [ + { + "range": { + "start": { "line": 0, "character": 0 }, + "end": { "line": 0, "character": 0 } + }, + "newText": "use std::fmt;\n" + } + ] + } + ] + } + }, + "rejectedResourceRequest": { + "label": "Create file", + "edit": { + "documentChanges": [ + { + "kind": "create", + "uri": "file:///workspace/generated.rs" + } + ] + } + }, + "expectedRejectedFailureReason": "Resource create, rename, and delete operations are not supported." + } +} From 1af0466989b31bb7bad995331cf67074e339b394 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Wed, 18 Nov 2026 22:15:40 +0800 Subject: [PATCH 2/4] fix(lsp): guard versioned workspace edits and hint resolution --- rust/contracts/application-boundary.md | 6 + rust/contracts/rust-core-api.md | 38 ++- rust/crates/lsp-client/src/client.rs | 5 + .../crates/lsp-client/src/client/lifecycle.rs | 8 +- rust/crates/lsp-client/src/client/requests.rs | 3 + rust/crates/lsp-client/src/client/results.rs | 296 +++++++++--------- .../lsp-client/src/client/server_messages.rs | 12 +- .../lsp-client/src/client/workspace_edits.rs | 211 +++++++++++++ rust/crates/lsp-client/src/tests.rs | 62 ++++ rust/crates/lsp-client/src/types.rs | 3 + rust/crates/lsp-engine/src/engine.rs | 2 +- rust/crates/lsp-engine/src/events.rs | 13 +- rust/crates/lsp-engine/src/host_requests.rs | 157 ++++++++-- rust/crates/lsp-engine/src/lifecycle.rs | 38 +-- rust/crates/lsp-engine/src/operations.rs | 4 +- rust/crates/lsp-engine/src/server_messages.rs | 1 + rust/crates/lsp-engine/src/state.rs | 12 +- rust/crates/lsp-engine/src/tests.rs | 114 +++++-- .../fixtures/lsp/editor-actions-hints-v1.json | 1 + 19 files changed, 729 insertions(+), 257 deletions(-) create mode 100644 rust/crates/lsp-client/src/client/workspace_edits.rs diff --git a/rust/contracts/application-boundary.md b/rust/contracts/application-boundary.md index 1add9d4f..0116cdc8 100644 --- a/rust/contracts/application-boundary.md +++ b/rust/contracts/application-boundary.md @@ -80,6 +80,12 @@ this lifecycle protection; actual symbol computation remains upstream-owned. | Modules | stable IDs, manifests, enabled state, lifecycle snapshots, dependencies, capabilities, and contributions | native factories, processes, timers, PTY/ConPTY, watchers, connections, and UI rendering | | Updates | normalized release metadata, state names, validated `stable|autobuild` preference, explicit rolling consent, and stable error codes | update feeds, package verification, download, installation, restart, and native UI | +Language-server workspace edits preserve explicit LSP document versions. +Core rejects edits for stale or unknown versioned documents. A native host checks +that its editor snapshots still match those versions before touching files or +buffers, and stops pending work when Core revokes a delivered request. The +[Core commands reference](rust-core-api.md#commands) specifies the event and reply shapes. + ### Application update channels A missing saved channel selects `stable` for Stable and legacy shared-identity builds; diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 07d3c9dc..40876ed0 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -3463,7 +3463,9 @@ to single-line bounded text (512 bytes), each action carries a deterministic `group` (`"quickfix"`, `"refactor"`, `"source"`, or `"other"`), and Core sorts actions stably with `isPreferred` first and then `quickfix`, `refactor`, `source`, `other` (up to 256 actions). `resolveCodeAction` strips Core-only `group` before -sending `codeAction/resolve`. A platform's display severity or marker projection is +sending `codeAction/resolve`. A code action with an unsupported or stale workspace +edit is omitted. Normalized edits preserve the optional `documentVersions` map +described below. A platform's display severity or marker projection is not a diagnostic request model. Non-LSP markers may request actions with a range and an empty diagnostic context. The round-trip fixtures are `rust/fixtures/lsp/diagnostic-code-actions-v1.json` and @@ -3500,7 +3502,7 @@ typed events. Hosts should use `waitEvents` so idle sessions do not poll. Event types include `stateChanged`, `featuresChanged`, `diagnostics`, `requestCompleted`, `requestProgress`, `functionsChanged`, `hostRequest`, -`workspaceApplyEdit`, `inlayHintsRefresh`, `semanticTokensRefresh`, +`workspaceApplyEdit`, `workspaceApplyEditCancelled`, `inlayHintsRefresh`, `semanticTokensRefresh`, `serverInfoChanged`, and `log`. Every request completes at most once with either `result` or a structured runtime error containing provider/session, stage, optional method/document/request, stable code, and @@ -5606,19 +5608,31 @@ Operation `inlayHints` (`textDocument/inlayHint`) sorts hints stably by (with `…`), caps tooltips at 2048 bytes, and keeps at most 8 hints per line and 512 hints per viewport request. When the server advertises `inlayHintProvider.resolveProvider`, `featuresChanged` includes `inlayHintResolve` and `resolveInlayHint` (`inlayHint/resolve`) -resolves a single hint (`{ hint }`). Core advertises `workspace.inlayHint.refreshSupport` +resolves a single hint (`{ hint }`). Pass back the normalized hint with its optional +`resolvePayload` for this operation. Core uses that bounded original hint (at most 16 KiB) +to keep the language server's original label parts, position and data. Hints that +exceed the resolve limit are displayable without a resolve payload. Core advertises `workspace.inlayHint.refreshSupport` and forwards `workspace/inlayHint/refresh` as the `inlayHintsRefresh` event after -acknowledging the request with JSON-RPC `null`. +acknowledging the request with JSON-RPC `null`. Repeated refreshes coalesce until +the host drains the queued event. When a language server sends `workspace/applyEdit`, Core validates its edit payload, -immediately replies `{ applied: false, failureReason }` for non-file URIs, snippet -edits, or `create`/`rename`/`delete` resource operations, and otherwise emits a -`workspaceApplyEdit` runtime event with `result: { applyEditId, label, changes }` -(mapping target file paths to UTF-16 text edits). After validating workspace -boundaries and applying or rejecting the edit via `lsp.planWorkspaceEdit` and -`lsp.applyTextEdits`, the host answers with `lsp.applyEditResponse` -(`{ sessionId, applyEditId, applied, failureReason? }`). If the server cancels the -pending request or the session shuts down first, Core settles the JSON-RPC call cleanly. +immediately replies `{ applied: false, failureReason }` for stale versioned targets, +invalid positions or replacement text, non-file URIs, snippet or annotated +edits, or `create`/`rename`/`delete` resource operations. The valid payload is +bounded to 256 target files, 4096 edits and 4 MiB of replacement text. Numeric +versions must match the session's current open documents. Core preserves them in +`documentVersions`, keyed by the same target paths as `changes`. The event is +`workspaceApplyEdit` with `result: { applyEditId, label, changes, documentVersions }`. +The native host rechecks the supplied versions against the synchronized editor +snapshots and validates workspace boundaries. It applies or rejects the edit +using `lsp.planWorkspaceEdit` and `lsp.applyTextEdits`, then answers with +`lsp.applyEditResponse` (`{ sessionId, applyEditId, applied, failureReason? }`). +Eight requests per session may await the host within the session request timeout. +If cancelled or expired before delivery, Core removes the queued edit. After +delivery, `workspaceApplyEditCancelled` carries `result: { applyEditId }` and the +host stops pending work for that ID. The server receives cancellation, timeout, +or shutdown settlement without waiting for a late host response. Operation `documentSymbols` (`textDocument/documentSymbol`) needs only the document `uri` and is offered, as the `documentSymbols` feature, when the server diff --git a/rust/crates/lsp-client/src/client.rs b/rust/crates/lsp-client/src/client.rs index d293b7ef..d8639e19 100644 --- a/rust/crates/lsp-client/src/client.rs +++ b/rust/crates/lsp-client/src/client.rs @@ -14,6 +14,7 @@ mod requests; mod results; mod server_messages; mod validation; +mod workspace_edits; pub use capabilities::*; pub(crate) use diagnostics::*; @@ -23,6 +24,7 @@ pub(crate) use requests::*; pub(crate) use results::*; pub use server_messages::*; pub(crate) use validation::*; +use workspace_edits::{parse_bounded_text_edit, parse_workspace_apply_edit, WorkspaceEdit}; #[cfg(test)] mod semantic_tests { @@ -207,6 +209,7 @@ mod formatting_and_completion_tests { "range": {"start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 1}}, "newText": "x" }])), + &Default::default(), ) .unwrap(); assert_eq!(result["edits"][0]["newText"], "x"); @@ -222,6 +225,7 @@ mod formatting_and_completion_tests { let result = lsp_feature_result_for_method( Some("textDocument/documentSymbol"), Some(&case["serverResult"]), + &Default::default(), ) .unwrap(); assert_eq!(result, case["expected"], "case {}", case["name"]); @@ -277,6 +281,7 @@ mod formatting_and_completion_tests { let result = lsp_feature_result_for_method( Some("textDocument/completion"), Some(&json!({"isIncomplete": true, "items": [{"label": "a"}]})), + &Default::default(), ) .unwrap(); assert_eq!(result["isIncomplete"], true); diff --git a/rust/crates/lsp-client/src/client/lifecycle.rs b/rust/crates/lsp-client/src/client/lifecycle.rs index 073b9f58..03f6990c 100644 --- a/rust/crates/lsp-client/src/client/lifecycle.rs +++ b/rust/crates/lsp-client/src/client/lifecycle.rs @@ -84,13 +84,7 @@ pub fn client_initialize_for_plugin( "inlayHint": { "dynamicRegistration": true, "resolveSupport": { - "properties": [ - "tooltip", - "textEdits", - "label.tooltip", - "label.location", - "label.command" - ] + "properties": ["tooltip", "textEdits"] } }, "semanticTokens": { diff --git a/rust/crates/lsp-client/src/client/requests.rs b/rust/crates/lsp-client/src/client/requests.rs index 93c02088..713c291c 100644 --- a/rust/crates/lsp-client/src/client/requests.rs +++ b/rust/crates/lsp-client/src/client/requests.rs @@ -438,6 +438,9 @@ fn inlay_hint_resolve_json(hint: Option<&Value>) -> Result { "This LSP request requires an inlay hint.", ) })?; + // A normalized hint's display label may be shortened or assembled from + // parts. Resolve must use the server's original position, label and data. + let hint = hint.get("resolvePayload").unwrap_or(hint); let object = hint.as_object().ok_or_else(|| { CoreError::new( ErrorCode::InvalidRequest, diff --git a/rust/crates/lsp-client/src/client/results.rs b/rust/crates/lsp-client/src/client/results.rs index e7b56e6c..ac66c40d 100644 --- a/rust/crates/lsp-client/src/client/results.rs +++ b/rust/crates/lsp-client/src/client/results.rs @@ -1,10 +1,14 @@ //! Parsing feature results into Core shapes. use super::*; +use std::borrow::Cow; +use std::collections::BTreeMap; +use std::io::{self, Write}; pub(crate) fn lsp_feature_result_for_method( method: Option<&str>, result: Option<&Value>, + open_documents: &BTreeMap, ) -> Option { let result = result?; match method { @@ -56,9 +60,9 @@ pub(crate) fn lsp_feature_result_for_method( "lenses": parse_code_lenses(result) })), Some("textDocument/codeAction") => Some(json!({ - "actions": parse_code_actions(result) + "actions": parse_code_actions(result, open_documents) })), - Some("codeAction/resolve") => parse_code_action(result).map(|action| { + Some("codeAction/resolve") => parse_code_action(result, open_documents).map(|action| { json!({ "action": action }) @@ -219,10 +223,11 @@ const MAX_INLAY_HINTS_PER_VIEWPORT: usize = 512; const MAX_INLAY_HINTS_PER_LINE: usize = 8; const MAX_INLAY_HINT_LABEL_CHARS: usize = 48; const MAX_INLAY_HINT_TOOLTIP_BYTES: usize = 2048; +const MAX_INLAY_HINT_RESOLVE_BYTES: usize = 16 * 1024; +const MAX_INLAY_HINT_TEXT_EDITS: usize = 16; const MAX_CODE_ACTIONS: usize = 256; const MAX_CODE_ACTION_TITLE_BYTES: usize = 512; -const MAX_APPLY_EDIT_LABEL_BYTES: usize = 256; fn parse_signature_help(result: &Value) -> Option { if result.is_null() { @@ -268,22 +273,24 @@ struct LabelBoundary { fn normalize_single_line_with_boundaries( raw: &str, max_chars: usize, -) -> (String, Vec) { +) -> (String, Vec, bool) { let mut normalized = String::new(); let mut boundaries = Vec::new(); let mut chars = raw.char_indices().peekable(); let mut raw_u16 = 0_usize; let mut norm_u16 = 0_usize; let mut emitted_chars = 0_usize; - let mut truncated = false; - let char_limit = if raw.chars().count() > max_chars { - truncated = true; + let truncated = raw.chars().nth(max_chars).is_some(); + let char_limit = if truncated { max_chars.saturating_sub(1) } else { max_chars }; while let Some((_, ch)) = chars.next() { + if emitted_chars == char_limit { + break; + } boundaries.push(LabelBoundary { raw_u16, norm_byte: normalized.len(), @@ -298,11 +305,9 @@ fn normalize_single_line_with_boundaries( norm_u16, }); raw_u16 += 1; - if emitted_chars < char_limit { - normalized.push(' '); - norm_u16 += 1; - emitted_chars += 1; - } + normalized.push(' '); + norm_u16 += 1; + emitted_chars += 1; continue; } raw_u16 += ch.len_utf16(); @@ -311,11 +316,9 @@ fn normalize_single_line_with_boundaries( } else { ch }; - if emitted_chars < char_limit { - normalized.push(out_ch); - norm_u16 += out_ch.len_utf16(); - emitted_chars += 1; - } + normalized.push(out_ch); + norm_u16 += out_ch.len_utf16(); + emitted_chars += 1; } boundaries.push(LabelBoundary { raw_u16, @@ -325,7 +328,7 @@ fn normalize_single_line_with_boundaries( if truncated { normalized.push('…'); } - (normalized, boundaries) + (normalized, boundaries, truncated) } fn parse_signature_information( @@ -333,7 +336,7 @@ fn parse_signature_information( fallback_active_param: Option, ) -> Option { let raw_label = signature.get("label")?.as_str()?; - let (label, boundaries) = + let (label, boundaries, label_truncated) = normalize_single_line_with_boundaries(raw_label, MAX_SIGNATURE_LABEL_CHARS); if label.trim().is_empty() { return None; @@ -344,9 +347,13 @@ fn parse_signature_information( let mut search_from_byte = 0_usize; if let Some(raw_params) = signature.get("parameters").and_then(Value::as_array) { for param in raw_params.iter().take(MAX_PARAMETERS) { - if let Some(parsed) = - parse_parameter_information(param, &label, &boundaries, &mut search_from_byte) - { + if let Some(parsed) = parse_parameter_information( + param, + &label, + &boundaries, + label_truncated, + &mut search_from_byte, + ) { parameters.push(parsed); } } @@ -375,6 +382,7 @@ fn parse_parameter_information( param: &Value, signature_label: &str, boundaries: &[LabelBoundary], + label_truncated: bool, search_from_byte: &mut usize, ) -> Option { let label_field = param.get("label")?; @@ -385,28 +393,33 @@ fn parse_parameter_information( if start_u16 > end_u16 { return None; } - let start_idx = boundaries - .binary_search_by_key(&start_u16, |b| b.raw_u16) - .ok()?; - let end_idx = boundaries - .binary_search_by_key(&end_u16, |b| b.raw_u16) - .ok()?; - let start_b = boundaries[start_idx].norm_byte; - let end_b = boundaries[end_idx].norm_byte; - let start_norm_u16 = boundaries[start_idx].norm_u16; - let end_norm_u16 = boundaries[end_idx].norm_u16; - if start_b < end_b && end_b <= signature_label.len() { + let last = boundaries.last()?.raw_u16; + let boundary = |position| { + boundaries + .binary_search_by_key(&position, |b| b.raw_u16) + .ok() + .map(|index| boundaries[index]) + }; + let start = boundary(start_u16.min(last)); + let end = boundary(end_u16.min(last)); + if !label_truncated && end_u16 > last { + return None; + } + let (start, end) = (start?, end?); + let start_b = start.norm_byte; + let end_b = end.norm_byte; + if start_b < end_b { *search_from_byte = end_b; ( signature_label[start_b..end_b].to_string(), - Some((start_norm_u16, end_norm_u16, start_b, end_b)), + Some((start.norm_u16, end.norm_u16, start_b, end_b)), ) } else { (String::new(), None) } } Value::String(raw_sub) => { - let (norm_sub, _) = normalize_single_line_with_boundaries(raw_sub, 128); + let (norm_sub, _, _) = normalize_single_line_with_boundaries(raw_sub, 128); if norm_sub.is_empty() { return None; } @@ -468,7 +481,7 @@ fn bounded_documentation(value: Option<&Value>, max_bytes: usize) -> (Option String { +pub(super) fn truncate_utf8_bytes(text: &str, max_bytes: usize) -> String { if text.len() <= max_bytes { return text.to_string(); } @@ -490,21 +503,29 @@ fn parse_inlay_hints(result: &Value) -> Vec { let Some(values) = result.as_array() else { return Vec::new(); }; - let mut hints: Vec = values.iter().filter_map(parse_inlay_hint).collect(); - hints.sort_by_key(|hint| (hint.position.line, hint.position.utf16_column)); + let mut hints: Vec<_> = values + .iter() + .filter_map(|hint| { + let position = parse_lsp_position(hint.get("position")?)?; + (position.line >= 0 && position.utf16_column >= 0).then_some((position, hint)) + }) + .collect(); + hints.sort_by_key(|(position, _)| (position.line, position.utf16_column)); let mut culled = Vec::with_capacity(hints.len().min(MAX_INLAY_HINTS_PER_VIEWPORT)); let mut current_line: Option = None; let mut line_count = 0_usize; - for hint in hints { - if current_line == Some(hint.position.line) { - if line_count >= MAX_INLAY_HINTS_PER_LINE { - continue; - } - line_count += 1; - } else { - current_line = Some(hint.position.line); - line_count = 1; + for (position, raw_hint) in hints { + if current_line != Some(position.line) { + current_line = Some(position.line); + line_count = 0; + } + if line_count >= MAX_INLAY_HINTS_PER_LINE { + continue; } + let Some(hint) = parse_inlay_hint(raw_hint) else { + continue; + }; + line_count += 1; culled.push(hint); if culled.len() >= MAX_INLAY_HINTS_PER_VIEWPORT { break; @@ -515,15 +536,35 @@ fn parse_inlay_hints(result: &Value) -> Vec { fn parse_inlay_hint(hint: &Value) -> Option { let raw_label = parse_inlay_hint_label(hint.get("label")?)?; - let (label, _) = normalize_single_line_with_boundaries(&raw_label, MAX_INLAY_HINT_LABEL_CHARS); + let (label, _, _) = + normalize_single_line_with_boundaries(&raw_label, MAX_INLAY_HINT_LABEL_CHARS); if label.trim().is_empty() { return None; } let tooltip = completion_documentation(hint.get("tooltip")) .map(|text| truncate_utf8_bytes(text.trim(), MAX_INLAY_HINT_TOOLTIP_BYTES)) .filter(|text| !text.is_empty()); + let resolve_payload = bounded_inlay_resolve_payload(hint); + let position = parse_lsp_position(hint.get("position")?)?; + if position.line < 0 || position.utf16_column < 0 { + return None; + } + let text_edits = hint + .get("textEdits") + .and_then(Value::as_array) + .filter(|edits| edits.len() <= MAX_INLAY_HINT_TEXT_EDITS) + .and_then(|edits| { + let mut bytes = 0; + edits + .iter() + .map(|edit| { + parse_bounded_text_edit(edit, &mut bytes, MAX_INLAY_HINT_RESOLVE_BYTES).ok() + }) + .collect::>>() + }) + .unwrap_or_default(); Some(LspInlayHintResponse { - position: parse_lsp_position(hint.get("position")?)?, + position, label, kind: hint.get("kind").and_then(Value::as_i64), tooltip, @@ -535,29 +576,51 @@ fn parse_inlay_hint(hint: &Value) -> Option { .get("paddingRight") .and_then(Value::as_bool) .unwrap_or(false), - text_edits: hint - .get("textEdits") - .and_then(Value::as_array) - .map(|edits| edits.iter().filter_map(parse_lsp_text_edit_value).collect()) - .unwrap_or_default(), - data: hint.get("data").filter(|value| !value.is_null()).cloned(), + text_edits, + data: resolve_payload + .as_ref() + .and_then(|payload| payload.get("data")) + .filter(|value| !value.is_null()) + .cloned(), + resolve_payload, }) } -fn parse_inlay_hint_label(value: &Value) -> Option { +fn parse_inlay_hint_label(value: &Value) -> Option> { match value { - Value::String(label) => Some(label.clone()), + Value::String(label) => Some(Cow::Borrowed(label)), Value::Array(parts) => { let label = parts .iter() .filter_map(|part| part.get("value").and_then(Value::as_str)) + .flat_map(str::chars) + .take(MAX_INLAY_HINT_LABEL_CHARS + 1) .collect::(); - (!label.is_empty()).then_some(label) + (!label.is_empty()).then_some(Cow::Owned(label)) } _ => None, } } +fn bounded_inlay_resolve_payload(hint: &Value) -> Option { + struct ByteBudget(usize); + impl Write for ByteBudget { + fn write(&mut self, bytes: &[u8]) -> io::Result { + self.0 = self + .0 + .checked_sub(bytes.len()) + .ok_or(io::ErrorKind::FileTooLarge)?; + Ok(bytes.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + serde_json::to_writer(ByteBudget(MAX_INLAY_HINT_RESOLVE_BYTES), hint).ok()?; + Some(hint.clone()) +} + /// Normalizes a `textDocument/documentSymbol` result into a unified tree. /// /// Servers answer with either `DocumentSymbol[]` (hierarchical) or @@ -751,11 +814,17 @@ fn parse_locations(result: &Value) -> Vec { .collect() } -fn parse_code_actions(result: &Value) -> Vec { +fn parse_code_actions( + result: &Value, + open_documents: &BTreeMap, +) -> Vec { let Some(values) = result.as_array() else { return Vec::new(); }; - let mut actions: Vec = values.iter().filter_map(parse_code_action).collect(); + let mut actions: Vec = values + .iter() + .filter_map(|action| parse_code_action(action, open_documents)) + .collect(); actions.sort_by_key(|action| { let preferred = action .get("isPreferred") @@ -788,7 +857,10 @@ fn code_action_group(kind: Option<&str>) -> &'static str { } } -fn parse_code_action(action: &Value) -> Option { +fn parse_code_action( + action: &Value, + open_documents: &BTreeMap, +) -> Option { if action.get("disabled").is_some_and(|value| !value.is_null()) { return None; } @@ -815,6 +887,12 @@ fn parse_code_action(action: &Value) -> Option { } else { action.get("command").and_then(parse_lsp_command) }; + // A code action must be applied as a unit. Never expose only the supported + // subset of a malformed or partly unsupported WorkspaceEdit. + let edit = match action.get("edit").filter(|edit| !edit.is_null()) { + Some(edit) => Some(WorkspaceEdit::parse(edit, open_documents).ok()?), + None => None, + }; Some(json!({ "title": title, "kind": kind, @@ -823,9 +901,7 @@ fn parse_code_action(action: &Value) -> Option { .get("isPreferred") .and_then(Value::as_bool) .unwrap_or(false), - "edit": action.get("edit").filter(|edit| !edit.is_null()).map(|edit| json!({ - "changes": parse_workspace_edit(edit) - })), + "edit": edit, "command": command, "data": action.get("data").cloned().unwrap_or(Value::Null) })) @@ -843,98 +919,6 @@ fn parse_lsp_command(value: &Value) -> Option { })) } -/// Validates and normalizes server-initiated `workspace/applyEdit` parameters. -/// -/// Outer `Err` rejects malformed JSON-RPC parameters (`-32602`). Inner `Err` -/// reports a valid `ApplyWorkspaceEditParams` that carries unsupported resource -/// operations or non-file URIs so the client replies `{ applied: false, failureReason }`. -pub(crate) fn parse_workspace_apply_edit( - params: Option<&Value>, -) -> Result, &'static str> { - let params = params - .and_then(Value::as_object) - .ok_or("Invalid workspace/applyEdit parameters")?; - let edit = params - .get("edit") - .and_then(Value::as_object) - .ok_or("workspace/applyEdit requires an edit object")?; - let label = params - .get("label") - .and_then(Value::as_str) - .map(str::trim) - .filter(|label| !label.is_empty()) - .map(|label| truncate_utf8_bytes(label, MAX_APPLY_EDIT_LABEL_BYTES)); - - let mut changes: serde_json::Map = serde_json::Map::new(); - if let Some(entries) = edit.get("changes") { - let Some(entries) = entries.as_object() else { - return Ok(Err("Workspace edit changes must be an object.")); - }; - for (uri, edits) in entries { - let Some(path) = file_path_for_uri(uri) else { - return Ok(Err("Workspace edit targets a non-file URI.")); - }; - let Some(raw_edits) = edits.as_array() else { - return Ok(Err("Workspace text edits must be an array.")); - }; - let mut parsed = Vec::with_capacity(raw_edits.len()); - for item in raw_edits { - if item.get("snippet").is_some() { - return Ok(Err("Snippet workspace edits are not supported.")); - } - let Some(edit_value) = parse_lsp_text_edit_value(item) else { - return Ok(Err("Workspace text edit is malformed.")); - }; - parsed.push(edit_value); - } - append_file_edits(&mut changes, path, parsed); - } - } - if let Some(document_changes) = edit.get("documentChanges") { - let Some(document_changes) = document_changes.as_array() else { - return Ok(Err("Workspace documentChanges must be an array.")); - }; - for change in document_changes { - let Some(change_obj) = change.as_object() else { - return Ok(Err("Workspace documentChange entry must be an object.")); - }; - if change_obj.get("kind").is_some() { - return Ok(Err( - "Resource create, rename, and delete operations are not supported.", - )); - } - let Some(uri) = change_obj - .get("textDocument") - .and_then(|document| document.get("uri")) - .and_then(Value::as_str) - else { - return Ok(Err("Workspace documentChange requires a textDocument URI.")); - }; - let Some(path) = file_path_for_uri(uri) else { - return Ok(Err("Workspace edit targets a non-file URI.")); - }; - let Some(raw_edits) = change_obj.get("edits").and_then(Value::as_array) else { - return Ok(Err("Workspace documentChange requires an edits array.")); - }; - let mut parsed = Vec::with_capacity(raw_edits.len()); - for item in raw_edits { - if item.get("snippet").is_some() { - return Ok(Err("Snippet workspace edits are not supported.")); - } - let Some(edit_value) = parse_lsp_text_edit_value(item) else { - return Ok(Err("Workspace text edit is malformed.")); - }; - parsed.push(edit_value); - } - append_file_edits(&mut changes, path, parsed); - } - } - Ok(Ok(json!({ - "label": label, - "changes": changes - }))) -} - fn append_file_edits( changes: &mut serde_json::Map, path: String, diff --git a/rust/crates/lsp-client/src/client/server_messages.rs b/rust/crates/lsp-client/src/client/server_messages.rs index 354d12a9..ecd0d1a7 100644 --- a/rust/crates/lsp-client/src/client/server_messages.rs +++ b/rust/crates/lsp-client/src/client/server_messages.rs @@ -42,7 +42,7 @@ pub fn client_apply_server_message_for_plugin( // silently drops every published diagnostic on Windows. // Match through the normalized form and publish under the // document's own canonical URI. - let document = open_document_for_published_uri(&state.open_documents, uri); + let document = open_document_for_server_uri(&state.open_documents, uri); let Some(document) = document else { return Ok(client_response(state, responses, events)); }; @@ -223,7 +223,7 @@ pub fn client_apply_server_message_for_plugin( }), )?); } else { - match parse_workspace_apply_edit(message.get("params")) { + match parse_workspace_apply_edit(message.get("params"), &state.open_documents) { Err(invalid) => { responses.push(json_rpc_error(id, -32602, invalid)?); } @@ -553,7 +553,11 @@ pub fn client_apply_server_message_for_plugin( message.get("result"), ) } else { - lsp_feature_result_for_method(pending.as_deref(), message.get("result")) + lsp_feature_result_for_method( + pending.as_deref(), + message.get("result"), + &state.open_documents, + ) }; events.push(LspClientEvent { kind: if message.get("error").is_some() { @@ -583,7 +587,7 @@ pub fn client_apply_server_message_for_plugin( /// lowercases the drive letter. A raw map lookup therefore misses even though /// the document is open. Comparison preserves URI component boundaries and /// folds the Windows drive letter while keeping Unix paths case-sensitive. -fn open_document_for_published_uri<'a>( +pub(super) fn open_document_for_server_uri<'a>( documents: &'a std::collections::BTreeMap, uri: &str, ) -> Option<&'a LspClientDocument> { diff --git a/rust/crates/lsp-client/src/client/workspace_edits.rs b/rust/crates/lsp-client/src/client/workspace_edits.rs new file mode 100644 index 00000000..329e8966 --- /dev/null +++ b/rust/crates/lsp-client/src/client/workspace_edits.rs @@ -0,0 +1,211 @@ +//! Validation of versioned LSP workspace edits before native application. + +use super::results::truncate_utf8_bytes; +use super::*; +use serde::Serialize; +use std::collections::BTreeMap; + +const MAX_APPLY_EDIT_LABEL_BYTES: usize = 256; + +/// Validates and normalizes server-initiated `workspace/applyEdit` parameters. +/// +/// Outer `Err` rejects malformed JSON-RPC parameters (`-32602`). Inner `Err` +/// reports a valid `ApplyWorkspaceEditParams` that carries unsupported resource +/// operations or non-file URIs so the client replies `{ applied: false, failureReason }`. +pub(super) fn parse_workspace_apply_edit( + params: Option<&Value>, + open_documents: &BTreeMap, +) -> Result, &'static str> { + let params = params + .and_then(Value::as_object) + .ok_or("Invalid workspace/applyEdit parameters")?; + let edit = params + .get("edit") + .filter(|edit| edit.is_object()) + .ok_or("workspace/applyEdit requires an edit object")?; + let label = params + .get("label") + .and_then(Value::as_str) + .map(str::trim) + .filter(|label| !label.is_empty()) + .map(|label| truncate_utf8_bytes(label, MAX_APPLY_EDIT_LABEL_BYTES)); + + Ok(WorkspaceEdit::parse(edit, open_documents).map(|edit| { + json!({ + "label": label, + "changes": edit.changes, + "documentVersions": edit.document_versions + }) + })) +} + +const MAX_WORKSPACE_EDIT_FILES: usize = 256; +const MAX_WORKSPACE_EDIT_EDITS: usize = 4096; +const MAX_WORKSPACE_EDIT_TEXT_BYTES: usize = 4 * 1024 * 1024; +const MAX_WORKSPACE_EDIT_URI_BYTES: usize = 4096; + +#[derive(Default, Serialize)] +#[serde(rename_all = "camelCase")] +pub(super) struct WorkspaceEdit { + changes: BTreeMap>, + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + document_versions: BTreeMap, + #[serde(skip)] + edit_count: usize, + #[serde(skip)] + text_bytes: usize, +} + +impl WorkspaceEdit { + pub(super) fn parse( + edit: &Value, + open_documents: &BTreeMap, + ) -> Result { + if !edit.is_object() { + return Err("Workspace edit must be an object."); + } + let mut result = Self::default(); + // The versioned form takes precedence when both representations arrive. + // Applying both would duplicate edits and drop their ordering semantics. + if let Some(changes) = edit.get("documentChanges") { + let changes = changes + .as_array() + .ok_or("Workspace documentChanges must be an array.")?; + for change in changes { + if !change.is_object() { + return Err("Workspace documentChange entry must be an object."); + } + if change.get("kind").is_some() { + return Err( + "Resource create, rename, and delete operations are not supported.", + ); + } + let document = change + .get("textDocument") + .and_then(Value::as_object) + .ok_or("Workspace documentChange requires a textDocument.")?; + let uri = document + .get("uri") + .and_then(Value::as_str) + .ok_or("Workspace documentChange requires a textDocument URI.")?; + let edits = change + .get("edits") + .and_then(Value::as_array) + .ok_or("Workspace documentChange requires an edits array.")?; + let version = document + .get("version") + .filter(|version| !version.is_null()) + .map(|version| { + version + .as_i64() + .ok_or("Workspace edit has an invalid document version.") + }) + .transpose()?; + result.insert(uri, version, edits, open_documents)?; + } + } else if let Some(changes) = edit.get("changes") { + let changes = changes + .as_object() + .ok_or("Workspace edit changes must be an object.")?; + for (uri, edits) in changes { + let edits = edits + .as_array() + .ok_or("Workspace text edits must be an array.")?; + result.insert(uri, None, edits, open_documents)?; + } + } + Ok(result) + } + + fn insert( + &mut self, + uri: &str, + version: Option, + edits: &[Value], + open_documents: &BTreeMap, + ) -> Result<(), &'static str> { + if self.changes.len() >= MAX_WORKSPACE_EDIT_FILES + || edits.len() > MAX_WORKSPACE_EDIT_EDITS - self.edit_count + { + return Err("Workspace edit exceeds the file or text edit limit."); + } + if uri.len() > MAX_WORKSPACE_EDIT_URI_BYTES { + return Err("Workspace edit target URI is too long."); + } + let path = file_path_for_uri(uri) + .filter(|path| !path.contains('\0')) + .ok_or("Workspace edit targets a non-file or invalid file URI.")?; + let path = if let Some(version) = version { + let document = + super::server_messages::open_document_for_server_uri(open_documents, uri) + .filter(|document| document.version > 0 && document.version == version) + .ok_or("Workspace edit targets an unknown or stale document version.")?; + // Use the identity Core already returned to the host, including + // Windows drive spelling if the language server normalized it. + let path = + file_path_for_uri(&document.uri).ok_or("Workspace edit targets a non-file URI.")?; + self.document_versions.insert(path.clone(), version); + path + } else { + path + }; + if self.changes.contains_key(&path) { + return Err("Workspace edit repeats a document target."); + } + let mut parsed = Vec::with_capacity(edits.len()); + for item in edits { + parsed.push(parse_bounded_text_edit( + item, + &mut self.text_bytes, + MAX_WORKSPACE_EDIT_TEXT_BYTES, + )?); + } + self.edit_count += parsed.len(); + self.changes.insert(path, parsed); + Ok(()) + } +} + +pub(super) fn parse_bounded_text_edit( + item: &Value, + text_bytes: &mut usize, + max_bytes: usize, +) -> Result { + if item.get("snippet").is_some() || item.get("annotationId").is_some() { + return Err("Snippet and annotated text edits are not supported."); + } + let new_text = item + .get("newText") + .and_then(Value::as_str) + .ok_or("Text edit is missing replacement text.")?; + *text_bytes = text_bytes + .checked_add(new_text.len()) + .filter(|bytes| *bytes <= max_bytes) + .ok_or("Edits exceed the replacement text limit.")?; + let range = item.get("range").ok_or("Text edit is missing a range.")?; + let start = text_edit_position(range, "start")?; + let end = text_edit_position(range, "end")?; + if start > end { + return Err("Text edit range is reversed."); + } + Ok(json!({ + "range": { + "start": {"line": start.0, "utf16Column": start.1}, + "end": {"line": end.0, "utf16Column": end.1} + }, + "newText": new_text + })) +} + +fn text_edit_position(range: &Value, end: &str) -> Result<(i32, i32), &'static str> { + let point = range.get(end); + let coordinate = |name| { + point.and_then(|point| { + let value = point.get(name)?.as_i64()?; + i32::try_from(value).ok().filter(|value| *value >= 0) + }) + }; + coordinate("line") + .zip(coordinate("character")) + .ok_or("Text edit contains an invalid position.") +} diff --git a/rust/crates/lsp-client/src/tests.rs b/rust/crates/lsp-client/src/tests.rs index b99a1ff5..695cb60e 100644 --- a/rust/crates/lsp-client/src/tests.rs +++ b/rust/crates/lsp-client/src/tests.rs @@ -2561,6 +2561,10 @@ fn client_editor_actions_signature_help_inlay_hints_and_apply_edit_match_fixture resolve_hint_wire["params"]["position"]["character"], json!(8) ); + assert_eq!( + resolve_hint_wire["params"]["label"], + fixture["inlayHints"]["serverResult"][2]["label"] + ); let refreshed = client_apply_server_message(ClientApplyServerMessageRequest { state: resolve_hint_req.state, @@ -2594,6 +2598,10 @@ fn client_editor_actions_signature_help_inlay_hints_and_apply_edit_match_fixture accepted_edit.events[0].result.as_ref().unwrap()["label"], json!("Apply quick fix") ); + assert_eq!( + accepted_edit.events[0].result.as_ref().unwrap()["documentVersions"], + fixture["workspaceApplyEdit"]["expectedDocumentVersions"] + ); let rejected_edit = client_apply_server_message(ClientApplyServerMessageRequest { state: accepted_edit.state, @@ -2614,3 +2622,57 @@ fn client_editor_actions_signature_help_inlay_hints_and_apply_edit_match_fixture fixture["workspaceApplyEdit"]["expectedRejectedFailureReason"] ); } + +#[test] +fn workspace_apply_edit_rejects_stale_versions_and_malformed_text_before_forwarding() { + let fixture: Value = serde_json::from_str(include_str!( + "../../../fixtures/lsp/editor-actions-hints-v1.json" + )) + .unwrap(); + let accepted = &fixture["workspaceApplyEdit"]["acceptedRequest"]; + let uri = "file:///workspace/main.rs"; + let opened = client_open_document(ClientOpenDocumentRequest { + state: LspClientState::default(), + uri: uri.to_string(), + language_id: "rust".to_string(), + text: "fn main() {}\n".to_string(), + }) + .unwrap(); + let mut stale = accepted.clone(); + stale["edit"]["documentChanges"][0]["textDocument"]["version"] = json!(2); + let mut missing_text = accepted.clone(); + missing_text["edit"]["documentChanges"][0]["edits"][0] + .as_object_mut() + .unwrap() + .remove("newText"); + let mut missing_position = accepted.clone(); + missing_position["edit"]["documentChanges"][0]["edits"][0]["range"]["start"] = + json!({ "line": 0 }); + let mut annotated = accepted.clone(); + annotated["edit"]["documentChanges"][0]["edits"][0]["annotationId"] = json!("approval"); + let mut repeated = accepted.clone(); + let repeated_target = repeated["edit"]["documentChanges"][0].clone(); + repeated["edit"]["documentChanges"] + .as_array_mut() + .unwrap() + .push(repeated_target); + for params in [stale, missing_text, missing_position, annotated, repeated] { + let response = client_apply_server_message(ClientApplyServerMessageRequest { + state: opened.state.clone(), + message: json!({ + "jsonrpc": "2.0", + "id": "edit-rejected", + "method": "workspace/applyEdit", + "params": params + }) + .to_string(), + }) + .unwrap(); + assert!( + response.events.is_empty(), + "unexpected host edit for {params}" + ); + let wire: Value = serde_json::from_str(&response.messages[0]).unwrap(); + assert_eq!(wire["result"]["applied"], json!(false)); + } +} diff --git a/rust/crates/lsp-client/src/types.rs b/rust/crates/lsp-client/src/types.rs index db61a5d1..d079eb08 100644 --- a/rust/crates/lsp-client/src/types.rs +++ b/rust/crates/lsp-client/src/types.rs @@ -22,6 +22,9 @@ pub struct LspInlayHintResponse { pub(crate) padding_right: bool, pub(crate) text_edits: Vec, pub(crate) data: Option, + /// Bounded original LSP object for a later inlayHint/resolve request. + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) resolve_payload: Option, } #[derive(Debug, Clone, Serialize)] diff --git a/rust/crates/lsp-engine/src/engine.rs b/rust/crates/lsp-engine/src/engine.rs index 11de9eda..60e1b8d2 100644 --- a/rust/crates/lsp-engine/src/engine.rs +++ b/rust/crates/lsp-engine/src/engine.rs @@ -249,7 +249,7 @@ impl LspEngine { request_timeout, shutdown_timeout, terminal_event_emitted: false, - deadline_cancellations: Vec::new(), + deadline_messages: Vec::new(), maintenance_write_deadline: None, plugin_server, relay_write_deadline: None, diff --git a/rust/crates/lsp-engine/src/events.rs b/rust/crates/lsp-engine/src/events.rs index 3c2f5360..14c21ace 100644 --- a/rust/crates/lsp-engine/src/events.rs +++ b/rust/crates/lsp-engine/src/events.rs @@ -200,6 +200,15 @@ pub(crate) fn push_semantic_tokens_refresh_event( } pub(crate) fn push_inlay_hints_refresh_event(session: &RuntimeSession, state: &mut SessionState) { + // One pending refresh covers every repeat until the host drains it. + if session.log_identity.role != SessionRole::LanguageServer + || state + .events + .iter() + .any(|event| event.kind == "inlayHintsRefresh") + { + return; + } let sequence = take_sequence(state); enqueue_runtime_event( session, @@ -596,13 +605,13 @@ pub(crate) fn clear_runtime_state(session: &RuntimeSession, state: &mut SessionS state.pending.clear(); state.request_by_operation.clear(); state.function_by_operation.clear(); - state.apply_edit_requests.clear(); + abandon_apply_edits(session, state, None); clear_function_registry(session, state); state.client.vcs_provider = None; state.client.toolchain_providers.clear(); state.client.keymap_import_providers.clear(); state.linked_document_paths = LinkedDocumentPaths::default(); - state.deadline_cancellations.clear(); + state.deadline_messages.clear(); state.maintenance_write_deadline = None; state.relay_write_deadline = None; state.pending_workspace_file_changes.clear(); diff --git a/rust/crates/lsp-engine/src/host_requests.rs b/rust/crates/lsp-engine/src/host_requests.rs index 4b14a20a..a57135c9 100644 --- a/rust/crates/lsp-engine/src/host_requests.rs +++ b/rust/crates/lsp-engine/src/host_requests.rs @@ -1,4 +1,4 @@ -//! Requests a plugin backend sends to the host: forwarding and cancellation. +//! Reverse requests that a process sends to the host: forwarding and cancellation. use super::*; @@ -140,10 +140,11 @@ pub(crate) fn forward_host_request_locked( Ok(Vec::new()) } -const MAX_PENDING_APPLY_EDIT_REQUESTS: usize = 32; +const MAX_PENDING_APPLY_EDIT_REQUESTS: usize = 8; /// Cancels a pending server-initiated `workspace/applyEdit` request on `$/cancelRequest`. pub(crate) fn cancel_apply_edit_request_locked( + session: &RuntimeSession, state: &mut SessionState, params: Option<&Value>, outbound: &mut Vec, @@ -154,57 +155,158 @@ pub(crate) fn cancel_apply_edit_request_locked( let Some(apply_edit_id) = state .apply_edit_requests .iter() - .find(|(_, pending)| *pending == server_id) + .find(|(_, pending)| &pending.server_id == server_id) .map(|(apply_edit_id, _)| apply_edit_id.clone()) else { return Ok(false); }; - let server_id = state + let pending = state .apply_edit_requests .remove(&apply_edit_id) - .unwrap_or(Value::Null); - outbound.push(json_rpc_error(&server_id, -32800, "Request cancelled")?); + .expect("the apply request was found under the same lock"); + revoke_apply_edit(session, state, &apply_edit_id); + outbound.push(json_rpc_error( + &pending.server_id, + -32800, + "Request cancelled", + )?); Ok(true) } +/// Removes expired host work and returns the protocol replies for the outbound worker. +pub(crate) fn expire_apply_edits( + session: &RuntimeSession, + state: &mut SessionState, + now: Instant, +) -> Vec { + let expired: Vec<_> = state + .apply_edit_requests + .iter() + .filter(|(_, request)| now >= request.deadline) + .map(|(id, _)| id.clone()) + .collect(); + expired + .into_iter() + .map(|id| { + let pending = state + .apply_edit_requests + .remove(&id) + .expect("the apply request was found under the same lock"); + revoke_apply_edit(session, state, &id); + rejected_apply_edit(&pending.server_id, "Workspace edit timed out.") + }) + .collect() +} + +/// Revokes queued and delivered requests. Graceful shutdown sends the replies; +/// a failed or exited process only needs the event-side cleanup. +pub(crate) fn abandon_apply_edits( + session: &RuntimeSession, + state: &mut SessionState, + mut outbound: Option<&mut Vec>, +) { + for (id, pending) in std::mem::take(&mut state.apply_edit_requests) { + revoke_apply_edit(session, state, &id); + if let Some(messages) = outbound.as_deref_mut() { + messages.push(rejected_apply_edit( + &pending.server_id, + "Language server session is shutting down.", + )); + } + } +} + +fn revoke_apply_edit(session: &RuntimeSession, state: &mut SessionState, id: &str) { + let queued = state.events.iter().position(|event| { + event.kind == "workspaceApplyEdit" + && event + .result + .as_ref() + .and_then(|result| result.get("applyEditId")) + .and_then(Value::as_str) + == Some(id) + }); + if let Some(index) = queued { + state.events.remove(index); + } else { + push_workspace_apply_edit_event( + session, + state, + "workspaceApplyEditCancelled", + json!({ "applyEditId": id }), + ); + } +} + +fn rejected_apply_edit(server_id: &Value, reason: &str) -> String { + json!({ + "jsonrpc": "2.0", + "id": server_id, + "result": { "applied": false, "failureReason": reason } + }) + .to_string() +} + /// Forwards a validated `workspace/applyEdit` request from the language server /// to the host as `workspaceApplyEdit`, or declines it immediately when the /// session is not ready or has reached the pending apply-edit cap. pub(crate) fn forward_apply_edit_locked( session: &RuntimeSession, state: &mut SessionState, - request: Value, + mut request: Value, ) -> Result, CoreError> { - let server_id = request.get("id").cloned().unwrap_or(Value::Null); - if state.lifecycle != LspLifecycleState::Ready || !state.client.initialized { - return Ok(vec![json_rpc_result( + let fields = request.as_object_mut().ok_or_else(|| { + CoreError::new( + ErrorCode::InvalidRequest, + "Workspace edit event is missing its payload.", + ) + })?; + let server_id = fields.remove("id").unwrap_or(Value::Null); + if session.log_identity.role != SessionRole::LanguageServer { + return Ok(vec![json_rpc_error( &server_id, - json!({ - "applied": false, - "failureReason": "Language server session is not ready." - }), + -32601, + "Workspace edits require a language-server session.", )?]); } + if state.lifecycle != LspLifecycleState::Ready || !state.client.initialized { + return Ok(vec![rejected_apply_edit( + &server_id, + "Language server session is not ready.", + )]); + } if state.apply_edit_requests.len() >= MAX_PENDING_APPLY_EDIT_REQUESTS { - return Ok(vec![json_rpc_result( + return Ok(vec![rejected_apply_edit( &server_id, - json!({ - "applied": false, - "failureReason": "Too many workspace edits are awaiting application." - }), - )?]); + "Too many workspace edits are awaiting application.", + )]); } let apply_edit_id = format!("apply-edit-{}", state.next_apply_edit_id); state.next_apply_edit_id += 1; - state - .apply_edit_requests - .insert(apply_edit_id.clone(), server_id); + state.apply_edit_requests.insert( + apply_edit_id.clone(), + PendingApplyEdit { + server_id, + deadline: Instant::now() + state.request_timeout, + }, + ); + fields.insert("applyEditId".to_string(), json!(apply_edit_id)); + push_workspace_apply_edit_event(session, state, "workspaceApplyEdit", request); + Ok(Vec::new()) +} + +fn push_workspace_apply_edit_event( + session: &RuntimeSession, + state: &mut SessionState, + kind: &str, + result: Value, +) { let sequence = take_sequence(state); enqueue_runtime_event( session, state, LspRuntimeEvent { - kind: "workspaceApplyEdit".to_string(), + kind: kind.to_string(), channel: None, plugin_id: None, role: None, @@ -220,11 +322,7 @@ pub(crate) fn forward_apply_edit_locked( uri: None, version: None, diagnostics: None, - result: Some(json!({ - "applyEditId": apply_edit_id, - "label": request.get("label").cloned().unwrap_or(Value::Null), - "changes": request.get("changes").cloned().unwrap_or_else(|| json!({})), - })), + result: Some(result), error: None, capabilities: None, completion_options: None, @@ -235,5 +333,4 @@ pub(crate) fn forward_apply_edit_locked( detail: None, }, ); - Ok(Vec::new()) } diff --git a/rust/crates/lsp-engine/src/lifecycle.rs b/rust/crates/lsp-engine/src/lifecycle.rs index 7f5bd8b5..17da34a0 100644 --- a/rust/crates/lsp-engine/src/lifecycle.rs +++ b/rust/crates/lsp-engine/src/lifecycle.rs @@ -26,7 +26,8 @@ impl RuntimeSession { None, ); clear_function_registry(self, &mut state); - state.apply_edit_requests.clear(); + let mut messages = std::mem::take(&mut state.deadline_messages); + abandon_apply_edits(self, &mut state, Some(&mut messages)); clear_runtime_diagnostics(self, &mut state); transition_locked(self, &mut state, LspLifecycleState::Stopping, None); plugin_operations::abandon(&self.startup_attempt); @@ -53,7 +54,8 @@ impl RuntimeSession { }, ); state.client = response.state; - (response.messages, false) + messages.extend(response.messages); + (messages, false) } else { state.client.pending_requests.clear(); state.pending.clear(); @@ -276,7 +278,7 @@ impl RuntimeSession { fn pump_outbound_maintenance(&self) { if !self .lock_state() - .is_ok_and(|state| !state.deadline_cancellations.is_empty()) + .is_ok_and(|state| !state.deadline_messages.is_empty()) { return; } @@ -286,13 +288,7 @@ impl RuntimeSession { let Ok(mut state) = self.lock_state() else { return; }; - let messages: Vec = std::mem::take(&mut state.deadline_cancellations) - .into_iter() - .map(|id| { - json!({ "jsonrpc": "2.0", "method": "$/cancelRequest", "params": { "id": id } }) - .to_string() - }) - .collect(); + let messages = std::mem::take(&mut state.deadline_messages); if messages.is_empty() { return; } @@ -313,7 +309,6 @@ impl RuntimeSession { pub(crate) fn expire_deadlines_at(&self, now: Instant) { // Relayed calls that no callee runs yet have no session deadline. self.relay.expire(now); - let mut cancellations = Vec::new(); let mut initialize_timeout = false; let mut shutdown_timeout = false; let mut maintenance_write_timeout = false; @@ -383,8 +378,17 @@ impl RuntimeSession { Some(error), ); } - cancellations.push(request_id); + state.deadline_messages.push( + json!({ + "jsonrpc": "2.0", + "method": "$/cancelRequest", + "params": { "id": request_id } + }) + .to_string(), + ); } + let expired_edits = expire_apply_edits(self, &mut state, now); + state.deadline_messages.extend(expired_edits); let held_expired = state .plugin_server .as_ref() @@ -467,16 +471,6 @@ impl RuntimeSession { } else if shutdown_timeout { self.kill_process(); } - if !cancellations.is_empty() { - if let Ok(mut state) = self.lock_state() { - if !matches!( - state.lifecycle, - LspLifecycleState::Stopped | LspLifecycleState::Failed - ) { - state.deadline_cancellations.extend(cancellations); - } - } - } } fn handle_process_exit(&self, exit_code: Option) { diff --git a/rust/crates/lsp-engine/src/operations.rs b/rust/crates/lsp-engine/src/operations.rs index dd8365eb..085ce777 100644 --- a/rust/crates/lsp-engine/src/operations.rs +++ b/rust/crates/lsp-engine/src/operations.rs @@ -523,7 +523,7 @@ impl RuntimeSession { let outbound_order = self.lock_outbound_order()?; let message = { let mut state = self.lock_state()?; - let server_id = state + let pending = state .apply_edit_requests .remove(&response.apply_edit_id) .ok_or_else(|| { @@ -547,7 +547,7 @@ impl RuntimeSession { json!(lithe_plugin_rpc::bounded_host_message(reason)); } } - json_rpc_result(&server_id, payload)? + json_rpc_result(&pending.server_id, payload)? }; self.send_messages_or_fail(&outbound_order, vec![message], "applyEditResponse") } diff --git a/rust/crates/lsp-engine/src/server_messages.rs b/rust/crates/lsp-engine/src/server_messages.rs index 3f6f760e..c3d9f297 100644 --- a/rust/crates/lsp-engine/src/server_messages.rs +++ b/rust/crates/lsp-engine/src/server_messages.rs @@ -452,6 +452,7 @@ impl RuntimeSession { } else if event.kind == "notification" && event.method.as_deref() == Some("$/cancelRequest") && cancel_apply_edit_request_locked( + self, &mut state, event.result.as_ref(), &mut outbound, diff --git a/rust/crates/lsp-engine/src/state.rs b/rust/crates/lsp-engine/src/state.rs index d2db5183..1532721c 100644 --- a/rust/crates/lsp-engine/src/state.rs +++ b/rust/crates/lsp-engine/src/state.rs @@ -55,6 +55,12 @@ pub(crate) struct PendingFunctionCall { pub(crate) request_id: String, } +/// A language-server workspace edit awaiting the native host's response. +pub(crate) struct PendingApplyEdit { + pub(crate) server_id: Value, + pub(crate) deadline: Instant, +} + pub(crate) struct SessionState { pub(crate) lifecycle: LspLifecycleState, pub(crate) client: LspClientState, @@ -76,8 +82,8 @@ pub(crate) struct SessionState { pub(crate) request_timeout: Duration, pub(crate) shutdown_timeout: Duration, pub(crate) terminal_event_emitted: bool, - /// Deadline cancellations awaiting the outbound worker, never written by the monitor. - pub(crate) deadline_cancellations: Vec, + /// Deadline messages awaiting the outbound worker, never written by the monitor. + pub(crate) deadline_messages: Vec, /// Bounds an outbound maintenance write independently of caller deadlines. pub(crate) maintenance_write_deadline: Option, /// Policy and waiting requests of a plugin-owned language server; `None` @@ -92,7 +98,7 @@ pub(crate) struct SessionState { pub(crate) next_host_request_id: u64, /// Server-initiated `workspace/applyEdit` requests awaiting `lsp.applyEditResponse`, /// keyed by the opaque `applyEditId` exposed to the host. - pub(crate) apply_edit_requests: BTreeMap, + pub(crate) apply_edit_requests: BTreeMap, pub(crate) next_apply_edit_id: u64, /// Trace is opt-in and serialized with protocol writes through outbound_order. pub(crate) detailed_diagnostics: bool, diff --git a/rust/crates/lsp-engine/src/tests.rs b/rust/crates/lsp-engine/src/tests.rs index dc1911d4..660cac82 100644 --- a/rust/crates/lsp-engine/src/tests.rs +++ b/rust/crates/lsp-engine/src/tests.rs @@ -6236,9 +6236,10 @@ fn session_signature_help_inlay_hints_refresh_and_workspace_apply_edit_round_tri "method": "workspace/inlayHint/refresh" })); harness.await_event(|event| event.kind == "inlayHintsRefresh"); - assert!(harness.server.messages().iter().any(|msg| { - msg.get("id") == Some(&json!("refresh-hints-1")) && msg.get("result") == Some(&Value::Null) - })); + assert_eq!( + harness.server.await_response("refresh-hints-1").unwrap()["result"], + Value::Null + ); // Server-initiated workspace/applyEdit -> host applyEditResponse round-trip. harness.server.send(json!({ @@ -6291,24 +6292,101 @@ fn session_signature_help_inlay_hints_refresh_and_workspace_apply_edit_round_tri } })); let second_seq = apply_event.sequence; - harness.await_event(|event| event.kind == "workspaceApplyEdit" && event.sequence > second_seq); + let pending_id = harness + .await_event(|event| event.kind == "workspaceApplyEdit" && event.sequence > second_seq) + .result + .as_ref() + .unwrap()["applyEditId"] + .as_str() + .unwrap() + .to_string(); harness.server.send(json!({ "jsonrpc": "2.0", "method": "$/cancelRequest", "params": { "id": "srv-apply-2" } })); - let deadline = Instant::now() + Duration::from_secs(5); - while Instant::now() < deadline { - if harness.server.messages().iter().any(|msg| { - msg.get("id") == Some(&json!("srv-apply-2")) - && msg.pointer("/error/code") == Some(&json!(-32800)) - }) { - break; - } - thread::sleep(Duration::from_millis(2)); - } - assert!(harness.server.messages().iter().any(|msg| { - msg.get("id") == Some(&json!("srv-apply-2")) - && msg.pointer("/error/code") == Some(&json!(-32800)) - })); + let cancelled = harness.await_event(|event| event.kind == "workspaceApplyEditCancelled"); + assert_eq!(cancelled.result, Some(json!({ "applyEditId": pending_id }))); + assert_eq!( + harness.server.await_response("srv-apply-2").unwrap()["error"]["code"], + json!(-32800) + ); + assert!(harness + .session() + .apply_edit_response(ApplyEditResponseRequest { + session_id: harness.session_id.clone(), + apply_edit_id: pending_id, + applied: true, + failure_reason: None, + }) + .is_err()); +} + +#[test] +fn workspace_apply_edit_revokes_queued_expired_and_stopping_requests() { + let mut harness = Harness::ready(); + let session = harness.session(); + let send_edit = |id| { + session + .handle_server_message( + json!({ + "jsonrpc": "2.0", + "id": id, + "method": "workspace/applyEdit", + "params": { "edit": { "changes": {} } } + }) + .to_string(), + ) + .unwrap(); + }; + send_edit("queued-edit"); + session + .handle_server_message( + json!({ + "jsonrpc": "2.0", + "method": "$/cancelRequest", + "params": { "id": "queued-edit" } + }) + .to_string(), + ) + .unwrap(); + assert_eq!( + harness.server.await_response("queued-edit").unwrap()["error"]["code"], + json!(-32800) + ); + assert!(!session + .poll_events() + .unwrap() + .iter() + .any(|event| event.kind.starts_with("workspaceApplyEdit"))); + + send_edit("expiring-edit"); + let request = harness.await_event(|event| event.kind == "workspaceApplyEdit"); + let request_id = request.result.as_ref().unwrap()["applyEditId"].clone(); + session.expire_deadlines_at(Instant::now() + Duration::from_secs(60)); + assert_eq!( + harness.server.await_response("expiring-edit").unwrap()["result"]["applied"], + json!(false) + ); + assert_eq!( + harness + .await_event(|event| event.kind == "workspaceApplyEditCancelled") + .result, + Some(json!({ "applyEditId": request_id })) + ); + + send_edit("stopping-edit"); + session.stop().unwrap(); + assert_eq!( + harness.server.await_response("stopping-edit").unwrap()["result"], + json!({ + "applied": false, + "failureReason": "Language server session is shutting down." + }) + ); + assert!(!session + .poll_events() + .unwrap() + .iter() + .any(|event| event.kind.starts_with("workspaceApplyEdit"))); } diff --git a/rust/fixtures/lsp/editor-actions-hints-v1.json b/rust/fixtures/lsp/editor-actions-hints-v1.json index 6b9f043b..af6158a4 100644 --- a/rust/fixtures/lsp/editor-actions-hints-v1.json +++ b/rust/fixtures/lsp/editor-actions-hints-v1.json @@ -198,6 +198,7 @@ ] } }, + "expectedDocumentVersions": { "/workspace/main.rs": 1 }, "rejectedResourceRequest": { "label": "Create file", "edit": { From dfa44f45c07a2f6df6e38a87985eabc759fc4094 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Wed, 18 Nov 2026 22:42:29 +0800 Subject: [PATCH 3/4] test(core): use the Result assertion for toolchain definitions --- rust/crates/core/src/tests/toolchain_definitions.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/rust/crates/core/src/tests/toolchain_definitions.rs b/rust/crates/core/src/tests/toolchain_definitions.rs index 0dfd7eef..3ac583a9 100644 --- a/rust/crates/core/src/tests/toolchain_definitions.rs +++ b/rust/crates/core/src/tests/toolchain_definitions.rs @@ -69,9 +69,8 @@ fn tool_definitions_declare_settings_category_and_audience() { tagged["audience"] = json!("plugin"); let mut plugin = manifest("dev.lithe.fixture.compiler", tagged); // The fields are toolDefinitions 1, so a host that supports only 0 never installs it. - let rejected = validate_manifest_value(plugin.clone()) - .err() - .expect("version 0 refuses settings categories"); + let rejected = + validate_manifest_value(plugin.clone()).expect_err("version 0 refuses settings categories"); assert_eq!(rejected.field.as_deref(), Some("requires.toolDefinitions")); plugin["requires"]["toolDefinitions"] = json!(1); assert!(validate_manifest_value(plugin.clone()).is_ok()); From c6083727ba2ee8d30adf868ac58cdd76ead0e713 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Wed, 18 Nov 2026 23:48:19 +0800 Subject: [PATCH 4/4] fix(lsp): preserve inlay registrations and signature selections --- rust/contracts/rust-core-api.md | 8 +- .../lsp-client/src/client/capabilities.rs | 51 +++++++--- rust/crates/lsp-client/src/client/results.rs | 69 ++++++++----- .../lsp-client/src/client/server_messages.rs | 15 +++ rust/crates/lsp-client/src/tests.rs | 98 +++++++++++++++++++ rust/crates/lsp-client/src/types.rs | 5 + rust/crates/lsp-engine/src/events.rs | 1 + .../fixtures/lsp/editor-actions-hints-v1.json | 8 +- 8 files changed, 209 insertions(+), 46 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 40876ed0..3df308ee 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -5601,12 +5601,16 @@ result). Its normalized result is `{ signatureHelp: null }` when no signature is documentation). Each parameter is normalized from either a substring label or UTF-16 `[start, end]` offsets into `{ label, utf16Start, utf16End, byteStart, byteEnd, documentation, isMarkdown }`, -and `activeSignature` / `activeParameter` are clamped into range. +and the original `activeSignature` / `activeParameter` selections are mapped to +the retained entries. Missing or out-of-range indices select the first retained +entry when one exists. The legacy top-level `activeParameter` is used only for +the active signature when that signature has no `activeParameter` of its own. Operation `inlayHints` (`textDocument/inlayHint`) sorts hints stably by `(line, utf16Column)`, trims labels to single-line text of at most 48 characters (with `…`), caps tooltips at 2048 bytes, and keeps at most 8 hints per line and -512 hints per viewport request. When the server advertises `inlayHintProvider.resolveProvider`, +512 hints per viewport request. When a static or dynamically registered provider +advertises `resolveProvider`, `featuresChanged` includes `inlayHintResolve` and `resolveInlayHint` (`inlayHint/resolve`) resolves a single hint (`{ hint }`). Pass back the normalized hint with its optional `resolvePayload` for this operation. Core uses that bounded original hint (at most 16 KiB) diff --git a/rust/crates/lsp-client/src/client/capabilities.rs b/rust/crates/lsp-client/src/client/capabilities.rs index 6b9f1743..b3993c78 100644 --- a/rust/crates/lsp-client/src/client/capabilities.rs +++ b/rust/crates/lsp-client/src/client/capabilities.rs @@ -165,12 +165,7 @@ pub(crate) fn feature_names_from_capabilities(capabilities: &Value) -> Vec) -> bool { + options.and_then(|options| options.get("resolveProvider")) == Some(&Value::Bool(true)) +} + +fn update_inlay_hint_features(state: &mut LspClientState) { + for (feature, enabled) in [ + ("inlayHints", !state.inlay_hint_providers.is_empty()), + ( + "inlayHintResolve", + state.inlay_hint_providers.values().any(|resolve| *resolve), + ), + ] { + if enabled { + insert_unique(&mut state.server_capabilities, feature); + } else { + state + .server_capabilities + .retain(|existing| existing != feature); + } + } +} + /// Signature-help trigger and retrigger characters the session's providers declared. /// /// Returns `{ "triggerCharacters": [...], "retriggerCharacters": [...] }`, each diff --git a/rust/crates/lsp-client/src/client/results.rs b/rust/crates/lsp-client/src/client/results.rs index ac66c40d..63ecf226 100644 --- a/rust/crates/lsp-client/src/client/results.rs +++ b/rust/crates/lsp-client/src/client/results.rs @@ -238,20 +238,27 @@ fn parse_signature_help(result: &Value) -> Option { return None; } let fallback_active_param = result.get("activeParameter").and_then(Value::as_u64); + let requested_active = result.get("activeSignature").and_then(Value::as_u64); let mut signatures = Vec::with_capacity(raw_signatures.len().min(MAX_SIGNATURES)); - for signature in raw_signatures.iter().take(MAX_SIGNATURES) { - if let Some(parsed) = parse_signature_information(signature, fallback_active_param) { + let mut active_signature = 0; + let mut active_fallback = None; + for (index, signature) in raw_signatures.iter().take(MAX_SIGNATURES).enumerate() { + if let Some((parsed, fallback)) = + parse_signature_information(signature, fallback_active_param) + { + if signatures.is_empty() || requested_active == Some(index as u64) { + active_signature = signatures.len(); + active_fallback = fallback; + } signatures.push(parsed); } } if signatures.is_empty() { return None; } - let requested_active = result - .get("activeSignature") - .and_then(Value::as_u64) - .unwrap_or(0) as usize; - let active_signature = requested_active.min(signatures.len() - 1); + if let Some(active_parameter) = active_fallback { + signatures[active_signature]["activeParameter"] = json!(active_parameter); + } let active_parameter = signatures[active_signature] .get("activeParameter") .cloned() @@ -334,7 +341,7 @@ fn normalize_single_line_with_boundaries( fn parse_signature_information( signature: &Value, fallback_active_param: Option, -) -> Option { +) -> Option<(Value, Option)> { let raw_label = signature.get("label")?.as_str()?; let (label, boundaries, label_truncated) = normalize_single_line_with_boundaries(raw_label, MAX_SIGNATURE_LABEL_CHARS); @@ -343,10 +350,16 @@ fn parse_signature_information( } let (documentation, is_markdown) = bounded_documentation(signature.get("documentation"), MAX_SIGNATURE_DOC_BYTES); + let active_field = signature.get("activeParameter"); + let requested = match active_field { + Some(value) => value.as_u64(), + None => fallback_active_param, + }; let mut parameters = Vec::new(); + let mut selected = 0; let mut search_from_byte = 0_usize; if let Some(raw_params) = signature.get("parameters").and_then(Value::as_array) { - for param in raw_params.iter().take(MAX_PARAMETERS) { + for (index, param) in raw_params.iter().take(MAX_PARAMETERS).enumerate() { if let Some(parsed) = parse_parameter_information( param, &label, @@ -354,28 +367,30 @@ fn parse_signature_information( label_truncated, &mut search_from_byte, ) { + if requested == Some(index as u64) { + selected = parameters.len(); + } parameters.push(parsed); } } } - let active_parameter = - if parameters.is_empty() || signature.get("activeParameter").is_some_and(Value::is_null) { - None - } else { - let raw_active = signature - .get("activeParameter") - .and_then(Value::as_u64) - .or(fallback_active_param) - .unwrap_or(0) as usize; - Some(raw_active.min(parameters.len() - 1)) - }; - Some(json!({ - "label": label, - "documentation": documentation, - "isMarkdown": is_markdown, - "parameters": parameters, - "activeParameter": active_parameter - })) + let has_active_parameter = !parameters.is_empty() && !active_field.is_some_and(Value::is_null); + // The legacy top-level index only belongs to the active signature. + let default_parameter = if active_field.is_none() { 0 } else { selected }; + let active_parameter = has_active_parameter.then_some(default_parameter); + let fallback_parameter = + (has_active_parameter && active_field.is_none() && fallback_active_param.is_some()) + .then_some(selected); + Some(( + json!({ + "label": label, + "documentation": documentation, + "isMarkdown": is_markdown, + "parameters": parameters, + "activeParameter": active_parameter + }), + fallback_parameter, + )) } fn parse_parameter_information( diff --git a/rust/crates/lsp-client/src/client/server_messages.rs b/rust/crates/lsp-client/src/client/server_messages.rs index ecd0d1a7..fe8e4865 100644 --- a/rust/crates/lsp-client/src/client/server_messages.rs +++ b/rust/crates/lsp-client/src/client/server_messages.rs @@ -517,6 +517,20 @@ pub fn client_apply_server_message_for_plugin( } _ => {} } + if let Some(options) = result + .get("capabilities") + .and_then(|capabilities| capabilities.get("inlayHintProvider")) + .filter(|options| options.is_object() || **options == Value::Bool(true)) + { + let id = options + .get("id") + .and_then(Value::as_str) + .unwrap_or_default(); + state.inlay_hint_providers.insert( + id.to_string(), + inlay_hint_registration_resolves(Some(options)), + ); + } if let Some(options) = result .get("capabilities") .and_then(|c| c.get("semanticTokensProvider")) @@ -538,6 +552,7 @@ pub fn client_apply_server_message_for_plugin( state.semantic_token_providers.clear(); state.completion_providers.clear(); state.signature_help_providers.clear(); + state.inlay_hint_providers.clear(); state.text_document_sync = LspTextDocumentSyncKind::Full; state.open_documents.clear(); state.diagnostics.clear(); diff --git a/rust/crates/lsp-client/src/tests.rs b/rust/crates/lsp-client/src/tests.rs index 695cb60e..acea62c5 100644 --- a/rust/crates/lsp-client/src/tests.rs +++ b/rust/crates/lsp-client/src/tests.rs @@ -2305,6 +2305,104 @@ fn client_completion_rejects_invalid_trigger_context() { } } +#[test] +fn inlay_hint_capabilities_track_independent_provider_registrations() { + for static_provider in [false, true] { + let initialized = client_initialize(ClientInitializeRequest { + state: LspClientState::default(), + root_uri: "file:///workspace".into(), + process_id: None, + initialization_options: None, + }) + .unwrap(); + let initialize: Value = serde_json::from_str(&initialized.messages[0]).unwrap(); + let mut state = client_apply_server_message(ClientApplyServerMessageRequest { + state: initialized.state, + message: json!({"jsonrpc": "2.0", "id": initialize["id"], "result": { + "capabilities": {"inlayHintProvider": static_provider} + }}) + .to_string(), + }) + .unwrap() + .state; + let apply = |state, id, method, params| { + client_apply_server_message(ClientApplyServerMessageRequest { + state, + message: json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}) + .to_string(), + }) + .unwrap() + .state + }; + state = apply( + state, + 2, + "client/registerCapability", + json!({"registrations": [ + {"id": "basic", "method": "textDocument/inlayHint"}, + {"id": "resolve", "method": "textDocument/inlayHint", "registerOptions": {"resolveProvider": true}} + ]}), + ); + let assert_features = |state: &LspClientState, hints, resolve| { + assert_eq!( + state.server_capabilities.iter().any(|f| f == "inlayHints"), + hints + ); + assert_eq!( + state + .server_capabilities + .iter() + .any(|f| f == "inlayHintResolve"), + resolve + ); + }; + assert_features(&state, true, true); + for (id, provider, enabled, resolve) in [ + (3, "unregistered-id", true, true), + (4, "resolve", true, false), + (5, "basic", static_provider, false), + ] { + state = apply( + state, + id, + "client/unregisterCapability", + json!({"unregisterations": [ + {"id": provider, "method": "textDocument/inlayHint"} + ]}), + ); + assert_features(&state, enabled, resolve); + } + } +} + +#[test] +fn signature_help_preserves_selected_indices_when_entries_are_filtered() { + let result = json!({ + "activeSignature": 1, + "activeParameter": 2, + "signatures": [ + {"label": " "}, + {"label": "selected(a, c)", "parameters": [ + {"label": "a"}, {"label": [5, 1]}, {"label": "c"} + ]}, + {"label": "other(x, y, z)", "parameters": [ + {"label": "x"}, {"label": "y"}, {"label": "z"} + ]} + ] + }); + let normalized = lsp_feature_result_for_method( + Some("textDocument/signatureHelp"), + Some(&result), + &Default::default(), + ) + .unwrap(); + let help = &normalized["signatureHelp"]; + assert_eq!(help["activeSignature"], 0); + assert_eq!(help["activeParameter"], 1); + assert_eq!(help["signatures"][0]["parameters"][1]["label"], "c"); + assert_eq!(help["signatures"][1]["activeParameter"], 0); +} + #[test] fn client_editor_actions_signature_help_inlay_hints_and_apply_edit_match_fixture() { let fixture: Value = serde_json::from_str(include_str!( diff --git a/rust/crates/lsp-client/src/types.rs b/rust/crates/lsp-client/src/types.rs index d079eb08..0b4f4e24 100644 --- a/rust/crates/lsp-client/src/types.rs +++ b/rust/crates/lsp-client/src/types.rs @@ -127,6 +127,10 @@ pub struct LspClientState { /// capability under the empty id, dynamic registrations under their own ids. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub signature_help_providers: BTreeMap, + /// Inlay hint registrations and their resolve support, keyed by registration id. + /// The static capability uses the empty id if the server provided no id. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub inlay_hint_providers: BTreeMap, /// Full semantic-token registrations, including the server-owned legends. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub semantic_token_providers: BTreeMap, @@ -197,6 +201,7 @@ impl Default for LspClientState { server_capabilities: Vec::new(), completion_providers: BTreeMap::new(), signature_help_providers: BTreeMap::new(), + inlay_hint_providers: BTreeMap::new(), semantic_token_providers: BTreeMap::new(), text_document_sync: LspTextDocumentSyncKind::Full, text_document_save_include_text: None, diff --git a/rust/crates/lsp-engine/src/events.rs b/rust/crates/lsp-engine/src/events.rs index 14c21ace..1af22a30 100644 --- a/rust/crates/lsp-engine/src/events.rs +++ b/rust/crates/lsp-engine/src/events.rs @@ -600,6 +600,7 @@ pub(crate) fn clear_runtime_state(session: &RuntimeSession, state: &mut SessionS state.client.server_capabilities.clear(); state.client.completion_providers.clear(); state.client.signature_help_providers.clear(); + state.client.inlay_hint_providers.clear(); state.client.open_documents.clear(); state.client.pending_requests.clear(); state.pending.clear(); diff --git a/rust/fixtures/lsp/editor-actions-hints-v1.json b/rust/fixtures/lsp/editor-actions-hints-v1.json index af6158a4..03435b41 100644 --- a/rust/fixtures/lsp/editor-actions-hints-v1.json +++ b/rust/fixtures/lsp/editor-actions-hints-v1.json @@ -107,7 +107,7 @@ "label": "add(int, int) -> int", "documentation": "Adds two integers.", "isMarkdown": false, - "activeParameter": 1, + "activeParameter": 0, "parameters": [ { "label": "int", @@ -133,7 +133,7 @@ "label": "日志(🧪 msg: str, 值: i32)", "documentation": "记录结构化日志", "isMarkdown": true, - "activeParameter": 1, + "activeParameter": 0, "parameters": [ { "label": "🧪 msg: str", @@ -156,8 +156,8 @@ ] } ], - "activeSignature": 1, - "activeParameter": 1 + "activeSignature": 0, + "activeParameter": 0 } }, "inlayHints": {