Skip to content

Commit 6a14126

Browse files
authored
feat(lsp-engine): keep hover answers so resting on a symbol again answers at once (#61)
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.
1 parent ca80599 commit 6a14126

15 files changed

Lines changed: 711 additions & 7 deletions

File tree

‎rust/crates/lsp-engine/src/configuration.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ pub(crate) fn apply_indexing_to_sessions(
132132
let order = session.lock_outbound_order()?;
133133
if session.lock_state()?.client.initialized {
134134
if let Some(configuration) = session.plugin_configuration() {
135+
session.lock_state()?.hover_cache.clear();
135136
session.send_messages_or_fail(
136137
&order,
137138
vec![plugin_configuration_notification(&configuration)],
@@ -171,7 +172,7 @@ impl RuntimeSession {
171172
let configuration = Arc::new(configuration);
172173
let outbound_order = self.lock_outbound_order()?;
173174
let initialized = {
174-
let state = self.lock_state()?;
175+
let mut state = self.lock_state()?;
175176
if matches!(
176177
state.lifecycle,
177178
LspLifecycleState::Stopping
@@ -183,6 +184,7 @@ impl RuntimeSession {
183184
"The language session is no longer running.",
184185
));
185186
}
187+
state.hover_cache.clear();
186188
// Under `outbound_order`, an uninitialized client sends the stored
187189
// configuration with its `initialized` notification instead.
188190
state.client.initialized

‎rust/crates/lsp-engine/src/documents.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ impl RuntimeSession {
77
pub(crate) fn save_document(&self, request: SaveDocumentRequest) -> Result<bool, CoreError> {
88
let outbound_order = self.lock_outbound_order()?;
99
let message = {
10-
let state = self.lock_state()?;
10+
let mut state = self.lock_state()?;
1111
ensure_not_terminal(state.lifecycle)?;
1212
if state.lifecycle != LspLifecycleState::Ready {
1313
return Ok(false);
@@ -24,6 +24,7 @@ impl RuntimeSession {
2424
if *document.text != request.text {
2525
return Ok(false);
2626
}
27+
state.hover_cache.clear();
2728
let mut params = json!({"textDocument": {"uri": request.uri}});
2829
if include_text {
2930
params["text"] = json!(request.text);
@@ -66,6 +67,7 @@ impl RuntimeSession {
6667
let message = {
6768
let mut state = self.lock_state()?;
6869
ensure_not_terminal(state.lifecycle)?;
70+
state.hover_cache.clear();
6971
if !state.client.initialized {
7072
state.pending_workspace_file_changes.extend(normalized);
7173
return Ok(());
@@ -114,6 +116,7 @@ impl RuntimeSession {
114116
});
115117
}
116118
}
119+
state.hover_cache.clear();
117120
if state.client.initialized {
118121
let response = if state
119122
.client
@@ -197,6 +200,7 @@ impl RuntimeSession {
197200
"Cannot close a document that is not owned by the language-server session.",
198201
));
199202
};
203+
state.hover_cache.clear();
200204
cleared = state.client.diagnostics.contains_key(uri);
201205
if document.version == 0 {
202206
state.client.open_documents.remove(uri);

‎rust/crates/lsp-engine/src/engine.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,7 @@ impl LspEngine {
210210
method: "initialize".to_string(),
211211
document_uri: None,
212212
document_version: None,
213+
hover: None,
213214
created_at: now,
214215
deadline: now + initialize_timeout,
215216
},
@@ -236,6 +237,7 @@ impl LspEngine {
236237
rejected_plugin_diagnostics: false,
237238
plugin_diagnostics_window: Instant::now(),
238239
plugin_diagnostics_count: 0,
240+
hover_cache: HoverCache::default(),
239241
}),
240242
event_signal: Condvar::new(),
241243
process: process.handle,

‎rust/crates/lsp-engine/src/events.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -562,6 +562,7 @@ pub(crate) fn clear_runtime_state(session: &RuntimeSession, state: &mut SessionS
562562
state.maintenance_write_deadline = None;
563563
state.relay_write_deadline = None;
564564
state.pending_workspace_file_changes.clear();
565+
state.hover_cache.clear();
565566
state.initialize_deadline = None;
566567
state.shutdown_deadline = None;
567568
push_features_event(session, state, Vec::new());
Lines changed: 242 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,242 @@
1+
//! Hover answers a session already received, so resting on a symbol again answers at
2+
//! once instead of asking the language server a second time.
3+
//!
4+
//! An answer is reused only for the same document version and a position the answer
5+
//! covers. Anything that can change what the server knows clears every answer, not
6+
//! only those of one document: an edit in one file changes the hover shown for its
7+
//! symbols in every other file.
8+
9+
use super::*;
10+
11+
/// Most answers one session keeps; the least recently used one goes first.
12+
pub(crate) const HOVER_CACHE_CAPACITY: usize = 32;
13+
14+
/// Longest hover text, in bytes, worth keeping. A longer answer is still delivered
15+
/// but asked for again next time, which bounds a session's cache to
16+
/// `HOVER_CACHE_CAPACITY * HOVER_CACHE_MAX_CONTENT_BYTES` of hover text.
17+
pub(crate) const HOVER_CACHE_MAX_CONTENT_BYTES: usize = 64 * 1024;
18+
19+
/// Zero-based LSP line and UTF-16 column, ordered line first.
20+
type Point = (i64, i64);
21+
22+
/// What a hover request in flight needs to keep its answer.
23+
#[derive(Debug, Clone)]
24+
pub(crate) struct HoverRequest {
25+
/// Document version the request was sent for; the answer describes that text.
26+
pub(crate) version: i64,
27+
pub(crate) position: Point,
28+
/// Cache generation when the request was sent. The answer is kept only if
29+
/// nothing cleared the cache before it arrived, because the server may have
30+
/// computed it from what it knew before the change.
31+
pub(crate) generation: u64,
32+
}
33+
34+
/// One kept answer.
35+
struct HoverEntry {
36+
uri: String,
37+
version: i64,
38+
position: Point,
39+
/// Same-line half-open column span `(line, start, end)` the server gave as the
40+
/// answer's range, when that range contains `position`. Any position inside it
41+
/// shows this answer, the way editors keep a hover open across its range.
42+
span: Option<(i64, i64, i64)>,
43+
/// The `requestCompleted` result exactly as the host received it.
44+
result: Value,
45+
}
46+
47+
impl HoverEntry {
48+
fn covers(&self, uri: &str, version: i64, position: Point) -> bool {
49+
if self.uri != uri || self.version != version {
50+
return false;
51+
}
52+
position == self.position
53+
|| self.span.is_some_and(|(line, start, end)| {
54+
position.0 == line && start <= position.1 && position.1 < end
55+
})
56+
}
57+
}
58+
59+
/// Hover answers of one session, owned by its `SessionState`.
60+
#[derive(Default)]
61+
pub(crate) struct HoverCache {
62+
/// Advances on every clear; see `HoverRequest::generation`.
63+
generation: u64,
64+
/// Least recently used first.
65+
entries: VecDeque<HoverEntry>,
66+
}
67+
68+
impl HoverCache {
69+
/// Forgets every answer. Called whenever the server may know something it did
70+
/// not know when it answered: a document opened, changed, saved or closed, files
71+
/// changed on disk, settings changed, a command ran, a plugin backend was
72+
/// notified or sent the server its own request, or the server asked the client
73+
/// for something or finished a piece of work.
74+
pub(crate) fn clear(&mut self) {
75+
self.entries.clear();
76+
self.generation = self.generation.wrapping_add(1);
77+
}
78+
79+
/// The answer kept for `position` in this version of the document, marked as
80+
/// the most recently used.
81+
pub(crate) fn lookup(&mut self, uri: &str, version: i64, position: Point) -> Option<Value> {
82+
let index = self
83+
.entries
84+
.iter()
85+
.rposition(|entry| entry.covers(uri, version, position))?;
86+
let entry = self.entries.remove(index)?;
87+
let result = entry.result.clone();
88+
self.entries.push_back(entry);
89+
Some(result)
90+
}
91+
92+
/// Describes a hover request about to be sent for `position`.
93+
pub(crate) fn request(&self, version: i64, position: Point) -> HoverRequest {
94+
HoverRequest {
95+
version,
96+
position,
97+
generation: self.generation,
98+
}
99+
}
100+
101+
/// Keeps the answer to `request`. An empty or oversized answer, or one the
102+
/// server computed before the cache was last cleared, is not kept: an empty
103+
/// answer can turn into a real one once the server has loaded the project.
104+
pub(crate) fn store(&mut self, uri: &str, request: &HoverRequest, result: &Value) {
105+
if request.generation != self.generation {
106+
return;
107+
}
108+
let Some(hover) = result.get("hover").filter(|hover| hover.is_object()) else {
109+
return;
110+
};
111+
let Some(contents) = hover.get("contents").and_then(Value::as_str) else {
112+
return;
113+
};
114+
if contents.trim().is_empty() || contents.len() > HOVER_CACHE_MAX_CONTENT_BYTES {
115+
return;
116+
}
117+
let span = same_line_span(hover.get("range")).filter(|(line, start, end)| {
118+
request.position.0 == *line && *start <= request.position.1 && request.position.1 < *end
119+
});
120+
self.entries.retain(|entry| {
121+
!(entry.uri == uri
122+
&& entry.version == request.version
123+
&& entry.position == request.position)
124+
});
125+
self.entries.push_back(HoverEntry {
126+
uri: uri.to_string(),
127+
version: request.version,
128+
position: request.position,
129+
span,
130+
result: result.clone(),
131+
});
132+
while self.entries.len() > HOVER_CACHE_CAPACITY {
133+
self.entries.pop_front();
134+
}
135+
}
136+
}
137+
138+
/// A hover range from `lithe_lsp_client` (`{start, end}` of `{line, utf16Column}`)
139+
/// as `(line, start, end)`, when it is a non-empty span on one line. A range over
140+
/// several lines is not used to answer other positions: it can enclose other
141+
/// symbols with hovers of their own.
142+
fn same_line_span(range: Option<&Value>) -> Option<(i64, i64, i64)> {
143+
let range = range?;
144+
let point = |key: &str| -> Option<Point> {
145+
let position = range.get(key)?;
146+
Some((
147+
position.get("line")?.as_i64()?,
148+
position.get("utf16Column")?.as_i64()?,
149+
))
150+
};
151+
let (start, end) = (point("start")?, point("end")?);
152+
(start.0 == end.0 && start.1 < end.1).then_some((start.0, start.1, end.1))
153+
}
154+
155+
/// Whether a message the server sent may mean it knows something new: any request
156+
/// it makes of the client (refreshes, edits, capability changes, configuration
157+
/// pulls, progress tokens) and the end of a piece of work such as loading the
158+
/// workspace.
159+
pub(crate) fn server_message_clears_hovers(value: &Value) -> bool {
160+
let Some(method) = value.get("method").and_then(Value::as_str) else {
161+
return false;
162+
};
163+
value.get("id").is_some()
164+
|| (method == "$/progress"
165+
&& value.pointer("/params/value/kind").and_then(Value::as_str) == Some("end"))
166+
}
167+
168+
#[cfg(test)]
169+
mod tests {
170+
use super::*;
171+
172+
fn answer(contents: &str) -> Value {
173+
json!({ "hover": { "contents": contents, "isMarkdown": false, "range": null } })
174+
}
175+
176+
fn keep(cache: &mut HoverCache, line: i64) {
177+
let request = cache.request(1, (line, 0));
178+
cache.store("file:///a.go", &request, &answer(&format!("line {line}")));
179+
}
180+
181+
#[test]
182+
fn the_least_recently_used_answer_goes_first_at_capacity() {
183+
let mut cache = HoverCache::default();
184+
for line in 0..HOVER_CACHE_CAPACITY as i64 {
185+
keep(&mut cache, line);
186+
}
187+
// Reading line 0 makes line 1 the oldest.
188+
assert!(cache.lookup("file:///a.go", 1, (0, 0)).is_some());
189+
keep(&mut cache, HOVER_CACHE_CAPACITY as i64);
190+
assert_eq!(cache.entries.len(), HOVER_CACHE_CAPACITY);
191+
assert!(cache.lookup("file:///a.go", 1, (1, 0)).is_none());
192+
assert!(cache.lookup("file:///a.go", 1, (0, 0)).is_some());
193+
assert!(cache
194+
.lookup("file:///a.go", 1, (HOVER_CACHE_CAPACITY as i64, 0))
195+
.is_some());
196+
}
197+
198+
#[test]
199+
fn an_answer_is_kept_once_per_position_and_only_for_its_document_version() {
200+
let mut cache = HoverCache::default();
201+
keep(&mut cache, 3);
202+
keep(&mut cache, 3);
203+
assert_eq!(cache.entries.len(), 1);
204+
assert!(cache.lookup("file:///a.go", 2, (3, 0)).is_none());
205+
assert!(cache.lookup("file:///b.go", 1, (3, 0)).is_none());
206+
assert_eq!(
207+
cache.lookup("file:///a.go", 1, (3, 0)),
208+
Some(answer("line 3"))
209+
);
210+
}
211+
212+
#[test]
213+
fn a_clear_forgets_answers_and_refuses_ones_requested_before_it() {
214+
let mut cache = HoverCache::default();
215+
keep(&mut cache, 0);
216+
let in_flight = cache.request(1, (5, 0));
217+
cache.clear();
218+
assert!(cache.lookup("file:///a.go", 1, (0, 0)).is_none());
219+
cache.store("file:///a.go", &in_flight, &answer("stale"));
220+
assert!(cache.entries.is_empty());
221+
}
222+
223+
#[test]
224+
fn only_server_requests_and_finished_work_clear_answers() {
225+
let clears = |message: Value| server_message_clears_hovers(&message);
226+
assert!(clears(
227+
json!({ "id": 1, "method": "workspace/codeLens/refresh" })
228+
));
229+
assert!(clears(json!({
230+
"method": "$/progress",
231+
"params": { "token": "t", "value": { "kind": "end" } }
232+
})));
233+
assert!(!clears(json!({
234+
"method": "$/progress",
235+
"params": { "token": "t", "value": { "kind": "report" } }
236+
})));
237+
assert!(!clears(
238+
json!({ "method": "textDocument/publishDiagnostics", "params": {} })
239+
));
240+
assert!(!clears(json!({ "id": 1, "result": null })));
241+
}
242+
}

‎rust/crates/lsp-engine/src/lib.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ mod engine;
7878
mod events;
7979
mod function_calls;
8080
mod host_requests;
81+
mod hover_cache;
8182
mod lifecycle;
8283
mod operations;
8384
mod plugin_server_calls;
@@ -93,6 +94,7 @@ use engine::*;
9394
use events::*;
9495
use function_calls::*;
9596
use host_requests::*;
97+
use hover_cache::*;
9698
use lifecycle::*;
9799
use operations::*;
98100
use plugin_server_calls::*;

‎rust/crates/lsp-engine/src/lifecycle.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ impl RuntimeSession {
4646
method: "shutdown".to_string(),
4747
document_uri: None,
4848
document_version: None,
49+
hover: None,
4950
created_at: now,
5051
deadline: now + shutdown_timeout,
5152
},

0 commit comments

Comments
 (0)