|
| 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 | +} |
0 commit comments