1 //! Utilities for LSP-related boilerplate code.
2 use std::{error::Error, ops::Range, sync::Arc};
4 use ide_db::base_db::Cancelled;
5 use lsp_server::Notification;
9 global_state::GlobalState,
10 line_index::{LineEndings, LineIndex, OffsetEncoding},
14 pub(crate) fn invalid_params_error(message: String) -> LspError {
15 LspError { code: lsp_server::ErrorCode::InvalidParams as i32, message }
18 pub(crate) fn is_cancelled(e: &(dyn Error + 'static)) -> bool {
19 e.downcast_ref::<Cancelled>().is_some()
22 pub(crate) fn notification_is<N: lsp_types::notification::Notification>(
23 notification: &Notification,
25 notification.method == N::METHOD
28 #[derive(Debug, Eq, PartialEq)]
29 pub(crate) enum Progress {
36 pub(crate) fn fraction(done: usize, total: usize) -> f64 {
37 assert!(done <= total);
38 done as f64 / total.max(1) as f64
43 pub(crate) fn show_message(&mut self, typ: lsp_types::MessageType, message: String) {
44 let message = message;
45 self.send_notification::<lsp_types::notification::ShowMessage>(
46 lsp_types::ShowMessageParams { typ, message },
50 /// rust-analyzer is resilient -- if it fails, this doesn't usually affect
51 /// the user experience. Part of that is that we deliberately hide panics
54 /// We do however want to pester rust-analyzer developers with panics and
55 /// other "you really gotta fix that" messages. The current strategy is to
56 /// be noisy for "from source" builds or when profiling is enabled.
58 /// It's unclear if making from source `cargo xtask install` builds more
59 /// panicky is a good idea, let's see if we can keep our awesome bleeding
60 /// edge users from being upset!
61 pub(crate) fn poke_rust_analyzer_developer(&mut self, message: String) {
62 let from_source_build = env!("REV").contains("dev");
63 let profiling_enabled = std::env::var("RA_PROFILE").is_ok();
64 if from_source_build || profiling_enabled {
65 self.show_message(lsp_types::MessageType::Error, message)
69 pub(crate) fn report_progress(
73 message: Option<String>,
74 fraction: Option<f64>,
76 if !self.config.work_done_progress() {
79 let percentage = fraction.map(|f| {
80 assert!((0.0..=1.0).contains(&f));
83 let token = lsp_types::ProgressToken::String(format!("rustAnalyzer/{}", title));
84 let work_done_progress = match state {
86 self.send_request::<lsp_types::request::WorkDoneProgressCreate>(
87 lsp_types::WorkDoneProgressCreateParams { token: token.clone() },
91 lsp_types::WorkDoneProgress::Begin(lsp_types::WorkDoneProgressBegin {
99 lsp_types::WorkDoneProgress::Report(lsp_types::WorkDoneProgressReport {
106 lsp_types::WorkDoneProgress::End(lsp_types::WorkDoneProgressEnd { message })
109 self.send_notification::<lsp_types::notification::Progress>(lsp_types::ProgressParams {
111 value: lsp_types::ProgressParamsValue::WorkDone(work_done_progress),
116 pub(crate) fn apply_document_changes(
117 old_text: &mut String,
118 content_changes: Vec<lsp_types::TextDocumentContentChangeEvent>,
120 let mut line_index = LineIndex {
121 index: Arc::new(ide::LineIndex::new(old_text)),
122 // We don't care about line endings or offset encoding here.
123 endings: LineEndings::Unix,
124 encoding: OffsetEncoding::Utf16,
127 // The changes we got must be applied sequentially, but can cross lines so we
128 // have to keep our line index updated.
129 // Some clients (e.g. Code) sort the ranges in reverse. As an optimization, we
130 // remember the last valid line in the index and only rebuild it if needed.
131 // The VFS will normalize the end of lines to `\n`.
134 UpToLineExclusive(u32),
138 fn covers(&self, line: u32) -> bool {
140 IndexValid::UpToLineExclusive(to) => to > line,
146 let mut index_valid = IndexValid::All;
147 for change in content_changes {
150 if !index_valid.covers(range.end.line) {
151 line_index.index = Arc::new(ide::LineIndex::new(old_text));
153 index_valid = IndexValid::UpToLineExclusive(range.start.line);
154 let range = from_proto::text_range(&line_index, range);
155 old_text.replace_range(Range::<usize>::from(range), &change.text);
158 *old_text = change.text;
159 index_valid = IndexValid::UpToLineExclusive(0);
165 /// Checks that the edits inside the completion and the additional edits do not overlap.
166 /// LSP explicitly forbids the additional edits to overlap both with the main edit and themselves.
167 pub(crate) fn all_edits_are_disjoint(
168 completion: &lsp_types::CompletionItem,
169 additional_edits: &[lsp_types::TextEdit],
171 let mut edit_ranges = Vec::new();
172 match completion.text_edit.as_ref() {
173 Some(lsp_types::CompletionTextEdit::Edit(edit)) => {
174 edit_ranges.push(edit.range);
176 Some(lsp_types::CompletionTextEdit::InsertAndReplace(edit)) => {
177 let replace = edit.replace;
178 let insert = edit.insert;
179 if replace.start != insert.start
180 || insert.start > insert.end
181 || insert.end > replace.end
183 // insert has to be a prefix of replace but it is not
186 edit_ranges.push(replace);
190 if let Some(additional_changes) = completion.additional_text_edits.as_ref() {
191 edit_ranges.extend(additional_changes.iter().map(|edit| edit.range));
193 edit_ranges.extend(additional_edits.iter().map(|edit| edit.range));
194 edit_ranges.sort_by_key(|range| (range.start, range.end));
197 .zip(edit_ranges.iter().skip(1))
198 .all(|(previous, next)| previous.end <= next.start)
204 CompletionItem, CompletionTextEdit, InsertReplaceEdit, Position, Range,
205 TextDocumentContentChangeEvent,
211 fn test_apply_document_changes() {
213 [$($sl:expr, $sc:expr; $el:expr, $ec:expr => $text:expr),+] => {
214 vec![$(TextDocumentContentChangeEvent {
216 start: Position { line: $sl, character: $sc },
217 end: Position { line: $el, character: $ec },
220 text: String::from($text),
225 let mut text = String::new();
226 apply_document_changes(&mut text, vec![]);
227 assert_eq!(text, "");
228 apply_document_changes(
230 vec![TextDocumentContentChangeEvent {
233 text: String::from("the"),
236 assert_eq!(text, "the");
237 apply_document_changes(&mut text, c![0, 3; 0, 3 => " quick"]);
238 assert_eq!(text, "the quick");
239 apply_document_changes(&mut text, c![0, 0; 0, 4 => "", 0, 5; 0, 5 => " foxes"]);
240 assert_eq!(text, "quick foxes");
241 apply_document_changes(&mut text, c![0, 11; 0, 11 => "\ndream"]);
242 assert_eq!(text, "quick foxes\ndream");
243 apply_document_changes(&mut text, c![1, 0; 1, 0 => "have "]);
244 assert_eq!(text, "quick foxes\nhave dream");
245 apply_document_changes(
247 c![0, 0; 0, 0 => "the ", 1, 4; 1, 4 => " quiet", 1, 16; 1, 16 => "s\n"],
249 assert_eq!(text, "the quick foxes\nhave quiet dreams\n");
250 apply_document_changes(&mut text, c![0, 15; 0, 15 => "\n", 2, 17; 2, 17 => "\n"]);
251 assert_eq!(text, "the quick foxes\n\nhave quiet dreams\n\n");
252 apply_document_changes(
254 c![1, 0; 1, 0 => "DREAM", 2, 0; 2, 0 => "they ", 3, 0; 3, 0 => "DON'T THEY?"],
256 assert_eq!(text, "the quick foxes\nDREAM\nthey have quiet dreams\nDON'T THEY?\n");
257 apply_document_changes(&mut text, c![0, 10; 1, 5 => "", 2, 0; 2, 12 => ""]);
258 assert_eq!(text, "the quick \nthey have quiet dreams\n");
260 text = String::from("❤️");
261 apply_document_changes(&mut text, c![0, 0; 0, 0 => "a"]);
262 assert_eq!(text, "a❤️");
264 text = String::from("a\nb");
265 apply_document_changes(&mut text, c![0, 1; 1, 0 => "\nțc", 0, 1; 1, 1 => "d"]);
266 assert_eq!(text, "adcb");
268 text = String::from("a\nb");
269 apply_document_changes(&mut text, c![0, 1; 1, 0 => "ț\nc", 0, 2; 0, 2 => "c"]);
270 assert_eq!(text, "ațc\ncb");
274 fn empty_completion_disjoint_tests() {
275 let empty_completion =
276 CompletionItem::new_simple("label".to_string(), "detail".to_string());
278 let disjoint_edit_1 = lsp_types::TextEdit::new(
279 Range::new(Position::new(2, 2), Position::new(3, 3)),
280 "new_text".to_string(),
282 let disjoint_edit_2 = lsp_types::TextEdit::new(
283 Range::new(Position::new(3, 3), Position::new(4, 4)),
284 "new_text".to_string(),
287 let joint_edit = lsp_types::TextEdit::new(
288 Range::new(Position::new(1, 1), Position::new(5, 5)),
289 "new_text".to_string(),
293 all_edits_are_disjoint(&empty_completion, &[]),
294 "Empty completion has all its edits disjoint"
297 all_edits_are_disjoint(
299 &[disjoint_edit_1.clone(), disjoint_edit_2.clone()]
301 "Empty completion is disjoint to whatever disjoint extra edits added"
305 !all_edits_are_disjoint(
307 &[disjoint_edit_1, disjoint_edit_2, joint_edit]
309 "Empty completion does not prevent joint extra edits from failing the validation"
314 fn completion_with_joint_edits_disjoint_tests() {
315 let disjoint_edit = lsp_types::TextEdit::new(
316 Range::new(Position::new(1, 1), Position::new(2, 2)),
317 "new_text".to_string(),
319 let disjoint_edit_2 = lsp_types::TextEdit::new(
320 Range::new(Position::new(2, 2), Position::new(3, 3)),
321 "new_text".to_string(),
323 let joint_edit = lsp_types::TextEdit::new(
324 Range::new(Position::new(1, 1), Position::new(5, 5)),
325 "new_text".to_string(),
328 let mut completion_with_joint_edits =
329 CompletionItem::new_simple("label".to_string(), "detail".to_string());
330 completion_with_joint_edits.additional_text_edits =
331 Some(vec![disjoint_edit.clone(), joint_edit.clone()]);
333 !all_edits_are_disjoint(&completion_with_joint_edits, &[]),
334 "Completion with disjoint edits fails the validation even with empty extra edits"
337 completion_with_joint_edits.text_edit =
338 Some(CompletionTextEdit::Edit(disjoint_edit.clone()));
339 completion_with_joint_edits.additional_text_edits = Some(vec![joint_edit.clone()]);
341 !all_edits_are_disjoint(&completion_with_joint_edits, &[]),
342 "Completion with disjoint edits fails the validation even with empty extra edits"
345 completion_with_joint_edits.text_edit =
346 Some(CompletionTextEdit::InsertAndReplace(InsertReplaceEdit {
347 new_text: "new_text".to_string(),
348 insert: disjoint_edit.range,
349 replace: disjoint_edit_2.range,
351 completion_with_joint_edits.additional_text_edits = Some(vec![joint_edit]);
353 !all_edits_are_disjoint(&completion_with_joint_edits, &[]),
354 "Completion with disjoint edits fails the validation even with empty extra edits"
359 fn completion_with_disjoint_edits_disjoint_tests() {
360 let disjoint_edit = lsp_types::TextEdit::new(
361 Range::new(Position::new(1, 1), Position::new(2, 2)),
362 "new_text".to_string(),
364 let disjoint_edit_2 = lsp_types::TextEdit::new(
365 Range::new(Position::new(2, 2), Position::new(3, 3)),
366 "new_text".to_string(),
368 let joint_edit = lsp_types::TextEdit::new(
369 Range::new(Position::new(1, 1), Position::new(5, 5)),
370 "new_text".to_string(),
373 let mut completion_with_disjoint_edits =
374 CompletionItem::new_simple("label".to_string(), "detail".to_string());
375 completion_with_disjoint_edits.text_edit = Some(CompletionTextEdit::Edit(disjoint_edit));
376 let completion_with_disjoint_edits = completion_with_disjoint_edits;
379 all_edits_are_disjoint(&completion_with_disjoint_edits, &[]),
380 "Completion with disjoint edits is valid"
383 !all_edits_are_disjoint(&completion_with_disjoint_edits, &[joint_edit]),
384 "Completion with disjoint edits and joint extra edit is invalid"
387 all_edits_are_disjoint(&completion_with_disjoint_edits, &[disjoint_edit_2]),
388 "Completion with disjoint edits and joint extra edit is valid"