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},
13 pub(crate) fn is_cancelled(e: &(dyn Error + 'static)) -> bool {
14 e.downcast_ref::<Cancelled>().is_some()
17 pub(crate) fn notification_is<N: lsp_types::notification::Notification>(
18 notification: &Notification,
20 notification.method == N::METHOD
23 #[derive(Debug, Eq, PartialEq)]
24 pub(crate) enum Progress {
31 pub(crate) fn fraction(done: usize, total: usize) -> f64 {
32 assert!(done <= total);
33 done as f64 / total.max(1) as f64
38 pub(crate) fn show_message(&mut self, typ: lsp_types::MessageType, message: String) {
39 let message = message;
40 self.send_notification::<lsp_types::notification::ShowMessage>(
41 lsp_types::ShowMessageParams { typ, message },
45 pub(crate) fn report_progress(
49 message: Option<String>,
50 fraction: Option<f64>,
52 if !self.config.work_done_progress() {
55 let percentage = fraction.map(|f| {
56 assert!(0.0 <= f && f <= 1.0);
59 let token = lsp_types::ProgressToken::String(format!("rustAnalyzer/{}", title));
60 let work_done_progress = match state {
62 self.send_request::<lsp_types::request::WorkDoneProgressCreate>(
63 lsp_types::WorkDoneProgressCreateParams { token: token.clone() },
67 lsp_types::WorkDoneProgress::Begin(lsp_types::WorkDoneProgressBegin {
75 lsp_types::WorkDoneProgress::Report(lsp_types::WorkDoneProgressReport {
82 lsp_types::WorkDoneProgress::End(lsp_types::WorkDoneProgressEnd { message })
85 self.send_notification::<lsp_types::notification::Progress>(lsp_types::ProgressParams {
87 value: lsp_types::ProgressParamsValue::WorkDone(work_done_progress),
92 pub(crate) fn apply_document_changes(
93 old_text: &mut String,
94 content_changes: Vec<lsp_types::TextDocumentContentChangeEvent>,
96 let mut line_index = LineIndex {
97 index: Arc::new(ide::LineIndex::new(old_text)),
98 // We don't care about line endings or offset encoding here.
99 endings: LineEndings::Unix,
100 encoding: OffsetEncoding::Utf16,
103 // The changes we got must be applied sequentially, but can cross lines so we
104 // have to keep our line index updated.
105 // Some clients (e.g. Code) sort the ranges in reverse. As an optimization, we
106 // remember the last valid line in the index and only rebuild it if needed.
107 // The VFS will normalize the end of lines to `\n`.
110 UpToLineExclusive(u32),
114 fn covers(&self, line: u32) -> bool {
116 IndexValid::UpToLineExclusive(to) => to > line,
122 let mut index_valid = IndexValid::All;
123 for change in content_changes {
126 if !index_valid.covers(range.end.line) {
127 line_index.index = Arc::new(ide::LineIndex::new(old_text));
129 index_valid = IndexValid::UpToLineExclusive(range.start.line);
130 let range = from_proto::text_range(&line_index, range);
131 old_text.replace_range(Range::<usize>::from(range), &change.text);
134 *old_text = change.text;
135 index_valid = IndexValid::UpToLineExclusive(0);
141 /// Checks that the edits inside the completion and the additional edits do not overlap.
142 /// LSP explicitly forbids the additional edits to overlap both with the main edit and themselves.
143 pub(crate) fn all_edits_are_disjoint(
144 completion: &lsp_types::CompletionItem,
145 additional_edits: &[lsp_types::TextEdit],
147 let mut edit_ranges = Vec::new();
148 match completion.text_edit.as_ref() {
149 Some(lsp_types::CompletionTextEdit::Edit(edit)) => {
150 edit_ranges.push(edit.range);
152 Some(lsp_types::CompletionTextEdit::InsertAndReplace(edit)) => {
153 let replace = edit.replace;
154 let insert = edit.insert;
155 if replace.start != insert.start
156 || insert.start > insert.end
157 || insert.end > replace.end
159 // insert has to be a prefix of replace but it is not
162 edit_ranges.push(replace);
166 if let Some(additional_changes) = completion.additional_text_edits.as_ref() {
167 edit_ranges.extend(additional_changes.iter().map(|edit| edit.range));
169 edit_ranges.extend(additional_edits.iter().map(|edit| edit.range));
170 edit_ranges.sort_by_key(|range| (range.start, range.end));
173 .zip(edit_ranges.iter().skip(1))
174 .all(|(previous, next)| previous.end <= next.start)
180 CompletionItem, CompletionTextEdit, InsertReplaceEdit, Position, Range,
181 TextDocumentContentChangeEvent,
187 fn test_apply_document_changes() {
189 [$($sl:expr, $sc:expr; $el:expr, $ec:expr => $text:expr),+] => {
190 vec![$(TextDocumentContentChangeEvent {
192 start: Position { line: $sl, character: $sc },
193 end: Position { line: $el, character: $ec },
196 text: String::from($text),
201 let mut text = String::new();
202 apply_document_changes(&mut text, vec![]);
203 assert_eq!(text, "");
204 apply_document_changes(
206 vec![TextDocumentContentChangeEvent {
209 text: String::from("the"),
212 assert_eq!(text, "the");
213 apply_document_changes(&mut text, c![0, 3; 0, 3 => " quick"]);
214 assert_eq!(text, "the quick");
215 apply_document_changes(&mut text, c![0, 0; 0, 4 => "", 0, 5; 0, 5 => " foxes"]);
216 assert_eq!(text, "quick foxes");
217 apply_document_changes(&mut text, c![0, 11; 0, 11 => "\ndream"]);
218 assert_eq!(text, "quick foxes\ndream");
219 apply_document_changes(&mut text, c![1, 0; 1, 0 => "have "]);
220 assert_eq!(text, "quick foxes\nhave dream");
221 apply_document_changes(
223 c![0, 0; 0, 0 => "the ", 1, 4; 1, 4 => " quiet", 1, 16; 1, 16 => "s\n"],
225 assert_eq!(text, "the quick foxes\nhave quiet dreams\n");
226 apply_document_changes(&mut text, c![0, 15; 0, 15 => "\n", 2, 17; 2, 17 => "\n"]);
227 assert_eq!(text, "the quick foxes\n\nhave quiet dreams\n\n");
228 apply_document_changes(
230 c![1, 0; 1, 0 => "DREAM", 2, 0; 2, 0 => "they ", 3, 0; 3, 0 => "DON'T THEY?"],
232 assert_eq!(text, "the quick foxes\nDREAM\nthey have quiet dreams\nDON'T THEY?\n");
233 apply_document_changes(&mut text, c![0, 10; 1, 5 => "", 2, 0; 2, 12 => ""]);
234 assert_eq!(text, "the quick \nthey have quiet dreams\n");
236 text = String::from("❤️");
237 apply_document_changes(&mut text, c![0, 0; 0, 0 => "a"]);
238 assert_eq!(text, "a❤️");
240 text = String::from("a\nb");
241 apply_document_changes(&mut text, c![0, 1; 1, 0 => "\nțc", 0, 1; 1, 1 => "d"]);
242 assert_eq!(text, "adcb");
244 text = String::from("a\nb");
245 apply_document_changes(&mut text, c![0, 1; 1, 0 => "ț\nc", 0, 2; 0, 2 => "c"]);
246 assert_eq!(text, "ațc\ncb");
250 fn empty_completion_disjoint_tests() {
251 let empty_completion =
252 CompletionItem::new_simple("label".to_string(), "detail".to_string());
254 let disjoint_edit_1 = lsp_types::TextEdit::new(
255 Range::new(Position::new(2, 2), Position::new(3, 3)),
256 "new_text".to_string(),
258 let disjoint_edit_2 = lsp_types::TextEdit::new(
259 Range::new(Position::new(3, 3), Position::new(4, 4)),
260 "new_text".to_string(),
263 let joint_edit = lsp_types::TextEdit::new(
264 Range::new(Position::new(1, 1), Position::new(5, 5)),
265 "new_text".to_string(),
269 all_edits_are_disjoint(&empty_completion, &[]),
270 "Empty completion has all its edits disjoint"
273 all_edits_are_disjoint(
275 &[disjoint_edit_1.clone(), disjoint_edit_2.clone()]
277 "Empty completion is disjoint to whatever disjoint extra edits added"
281 !all_edits_are_disjoint(
283 &[disjoint_edit_1, disjoint_edit_2, joint_edit]
285 "Empty completion does not prevent joint extra edits from failing the validation"
290 fn completion_with_joint_edits_disjoint_tests() {
291 let disjoint_edit = lsp_types::TextEdit::new(
292 Range::new(Position::new(1, 1), Position::new(2, 2)),
293 "new_text".to_string(),
295 let disjoint_edit_2 = lsp_types::TextEdit::new(
296 Range::new(Position::new(2, 2), Position::new(3, 3)),
297 "new_text".to_string(),
299 let joint_edit = lsp_types::TextEdit::new(
300 Range::new(Position::new(1, 1), Position::new(5, 5)),
301 "new_text".to_string(),
304 let mut completion_with_joint_edits =
305 CompletionItem::new_simple("label".to_string(), "detail".to_string());
306 completion_with_joint_edits.additional_text_edits =
307 Some(vec![disjoint_edit.clone(), joint_edit.clone()]);
309 !all_edits_are_disjoint(&completion_with_joint_edits, &[]),
310 "Completion with disjoint edits fails the validation even with empty extra edits"
313 completion_with_joint_edits.text_edit =
314 Some(CompletionTextEdit::Edit(disjoint_edit.clone()));
315 completion_with_joint_edits.additional_text_edits = Some(vec![joint_edit.clone()]);
317 !all_edits_are_disjoint(&completion_with_joint_edits, &[]),
318 "Completion with disjoint edits fails the validation even with empty extra edits"
321 completion_with_joint_edits.text_edit =
322 Some(CompletionTextEdit::InsertAndReplace(InsertReplaceEdit {
323 new_text: "new_text".to_string(),
324 insert: disjoint_edit.range,
325 replace: disjoint_edit_2.range,
327 completion_with_joint_edits.additional_text_edits = Some(vec![joint_edit]);
329 !all_edits_are_disjoint(&completion_with_joint_edits, &[]),
330 "Completion with disjoint edits fails the validation even with empty extra edits"
335 fn completion_with_disjoint_edits_disjoint_tests() {
336 let disjoint_edit = lsp_types::TextEdit::new(
337 Range::new(Position::new(1, 1), Position::new(2, 2)),
338 "new_text".to_string(),
340 let disjoint_edit_2 = lsp_types::TextEdit::new(
341 Range::new(Position::new(2, 2), Position::new(3, 3)),
342 "new_text".to_string(),
344 let joint_edit = lsp_types::TextEdit::new(
345 Range::new(Position::new(1, 1), Position::new(5, 5)),
346 "new_text".to_string(),
349 let mut completion_with_disjoint_edits =
350 CompletionItem::new_simple("label".to_string(), "detail".to_string());
351 completion_with_disjoint_edits.text_edit = Some(CompletionTextEdit::Edit(disjoint_edit));
352 let completion_with_disjoint_edits = completion_with_disjoint_edits;
355 all_edits_are_disjoint(&completion_with_disjoint_edits, &[]),
356 "Completion with disjoint edits is valid"
359 !all_edits_are_disjoint(&completion_with_disjoint_edits, &[joint_edit]),
360 "Completion with disjoint edits and joint extra edit is invalid"
363 all_edits_are_disjoint(&completion_with_disjoint_edits, &[disjoint_edit_2]),
364 "Completion with disjoint edits and joint extra edit is valid"