From f03ffaafc8c37e22a243c7c1bb5fbe3ce19fbff0 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Mon, 16 Nov 2026 10:47:47 +0800 Subject: [PATCH] feat(lsp-engine): keep hover answers so resting on a symbol again answers at once Refs 1lck/Lithe-IDEA#1995. Every hover went to the language server, so resting on the same symbol again waited for the server a second time. The LSP engine now keeps each session's hover answers in a bounded cache (HOVER_CACHE_CAPACITY = 32, least recently used first; answers over HOVER_CACHE_MAX_CONTENT_BYTES = 64 KiB are not kept). A host hover for the same document version and position, or for a position inside the answer's same-line range, completes from the cache without writing textDocument/hover. Empty answers, errors, and answers that arrive after a clear are delivered but not kept. Every kept answer is forgotten when anything can change what the server knows: document open/change/save/close, workspace file changes, configuration or indexing-exclusion changes, executeCommand, plugin backend languageServer requests and notifications, host notifications, any request from the server, the end of a $/progress, and session stop. A generation counter refuses answers the server computed before such a clear. Documents the behaviour in the contract README, the languages reference and the protocol changelog; the requestCompleted result shape is unchanged. --- rust/crates/lsp-engine/src/configuration.rs | 4 +- rust/crates/lsp-engine/src/documents.rs | 6 +- rust/crates/lsp-engine/src/engine.rs | 2 + rust/crates/lsp-engine/src/events.rs | 1 + rust/crates/lsp-engine/src/hover_cache.rs | 242 ++++++++++++ rust/crates/lsp-engine/src/lib.rs | 2 + rust/crates/lsp-engine/src/lifecycle.rs | 1 + rust/crates/lsp-engine/src/operations.rs | 42 +- .../lsp-engine/src/plugin_server_calls.rs | 5 + rust/crates/lsp-engine/src/server_messages.rs | 11 + rust/crates/lsp-engine/src/state.rs | 5 + rust/crates/lsp-engine/src/tests.rs | 370 +++++++++++++++++- shared/plugins/contract/v1/README.md | 17 + shared/plugins/reference/domains/languages.md | 4 + .../plugins/reference/protocol-changelog.md | 6 + 15 files changed, 711 insertions(+), 7 deletions(-) create mode 100644 rust/crates/lsp-engine/src/hover_cache.rs diff --git a/rust/crates/lsp-engine/src/configuration.rs b/rust/crates/lsp-engine/src/configuration.rs index d48d64a0..9628d278 100644 --- a/rust/crates/lsp-engine/src/configuration.rs +++ b/rust/crates/lsp-engine/src/configuration.rs @@ -132,6 +132,7 @@ pub(crate) fn apply_indexing_to_sessions( let order = session.lock_outbound_order()?; if session.lock_state()?.client.initialized { if let Some(configuration) = session.plugin_configuration() { + session.lock_state()?.hover_cache.clear(); session.send_messages_or_fail( &order, vec![plugin_configuration_notification(&configuration)], @@ -171,7 +172,7 @@ impl RuntimeSession { let configuration = Arc::new(configuration); let outbound_order = self.lock_outbound_order()?; let initialized = { - let state = self.lock_state()?; + let mut state = self.lock_state()?; if matches!( state.lifecycle, LspLifecycleState::Stopping @@ -183,6 +184,7 @@ impl RuntimeSession { "The language session is no longer running.", )); } + state.hover_cache.clear(); // Under `outbound_order`, an uninitialized client sends the stored // configuration with its `initialized` notification instead. state.client.initialized diff --git a/rust/crates/lsp-engine/src/documents.rs b/rust/crates/lsp-engine/src/documents.rs index 917cda03..5777e6ca 100644 --- a/rust/crates/lsp-engine/src/documents.rs +++ b/rust/crates/lsp-engine/src/documents.rs @@ -7,7 +7,7 @@ impl RuntimeSession { pub(crate) fn save_document(&self, request: SaveDocumentRequest) -> Result { let outbound_order = self.lock_outbound_order()?; let message = { - let state = self.lock_state()?; + let mut state = self.lock_state()?; ensure_not_terminal(state.lifecycle)?; if state.lifecycle != LspLifecycleState::Ready { return Ok(false); @@ -24,6 +24,7 @@ impl RuntimeSession { if *document.text != request.text { return Ok(false); } + state.hover_cache.clear(); let mut params = json!({"textDocument": {"uri": request.uri}}); if include_text { params["text"] = json!(request.text); @@ -66,6 +67,7 @@ impl RuntimeSession { let message = { let mut state = self.lock_state()?; ensure_not_terminal(state.lifecycle)?; + state.hover_cache.clear(); if !state.client.initialized { state.pending_workspace_file_changes.extend(normalized); return Ok(()); @@ -114,6 +116,7 @@ impl RuntimeSession { }); } } + state.hover_cache.clear(); if state.client.initialized { let response = if state .client @@ -197,6 +200,7 @@ impl RuntimeSession { "Cannot close a document that is not owned by the language-server session.", )); }; + state.hover_cache.clear(); cleared = state.client.diagnostics.contains_key(uri); if document.version == 0 { state.client.open_documents.remove(uri); diff --git a/rust/crates/lsp-engine/src/engine.rs b/rust/crates/lsp-engine/src/engine.rs index f6072498..e49f0416 100644 --- a/rust/crates/lsp-engine/src/engine.rs +++ b/rust/crates/lsp-engine/src/engine.rs @@ -210,6 +210,7 @@ impl LspEngine { method: "initialize".to_string(), document_uri: None, document_version: None, + hover: None, created_at: now, deadline: now + initialize_timeout, }, @@ -236,6 +237,7 @@ impl LspEngine { rejected_plugin_diagnostics: false, plugin_diagnostics_window: Instant::now(), plugin_diagnostics_count: 0, + hover_cache: HoverCache::default(), }), event_signal: Condvar::new(), process: process.handle, diff --git a/rust/crates/lsp-engine/src/events.rs b/rust/crates/lsp-engine/src/events.rs index 2784e231..bf2c7a6a 100644 --- a/rust/crates/lsp-engine/src/events.rs +++ b/rust/crates/lsp-engine/src/events.rs @@ -562,6 +562,7 @@ pub(crate) fn clear_runtime_state(session: &RuntimeSession, state: &mut SessionS state.maintenance_write_deadline = None; state.relay_write_deadline = None; state.pending_workspace_file_changes.clear(); + state.hover_cache.clear(); state.initialize_deadline = None; state.shutdown_deadline = None; push_features_event(session, state, Vec::new()); diff --git a/rust/crates/lsp-engine/src/hover_cache.rs b/rust/crates/lsp-engine/src/hover_cache.rs new file mode 100644 index 00000000..f3e1b2b6 --- /dev/null +++ b/rust/crates/lsp-engine/src/hover_cache.rs @@ -0,0 +1,242 @@ +//! Hover answers a session already received, so resting on a symbol again answers at +//! once instead of asking the language server a second time. +//! +//! An answer is reused only for the same document version and a position the answer +//! covers. Anything that can change what the server knows clears every answer, not +//! only those of one document: an edit in one file changes the hover shown for its +//! symbols in every other file. + +use super::*; + +/// Most answers one session keeps; the least recently used one goes first. +pub(crate) const HOVER_CACHE_CAPACITY: usize = 32; + +/// Longest hover text, in bytes, worth keeping. A longer answer is still delivered +/// but asked for again next time, which bounds a session's cache to +/// `HOVER_CACHE_CAPACITY * HOVER_CACHE_MAX_CONTENT_BYTES` of hover text. +pub(crate) const HOVER_CACHE_MAX_CONTENT_BYTES: usize = 64 * 1024; + +/// Zero-based LSP line and UTF-16 column, ordered line first. +type Point = (i64, i64); + +/// What a hover request in flight needs to keep its answer. +#[derive(Debug, Clone)] +pub(crate) struct HoverRequest { + /// Document version the request was sent for; the answer describes that text. + pub(crate) version: i64, + pub(crate) position: Point, + /// Cache generation when the request was sent. The answer is kept only if + /// nothing cleared the cache before it arrived, because the server may have + /// computed it from what it knew before the change. + pub(crate) generation: u64, +} + +/// One kept answer. +struct HoverEntry { + uri: String, + version: i64, + position: Point, + /// Same-line half-open column span `(line, start, end)` the server gave as the + /// answer's range, when that range contains `position`. Any position inside it + /// shows this answer, the way editors keep a hover open across its range. + span: Option<(i64, i64, i64)>, + /// The `requestCompleted` result exactly as the host received it. + result: Value, +} + +impl HoverEntry { + fn covers(&self, uri: &str, version: i64, position: Point) -> bool { + if self.uri != uri || self.version != version { + return false; + } + position == self.position + || self.span.is_some_and(|(line, start, end)| { + position.0 == line && start <= position.1 && position.1 < end + }) + } +} + +/// Hover answers of one session, owned by its `SessionState`. +#[derive(Default)] +pub(crate) struct HoverCache { + /// Advances on every clear; see `HoverRequest::generation`. + generation: u64, + /// Least recently used first. + entries: VecDeque, +} + +impl HoverCache { + /// Forgets every answer. Called whenever the server may know something it did + /// not know when it answered: a document opened, changed, saved or closed, files + /// changed on disk, settings changed, a command ran, a plugin backend was + /// notified or sent the server its own request, or the server asked the client + /// for something or finished a piece of work. + pub(crate) fn clear(&mut self) { + self.entries.clear(); + self.generation = self.generation.wrapping_add(1); + } + + /// The answer kept for `position` in this version of the document, marked as + /// the most recently used. + pub(crate) fn lookup(&mut self, uri: &str, version: i64, position: Point) -> Option { + let index = self + .entries + .iter() + .rposition(|entry| entry.covers(uri, version, position))?; + let entry = self.entries.remove(index)?; + let result = entry.result.clone(); + self.entries.push_back(entry); + Some(result) + } + + /// Describes a hover request about to be sent for `position`. + pub(crate) fn request(&self, version: i64, position: Point) -> HoverRequest { + HoverRequest { + version, + position, + generation: self.generation, + } + } + + /// Keeps the answer to `request`. An empty or oversized answer, or one the + /// server computed before the cache was last cleared, is not kept: an empty + /// answer can turn into a real one once the server has loaded the project. + pub(crate) fn store(&mut self, uri: &str, request: &HoverRequest, result: &Value) { + if request.generation != self.generation { + return; + } + let Some(hover) = result.get("hover").filter(|hover| hover.is_object()) else { + return; + }; + let Some(contents) = hover.get("contents").and_then(Value::as_str) else { + return; + }; + if contents.trim().is_empty() || contents.len() > HOVER_CACHE_MAX_CONTENT_BYTES { + return; + } + let span = same_line_span(hover.get("range")).filter(|(line, start, end)| { + request.position.0 == *line && *start <= request.position.1 && request.position.1 < *end + }); + self.entries.retain(|entry| { + !(entry.uri == uri + && entry.version == request.version + && entry.position == request.position) + }); + self.entries.push_back(HoverEntry { + uri: uri.to_string(), + version: request.version, + position: request.position, + span, + result: result.clone(), + }); + while self.entries.len() > HOVER_CACHE_CAPACITY { + self.entries.pop_front(); + } + } +} + +/// A hover range from `lithe_lsp_client` (`{start, end}` of `{line, utf16Column}`) +/// as `(line, start, end)`, when it is a non-empty span on one line. A range over +/// several lines is not used to answer other positions: it can enclose other +/// symbols with hovers of their own. +fn same_line_span(range: Option<&Value>) -> Option<(i64, i64, i64)> { + let range = range?; + let point = |key: &str| -> Option { + let position = range.get(key)?; + Some(( + position.get("line")?.as_i64()?, + position.get("utf16Column")?.as_i64()?, + )) + }; + let (start, end) = (point("start")?, point("end")?); + (start.0 == end.0 && start.1 < end.1).then_some((start.0, start.1, end.1)) +} + +/// Whether a message the server sent may mean it knows something new: any request +/// it makes of the client (refreshes, edits, capability changes, configuration +/// pulls, progress tokens) and the end of a piece of work such as loading the +/// workspace. +pub(crate) fn server_message_clears_hovers(value: &Value) -> bool { + let Some(method) = value.get("method").and_then(Value::as_str) else { + return false; + }; + value.get("id").is_some() + || (method == "$/progress" + && value.pointer("/params/value/kind").and_then(Value::as_str) == Some("end")) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn answer(contents: &str) -> Value { + json!({ "hover": { "contents": contents, "isMarkdown": false, "range": null } }) + } + + fn keep(cache: &mut HoverCache, line: i64) { + let request = cache.request(1, (line, 0)); + cache.store("file:///a.go", &request, &answer(&format!("line {line}"))); + } + + #[test] + fn the_least_recently_used_answer_goes_first_at_capacity() { + let mut cache = HoverCache::default(); + for line in 0..HOVER_CACHE_CAPACITY as i64 { + keep(&mut cache, line); + } + // Reading line 0 makes line 1 the oldest. + assert!(cache.lookup("file:///a.go", 1, (0, 0)).is_some()); + keep(&mut cache, HOVER_CACHE_CAPACITY as i64); + assert_eq!(cache.entries.len(), HOVER_CACHE_CAPACITY); + assert!(cache.lookup("file:///a.go", 1, (1, 0)).is_none()); + assert!(cache.lookup("file:///a.go", 1, (0, 0)).is_some()); + assert!(cache + .lookup("file:///a.go", 1, (HOVER_CACHE_CAPACITY as i64, 0)) + .is_some()); + } + + #[test] + fn an_answer_is_kept_once_per_position_and_only_for_its_document_version() { + let mut cache = HoverCache::default(); + keep(&mut cache, 3); + keep(&mut cache, 3); + assert_eq!(cache.entries.len(), 1); + assert!(cache.lookup("file:///a.go", 2, (3, 0)).is_none()); + assert!(cache.lookup("file:///b.go", 1, (3, 0)).is_none()); + assert_eq!( + cache.lookup("file:///a.go", 1, (3, 0)), + Some(answer("line 3")) + ); + } + + #[test] + fn a_clear_forgets_answers_and_refuses_ones_requested_before_it() { + let mut cache = HoverCache::default(); + keep(&mut cache, 0); + let in_flight = cache.request(1, (5, 0)); + cache.clear(); + assert!(cache.lookup("file:///a.go", 1, (0, 0)).is_none()); + cache.store("file:///a.go", &in_flight, &answer("stale")); + assert!(cache.entries.is_empty()); + } + + #[test] + fn only_server_requests_and_finished_work_clear_answers() { + let clears = |message: Value| server_message_clears_hovers(&message); + assert!(clears( + json!({ "id": 1, "method": "workspace/codeLens/refresh" }) + )); + assert!(clears(json!({ + "method": "$/progress", + "params": { "token": "t", "value": { "kind": "end" } } + }))); + assert!(!clears(json!({ + "method": "$/progress", + "params": { "token": "t", "value": { "kind": "report" } } + }))); + assert!(!clears( + json!({ "method": "textDocument/publishDiagnostics", "params": {} }) + )); + assert!(!clears(json!({ "id": 1, "result": null }))); + } +} diff --git a/rust/crates/lsp-engine/src/lib.rs b/rust/crates/lsp-engine/src/lib.rs index b5b7f3f8..ea3203be 100644 --- a/rust/crates/lsp-engine/src/lib.rs +++ b/rust/crates/lsp-engine/src/lib.rs @@ -78,6 +78,7 @@ mod engine; mod events; mod function_calls; mod host_requests; +mod hover_cache; mod lifecycle; mod operations; mod plugin_server_calls; @@ -93,6 +94,7 @@ use engine::*; use events::*; use function_calls::*; use host_requests::*; +use hover_cache::*; use lifecycle::*; use operations::*; use plugin_server_calls::*; diff --git a/rust/crates/lsp-engine/src/lifecycle.rs b/rust/crates/lsp-engine/src/lifecycle.rs index c134ce14..80fa4894 100644 --- a/rust/crates/lsp-engine/src/lifecycle.rs +++ b/rust/crates/lsp-engine/src/lifecycle.rs @@ -46,6 +46,7 @@ impl RuntimeSession { method: "shutdown".to_string(), document_uri: None, document_version: None, + hover: None, created_at: now, deadline: now + shutdown_timeout, }, diff --git a/rust/crates/lsp-engine/src/operations.rs b/rust/crates/lsp-engine/src/operations.rs index 30dc7895..c925718b 100644 --- a/rust/crates/lsp-engine/src/operations.rs +++ b/rust/crates/lsp-engine/src/operations.rs @@ -123,6 +123,7 @@ impl RuntimeSession { method: request.method, document_uri: None, document_version: None, + hover: None, created_at: now, deadline: now + timeout, }, @@ -206,6 +207,7 @@ impl RuntimeSession { method: lithe_lsp_client::keymap_provider::IMPORT_METHOD.to_string(), document_uri: None, document_version: None, + hover: None, created_at: now, deadline: now + timeout, }, @@ -275,6 +277,7 @@ impl RuntimeSession { method: lithe_lsp_client::toolchain_provider::QUERY_METHOD.to_string(), document_uri: None, document_version: None, + hover: None, created_at: now, deadline: now + timeout, }, @@ -349,6 +352,7 @@ impl RuntimeSession { method: planned.method.to_string(), document_uri: None, document_version: None, + hover: None, created_at: now, deadline: now + timeout, }, @@ -439,6 +443,7 @@ impl RuntimeSession { method: lithe_plugin_rpc::INVOKE_METHOD.to_string(), document_uri: None, document_version: None, + hover: None, created_at: now, deadline: now + timeout, }, @@ -518,7 +523,7 @@ impl RuntimeSession { ) -> Result { let outbound_order = self.lock_outbound_order()?; let message = { - let state = self.lock_state()?; + let mut state = self.lock_state()?; if self.plugin_id.is_none() { return Err(CoreError::new( ErrorCode::InvalidRequest, @@ -540,6 +545,7 @@ impl RuntimeSession { if !delivered { return Ok(false); } + state.hover_cache.clear(); json_rpc_notification(¬ification.method, notification.params)? }; self.send_messages_or_fail(&outbound_order, vec![message], "hostNotify")?; @@ -633,6 +639,7 @@ impl RuntimeSession { } let message = json_rpc_notification(&request.method, request.params)?; let outbound_order = self.lock_outbound_order()?; + self.lock_state()?.hover_cache.clear(); self.send_messages_or_fail(&outbound_order, vec![message], "pluginServerNotify")?; Ok(true) } @@ -701,6 +708,38 @@ impl RuntimeSession { } } + let mut hover = None; + if request.operation == LspSemanticOperation::Hover + && requested_kind == PendingKind::Feature + { + let open_version = uri + .as_deref() + .and_then(|uri| state.client.open_documents.get(uri)) + .map(|document| document.version) + .filter(|version| *version > 0); + if let (Some(document_uri), Some(version), Some(position)) = + (uri.as_deref(), open_version, request.position) + { + let position = (position.line, position.utf16_column); + if let Some(result) = state.hover_cache.lookup(document_uri, version, position) + { + push_request_event( + self, + &mut state, + &operation_id, + method, + Some(result), + None, + ); + return Ok(()); + } + hover = Some(state.hover_cache.request(version, position)); + } + } + if request.operation == LspSemanticOperation::ExecuteCommand { + state.hover_cache.clear(); + } + let pending_kind = requested_kind; let response = match request.operation { LspSemanticOperation::WorkspaceSymbols => { @@ -765,6 +804,7 @@ impl RuntimeSession { .and_then(|uri| state.client.open_documents.get(uri)) .map(|document| document.version) }), + hover, created_at: now, deadline: now + state.request_timeout, }; diff --git a/rust/crates/lsp-engine/src/plugin_server_calls.rs b/rust/crates/lsp-engine/src/plugin_server_calls.rs index 4ef74a1e..4784a582 100644 --- a/rust/crates/lsp-engine/src/plugin_server_calls.rs +++ b/rust/crates/lsp-engine/src/plugin_server_calls.rs @@ -66,6 +66,9 @@ pub(crate) fn plugin_server_timeout(requested: Option) -> Duration { /// Allocates the JSON-RPC request of an admitted operation and records it as /// pending. Returns the messages to write and the request ID. +/// +/// A backend's request can be a command that changes what the server knows, and +/// its method alone does not say whether it is, so kept hovers are forgotten. pub(crate) fn register_plugin_server_request( state: &mut SessionState, operation_id: &str, @@ -74,6 +77,7 @@ pub(crate) fn register_plugin_server_request( created_at: Instant, deadline: Instant, ) -> Result<(Vec, String), CoreError> { + state.hover_cache.clear(); let response = allocate_raw_request(state.client.clone(), method, params)?; let request_id = (response.state.next_request_id - 1).to_string(); state.client = response.state; @@ -85,6 +89,7 @@ pub(crate) fn register_plugin_server_request( method: method.to_string(), document_uri: None, document_version: None, + hover: None, created_at, deadline, }, diff --git a/rust/crates/lsp-engine/src/server_messages.rs b/rust/crates/lsp-engine/src/server_messages.rs index 0f93ace9..a7c12dba 100644 --- a/rust/crates/lsp-engine/src/server_messages.rs +++ b/rust/crates/lsp-engine/src/server_messages.rs @@ -82,6 +82,9 @@ impl RuntimeSession { } } after_policy_check(); + if server_message_clears_hovers(&value) { + self.lock_state()?.hover_cache.clear(); + } if method == Some("workspace/configuration") { if let Some(response) = self.provider_configuration_response(&value)? { return self.send_messages_or_fail( @@ -323,6 +326,14 @@ impl RuntimeSession { } else { result }; + if let (Some(hover), Some(uri), None, Some(result)) = ( + pending.hover.as_ref(), + pending.document_uri.as_deref(), + error.as_ref(), + result.as_ref(), + ) { + state.hover_cache.store(uri, hover, result); + } push_request_event( self, &mut state, diff --git a/rust/crates/lsp-engine/src/state.rs b/rust/crates/lsp-engine/src/state.rs index 9ae07df2..deb226f0 100644 --- a/rust/crates/lsp-engine/src/state.rs +++ b/rust/crates/lsp-engine/src/state.rs @@ -42,6 +42,8 @@ pub(crate) struct PendingRequest { pub(crate) document_uri: Option, /// Document version observed when a presentation request was allocated. pub(crate) document_version: Option, + /// Set for a host hover whose answer may be kept in `SessionState::hover_cache`. + pub(crate) hover: Option, pub(crate) created_at: Instant, pub(crate) deadline: Instant, } @@ -97,6 +99,9 @@ pub(crate) struct SessionState { /// Sender-side ingress budget uses the existing process clock, never a timer. pub(crate) plugin_diagnostics_window: Instant, pub(crate) plugin_diagnostics_count: u16, + /// Hover answers reused for a position the server already described; bounded + /// by `HOVER_CACHE_CAPACITY` and emptied whenever the server may know more. + pub(crate) hover_cache: HoverCache, } pub(crate) struct RuntimeSession { diff --git a/rust/crates/lsp-engine/src/tests.rs b/rust/crates/lsp-engine/src/tests.rs index 180f323c..a1541b65 100644 --- a/rust/crates/lsp-engine/src/tests.rs +++ b/rust/crates/lsp-engine/src/tests.rs @@ -326,6 +326,17 @@ impl Harness { /// Issues a feature request and returns its opaque operation ID. fn request(&self, operation: LspSemanticOperation, uri: &str) -> String { + self.request_at(operation, uri, 0, 0) + } + + /// Issues a feature request at a position and returns its opaque operation ID. + fn request_at( + &self, + operation: LspSemanticOperation, + uri: &str, + line: i64, + utf16_column: i64, + ) -> String { let operation_id = self.engine.next_operation_id(); self.session() .request( @@ -335,10 +346,7 @@ impl Harness { operation_id: Some(operation_id.clone()), operation, uri: Some(uri.to_string()), - position: Some(LspPosition { - line: 0, - utf16_column: 0, - }), + position: Some(LspPosition { line, utf16_column }), new_name: None, range: None, diagnostics: Vec::new(), @@ -355,6 +363,74 @@ impl Harness { operation_id } + /// Number of `textDocument/hover` requests written so far. Requests are + /// written before `request` returns, so this needs no waiting. + fn hover_requests(&self) -> usize { + self.server + .messages() + .iter() + .filter(|message| { + message.get("method").and_then(Value::as_str) == Some("textDocument/hover") + && message.get("id").is_some() + }) + .count() + } + + /// Hovers at a position of `HOVER_URI`, asserts the server was asked, and + /// answers with `reply` (an object holding `result` or `error`). Returns the + /// completion the host receives. + fn answer_hover(&mut self, line: i64, column: i64, reply: Value) -> LspRuntimeEvent { + let asked = self.hover_requests(); + let operation = self.request_at(LspSemanticOperation::Hover, HOVER_URI, line, column); + assert_eq!( + self.hover_requests(), + asked + 1, + "the hover at {line}:{column} should reach the server" + ); + let id = self + .server + .await_request_at("textDocument/hover", asked) + .expect("the hover request should be recorded"); + let mut message = json!({ "jsonrpc": "2.0", "id": id }); + for (key, value) in reply.as_object().expect("a reply is an object") { + message[key] = value.clone(); + } + self.server.send(message); + self.await_event(|event| { + event.kind == "requestCompleted" && event.operation_id.as_deref() == Some(&operation) + }) + .clone() + } + + /// Hovers at a position of `HOVER_URI` and asserts the answer was kept: the + /// server is not asked and the host already has the completion. + fn hover_from_cache(&mut self, line: i64, column: i64) -> LspRuntimeEvent { + let asked = self.hover_requests(); + let operation = self.request_at(LspSemanticOperation::Hover, HOVER_URI, line, column); + assert_eq!( + self.hover_requests(), + asked, + "the hover at {line}:{column} should be answered without the server" + ); + self.poll(); + self.events + .iter() + .find(|event| { + event.kind == "requestCompleted" + && event.operation_id.as_deref() == Some(&operation) + }) + .cloned() + .expect("a kept hover completes before the request returns") + } + + /// Hovers at a position of `HOVER_URI` and asserts the server was asked + /// again, leaving that request unanswered. + fn hover_asks_server(&mut self, line: i64, column: i64, why: &str) { + let asked = self.hover_requests(); + self.request_at(LspSemanticOperation::Hover, HOVER_URI, line, column); + assert_eq!(self.hover_requests(), asked + 1, "{why}"); + } + /// The recorded JSON-RPC message with the given request ID. fn written_request(&self, request_id: &str) -> Value { self.server @@ -5666,3 +5742,289 @@ mod plugin_owned_server { assert!(refused(None, metals_policy(false))); } } + +/// Document every hover-cache test rests on. +const HOVER_URI: &str = "file:///workspace/main.go"; +const HOVER_TEXT: &str = "package main\nfunc main() {}\n"; + +/// A ready session that saves with text, runs commands, and has `HOVER_URI` +/// and `file:///workspace/other.go` open. +fn hover_harness() -> Harness { + let mut harness = Harness::start(|_| {}); + let mut capabilities = ready_capabilities(); + capabilities["textDocumentSync"] = json!({ "change": 1, "save": { "includeText": true } }); + capabilities["executeCommandProvider"] = json!({ "commands": ["source.fix"] }); + harness.server.complete_initialize(capabilities); + harness.await_state(LspLifecycleState::Ready); + harness.sync(HOVER_URI, HOVER_TEXT); + harness.sync("file:///workspace/other.go", "package main\n"); + harness +} + +/// The server's answer for `func main()`, over `main` on line one. +fn main_hover() -> Value { + json!({ "result": { + "contents": { "kind": "markdown", "value": "```go\nfunc main()\n```" }, + "range": { "start": { "line": 1, "character": 5 }, "end": { "line": 1, "character": 9 } } + }}) +} + +fn hover_contents(event: &LspRuntimeEvent) -> Option<&str> { + event.result.as_ref()?.pointer("/hover/contents")?.as_str() +} + +/// Issue #1995: resting on a symbol again must not wait for the server again. +#[test] +fn a_kept_hover_answers_its_position_and_range_without_asking_again() { + let mut harness = hover_harness(); + let first = harness.answer_hover(1, 6, main_hover()); + assert_eq!(hover_contents(&first), Some("```go\nfunc main()\n```")); + + let again = harness.hover_from_cache(1, 6); + assert_eq!(again.result, first.result); + assert_eq!(again.method, first.method); + assert!(again.error.is_none()); + // Every column of the answered range shows the same answer. + assert_eq!(harness.hover_from_cache(1, 5).result, first.result); + assert_eq!(harness.hover_from_cache(1, 8).result, first.result); + harness.hover_asks_server(1, 9, "the range ends before column 9"); + harness.hover_asks_server(0, 6, "another line is another symbol"); +} + +#[test] +fn a_range_over_several_lines_or_elsewhere_answers_only_the_requested_position() { + let mut harness = hover_harness(); + harness.answer_hover( + 0, + 2, + json!({ "result": { + "contents": "package main", + "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 1, "character": 4 } } + }}), + ); + harness.hover_from_cache(0, 2); + harness.hover_asks_server(0, 3, "a multi-line range can enclose other symbols"); + harness.hover_asks_server(1, 0, "a multi-line range can enclose other symbols"); + + harness.answer_hover( + 1, + 0, + json!({ "result": { + "contents": "func", + "range": { "start": { "line": 1, "character": 5 }, "end": { "line": 1, "character": 9 } } + }}), + ); + harness.hover_from_cache(1, 0); + harness.hover_asks_server( + 1, + 6, + "a range that misses the request describes something else", + ); +} + +#[test] +fn an_empty_failed_or_oversized_hover_is_asked_for_again() { + let mut harness = hover_harness(); + let oversized = "x".repeat(HOVER_CACHE_MAX_CONTENT_BYTES + 1); + let replies = [ + json!({ "result": null }), + json!({ "result": { "contents": "" } }), + json!({ "result": { "contents": " \n " } }), + json!({ "result": { "contents": [] } }), + json!({ "error": { "code": -32801, "message": "content modified" } }), + json!({ "result": { "contents": oversized } }), + ]; + for reply in replies { + // `answer_hover` asserts that each of these asks the server again. + let completion = harness.answer_hover(1, 6, reply); + assert!(completion.result.is_some() || completion.error.is_some()); + } + let oversized_answer = harness + .events + .iter() + .rev() + .find(|event| event.kind == "requestCompleted") + .unwrap(); + assert_eq!( + hover_contents(oversized_answer).map(str::len), + Some(HOVER_CACHE_MAX_CONTENT_BYTES + 1), + "an oversized answer is still delivered" + ); + harness.hover_asks_server(1, 6, "an oversized answer is not kept"); +} + +#[test] +fn anything_that_can_change_what_the_server_knows_forgets_kept_hovers() { + type Invalidation = Box; + let other = "file:///workspace/other.go"; + let cases: Vec<(&str, Invalidation)> = vec![ + ( + "editing another document", + Box::new(move |harness| harness.sync(other, "package main\n\nvar edited = 1\n")), + ), + ( + "saving", + Box::new(|harness| { + let saved = harness + .session() + .save_document(SaveDocumentRequest { + session_id: harness.session_id.clone(), + uri: HOVER_URI.to_string(), + text: HOVER_TEXT.to_string(), + }) + .unwrap(); + assert!(saved); + }), + ), + ( + "closing and reopening at the same version", + Box::new(|harness| { + harness.session().close_document(HOVER_URI).unwrap(); + harness.sync(HOVER_URI, HOVER_TEXT); + assert_eq!(harness.snapshot().open_documents[HOVER_URI].version, 1); + }), + ), + ( + "a file changing on disk", + Box::new(move |harness| { + harness + .session() + .workspace_files_changed(vec![WorkspaceFileChange { + uri: "file:///workspace/go.mod".to_string(), + kind: WorkspaceFileChangeKind::Changed, + }]) + .unwrap(); + }), + ), + ( + "running a command", + Box::new(|harness| { + let operation_id = harness.engine.next_operation_id(); + harness + .session() + .request( + SemanticRequest { + query: None, + session_id: harness.session_id.clone(), + operation_id: Some(operation_id.clone()), + operation: LspSemanticOperation::ExecuteCommand, + uri: None, + position: None, + new_name: None, + range: None, + diagnostics: Vec::new(), + completion_context: None, + completion_item: None, + code_action: None, + command: Some(json!({ "title": "Fix", "command": "source.fix" })), + formatting_options: None, + include_declaration: None, + }, + operation_id, + ) + .unwrap(); + }), + ), + ( + "a request from the server", + Box::new(|harness| { + harness + .session() + .handle_server_message( + json!({ + "jsonrpc": "2.0", "id": "progress-token", + "method": "window/workDoneProgress/create", + "params": { "token": "load" } + }) + .to_string(), + ) + .unwrap(); + }), + ), + ( + "the end of a piece of server work", + Box::new(|harness| { + harness + .session() + .handle_server_message( + json!({ + "jsonrpc": "2.0", "method": "$/progress", + "params": { "token": "load", "value": { "kind": "end" } } + }) + .to_string(), + ) + .unwrap(); + }), + ), + ]; + let mut harness = hover_harness(); + for (name, invalidate) in cases { + harness.answer_hover(1, 6, main_hover()); + harness.hover_from_cache(1, 6); + invalidate(&mut harness); + harness.hover_asks_server(1, 6, &format!("{name} must forget kept hovers")); + } +} + +#[test] +fn progress_reports_and_other_documents_hovers_keep_kept_hovers() { + let mut harness = hover_harness(); + harness.answer_hover(1, 6, main_hover()); + harness + .session() + .handle_server_message( + json!({ + "jsonrpc": "2.0", "method": "$/progress", + "params": { "token": "load", "value": { "kind": "report", "message": "1/9" } } + }) + .to_string(), + ) + .unwrap(); + // Repeating the synchronized text changes nothing on the server. + harness.sync(HOVER_URI, HOVER_TEXT); + harness.request_at( + LspSemanticOperation::Hover, + "file:///workspace/other.go", + 0, + 0, + ); + harness.hover_from_cache(1, 6); +} + +/// The server may have computed an answer from what it knew before a change it +/// was told about while the request was in flight. +#[test] +fn a_hover_answered_across_an_invalidation_is_delivered_but_not_kept() { + let mut harness = hover_harness(); + let operation = harness.request_at(LspSemanticOperation::Hover, HOVER_URI, 1, 6); + let id = harness + .server + .await_request_at("textDocument/hover", 0) + .unwrap(); + harness + .session() + .workspace_files_changed(vec![WorkspaceFileChange { + uri: "file:///workspace/go.mod".to_string(), + kind: WorkspaceFileChangeKind::Changed, + }]) + .unwrap(); + let mut answer = main_hover(); + answer["jsonrpc"] = json!("2.0"); + answer["id"] = json!(id); + harness.server.send(answer); + let completion = harness + .await_event(|event| { + event.kind == "requestCompleted" && event.operation_id.as_deref() == Some(&operation) + }) + .clone(); + assert_eq!(hover_contents(&completion), Some("```go\nfunc main()\n```")); + harness.hover_asks_server(1, 6, "an answer from before the change is not kept"); +} + +#[test] +fn an_edit_to_the_hovered_document_asks_again_at_its_new_version() { + let mut harness = hover_harness(); + harness.answer_hover(1, 6, main_hover()); + harness.sync(HOVER_URI, "package main\nfunc main() { println() }\n"); + harness.hover_asks_server(1, 6, "an edit changes the hovered text"); +} diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 171071a7..d5916cb3 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -313,6 +313,23 @@ process is the same kind of process: it declares `launch`, `arguments`, `validationArguments`, `runtimeDependencies`, and `initializationOptions` with the same meaning and validation; see [Build providers](#build-providers). +The host keeps a language server's hover answers for the life of its LSP +session, so resting on the same symbol again does not wait for the server. A +kept answer is shown for the document version and position it was asked for, +and for any other position inside the answer's `range` when that range lies on +the requested line and contains the requested position. A session keeps at most +32 answers and drops the least recently used one first. The host never keeps an +empty answer, an error, an answer with more than 64 KiB of text, or an answer +that arrives after the kept answers were forgotten; each of these is delivered +and asked for again next time. Every kept answer is forgotten when a document +opens, changes, is saved or closes; a workspace file changes on disk; settings or +indexing exclusions change; a command runs; a plugin backend sends +`languageServer/request` or `languageServer/notify` to the server, or the host +sends a notification to a plugin backend; the server sends the client any +request or ends a `$/progress` report; and when the session stops. A server +whose hover changes for any other reason announces it with a request, such as a +refresh, or by ending a progress report. + #### Language server host integrations diff --git a/shared/plugins/reference/domains/languages.md b/shared/plugins/reference/domains/languages.md index 26603a47..851a1452 100644 --- a/shared/plugins/reference/domains/languages.md +++ b/shared/plugins/reference/domains/languages.md @@ -61,6 +61,8 @@ 宿主拥有语言服务器进程的生命周期、LSP 会话,以及在提供者被停用时停止进程。 +宿主在一次 LSP 会话里保留语言服务器的悬浮提示答案,在同一个符号上再次停留时不必再等服务器。保留的答案用于请求时的文档版本和位置;答案的 `range` 在请求所在行上且包含请求位置时,范围内的其他位置也用它。每个会话最多保留 32 个答案,先丢最久没用的。空答案、错误、文本超过 64 KiB 的答案,以及在清空之后才到达的答案都不保留,照常交付,下次重新请求。文档打开、修改、保存或关闭,工作区文件在磁盘上变化,设置或索引排除项变化,运行命令,插件后端向服务器发 `languageServer/request` 或 `languageServer/notify`、宿主向插件后端发通知,服务器向客户端发任何请求或结束一项 `$/progress`,以及会话停止时,宿主清空所有保留的答案。悬浮提示因其他原因变化的服务器,用请求(例如刷新)或结束一项进度来告知。完整规则见[契约](../../contract/v1/README.md#language-servers)。 + #### 宿主集成(`hostIntegration`) `hostIntegration` 是保留字段。Core 不实现任何宿主集成,也不按语言 ID、服务器 ID 或工具名走特殊逻辑;语言在启动之外需要的一切,都由插件自己的后端、提供者和声明给出。声明任何 `hostIntegration` ID 都返回 `plugin.integration.unsupported`,字段为 `languageServers[].hostIntegration.id`。 @@ -311,6 +313,8 @@ The rules for `id`, `fileExtensions`, `fileNames`, `projectFileNames`, and `depe The host owns the language server process lifecycle, the LSP session, and stopping the process when the provider is disabled. +The host keeps a language server's hover answers for the life of its LSP session, so resting on the same symbol again does not wait for the server. A kept answer is shown for the document version and position it was asked for, and for other positions inside the answer's `range` when that range lies on the requested line and contains the requested position. A session keeps at most 32 answers, dropping the least recently used first. Empty answers, errors, answers with more than 64 KiB of text, and answers that arrive after a clear are delivered but not kept. Every kept answer is forgotten when a document opens, changes, is saved or closes; a workspace file changes on disk; settings or indexing exclusions change; a command runs; a plugin backend sends `languageServer/request` or `languageServer/notify`, or the host notifies a plugin backend; the server sends the client any request or ends a `$/progress` report; and when the session stops. A server whose hover changes for any other reason announces it with a request, such as a refresh, or by ending a progress report. The full rules are in [the contract](../../contract/v1/README.md#language-servers). + #### Host integrations (`hostIntegration`) `hostIntegration` is reserved. Core implements no host integration and runs no special logic for a language ID, a server ID, or a tool name; everything a language needs beyond its launch comes from the plugin's own backend, providers, and declarations. Any `hostIntegration` ID returns `plugin.integration.unsupported`, at `languageServers[].hostIntegration.id`. diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 060ca08e..53d72397 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -133,6 +133,12 @@ ## 时间线(新的在上) +### 2026-11-16 + +| PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | +| --- | --- | --- | --- | --- | +| [#61](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/61) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | `languageServers` 0 内的补充 | LSP 引擎在一次会话里保留语言服务器的悬浮提示答案([1lck/Lithe-IDEA#1995](https://github.com/1lck/Lithe-IDEA/issues/1995)):同一文档版本的同一位置,或答案 `range` 在同一行内覆盖的位置,直接用保留的答案完成请求,不再发 `textDocument/hover`。每个会话最多 32 个,先丢最久没用的;空答案、错误、文本超过 64 KiB 的答案和清空之后才到达的答案照常交付但不保留。文档打开、修改、保存、关闭,工作区文件变化,设置或索引排除项变化,运行命令,后端的 `languageServer/request`、`languageServer/notify` 和宿主通知,服务器发来的任何请求和 `$/progress` 结束,以及会话停止时全部清空。`requestCompleted` 的结果形状不变,没有新增方法、字段或能力版本。 | + ### 2026-11-15 | PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 |