]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/lsp_utils.rs
Update salsa
[rust.git] / crates / rust-analyzer / src / lsp_utils.rs
1 //! Utilities for LSP-related boilerplate code.
2 use std::{error::Error, ops::Range, sync::Arc};
3
4 use ide_db::base_db::Cancelled;
5 use lsp_server::Notification;
6
7 use crate::{
8     from_proto,
9     global_state::GlobalState,
10     line_index::{LineEndings, LineIndex, OffsetEncoding},
11 };
12
13 pub(crate) fn is_cancelled(e: &(dyn Error + 'static)) -> bool {
14     e.downcast_ref::<Cancelled>().is_some()
15 }
16
17 pub(crate) fn notification_is<N: lsp_types::notification::Notification>(
18     notification: &Notification,
19 ) -> bool {
20     notification.method == N::METHOD
21 }
22
23 #[derive(Debug, Eq, PartialEq)]
24 pub(crate) enum Progress {
25     Begin,
26     Report,
27     End,
28 }
29
30 impl Progress {
31     pub(crate) fn fraction(done: usize, total: usize) -> f64 {
32         assert!(done <= total);
33         done as f64 / total.max(1) as f64
34     }
35 }
36
37 impl GlobalState {
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 },
42         )
43     }
44
45     pub(crate) fn report_progress(
46         &mut self,
47         title: &str,
48         state: Progress,
49         message: Option<String>,
50         fraction: Option<f64>,
51     ) {
52         if !self.config.work_done_progress() {
53             return;
54         }
55         let percentage = fraction.map(|f| {
56             assert!(0.0 <= f && f <= 1.0);
57             (f * 100.0) as u32
58         });
59         let token = lsp_types::ProgressToken::String(format!("rustAnalyzer/{}", title));
60         let work_done_progress = match state {
61             Progress::Begin => {
62                 self.send_request::<lsp_types::request::WorkDoneProgressCreate>(
63                     lsp_types::WorkDoneProgressCreateParams { token: token.clone() },
64                     |_, _| (),
65                 );
66
67                 lsp_types::WorkDoneProgress::Begin(lsp_types::WorkDoneProgressBegin {
68                     title: title.into(),
69                     cancellable: None,
70                     message,
71                     percentage,
72                 })
73             }
74             Progress::Report => {
75                 lsp_types::WorkDoneProgress::Report(lsp_types::WorkDoneProgressReport {
76                     cancellable: None,
77                     message,
78                     percentage,
79                 })
80             }
81             Progress::End => {
82                 lsp_types::WorkDoneProgress::End(lsp_types::WorkDoneProgressEnd { message })
83             }
84         };
85         self.send_notification::<lsp_types::notification::Progress>(lsp_types::ProgressParams {
86             token,
87             value: lsp_types::ProgressParamsValue::WorkDone(work_done_progress),
88         });
89     }
90 }
91
92 pub(crate) fn apply_document_changes(
93     old_text: &mut String,
94     content_changes: Vec<lsp_types::TextDocumentContentChangeEvent>,
95 ) {
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,
101     };
102
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`.
108     enum IndexValid {
109         All,
110         UpToLineExclusive(u32),
111     }
112
113     impl IndexValid {
114         fn covers(&self, line: u32) -> bool {
115             match *self {
116                 IndexValid::UpToLineExclusive(to) => to > line,
117                 _ => true,
118             }
119         }
120     }
121
122     let mut index_valid = IndexValid::All;
123     for change in content_changes {
124         match change.range {
125             Some(range) => {
126                 if !index_valid.covers(range.end.line) {
127                     line_index.index = Arc::new(ide::LineIndex::new(&old_text));
128                 }
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);
132             }
133             None => {
134                 *old_text = change.text;
135                 index_valid = IndexValid::UpToLineExclusive(0);
136             }
137         }
138     }
139 }
140
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],
146 ) -> bool {
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);
151         }
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
158             {
159                 // insert has to be a prefix of replace but it is not
160                 return false;
161             }
162             edit_ranges.push(replace);
163         }
164         None => {}
165     }
166     if let Some(additional_changes) = completion.additional_text_edits.as_ref() {
167         edit_ranges.extend(additional_changes.iter().map(|edit| edit.range));
168     };
169     edit_ranges.extend(additional_edits.iter().map(|edit| edit.range));
170     edit_ranges.sort_by_key(|range| (range.start, range.end));
171     edit_ranges
172         .iter()
173         .zip(edit_ranges.iter().skip(1))
174         .all(|(previous, next)| previous.end <= next.start)
175 }
176
177 #[cfg(test)]
178 mod tests {
179     use lsp_types::{
180         CompletionItem, CompletionTextEdit, InsertReplaceEdit, Position, Range,
181         TextDocumentContentChangeEvent,
182     };
183
184     use super::*;
185
186     #[test]
187     fn test_apply_document_changes() {
188         macro_rules! c {
189             [$($sl:expr, $sc:expr; $el:expr, $ec:expr => $text:expr),+] => {
190                 vec![$(TextDocumentContentChangeEvent {
191                     range: Some(Range {
192                         start: Position { line: $sl, character: $sc },
193                         end: Position { line: $el, character: $ec },
194                     }),
195                     range_length: None,
196                     text: String::from($text),
197                 }),+]
198             };
199         }
200
201         let mut text = String::new();
202         apply_document_changes(&mut text, vec![]);
203         assert_eq!(text, "");
204         apply_document_changes(
205             &mut text,
206             vec![TextDocumentContentChangeEvent {
207                 range: None,
208                 range_length: None,
209                 text: String::from("the"),
210             }],
211         );
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(
222             &mut text,
223             c![0, 0; 0, 0 => "the ", 1, 4; 1, 4 => " quiet", 1, 16; 1, 16 => "s\n"],
224         );
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(
229             &mut text,
230             c![1, 0; 1, 0 => "DREAM", 2, 0; 2, 0 => "they ", 3, 0; 3, 0 => "DON'T THEY?"],
231         );
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");
235
236         text = String::from("❤️");
237         apply_document_changes(&mut text, c![0, 0; 0, 0 => "a"]);
238         assert_eq!(text, "a❤️");
239
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");
243
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");
247     }
248
249     #[test]
250     fn empty_completion_disjoint_tests() {
251         let empty_completion =
252             CompletionItem::new_simple("label".to_string(), "detail".to_string());
253
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(),
257         );
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(),
261         );
262
263         let joint_edit = lsp_types::TextEdit::new(
264             Range::new(Position::new(1, 1), Position::new(5, 5)),
265             "new_text".to_string(),
266         );
267
268         assert!(
269             all_edits_are_disjoint(&empty_completion, &[]),
270             "Empty completion has all its edits disjoint"
271         );
272         assert!(
273             all_edits_are_disjoint(
274                 &empty_completion,
275                 &[disjoint_edit_1.clone(), disjoint_edit_2.clone()]
276             ),
277             "Empty completion is disjoint to whatever disjoint extra edits added"
278         );
279
280         assert!(
281             !all_edits_are_disjoint(
282                 &empty_completion,
283                 &[disjoint_edit_1, disjoint_edit_2, joint_edit]
284             ),
285             "Empty completion does not prevent joint extra edits from failing the validation"
286         );
287     }
288
289     #[test]
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(),
294         );
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(),
298         );
299         let joint_edit = lsp_types::TextEdit::new(
300             Range::new(Position::new(1, 1), Position::new(5, 5)),
301             "new_text".to_string(),
302         );
303
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()]);
308         assert!(
309             !all_edits_are_disjoint(&completion_with_joint_edits, &[]),
310             "Completion with disjoint edits fails the validation even with empty extra edits"
311         );
312
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()]);
316         assert!(
317             !all_edits_are_disjoint(&completion_with_joint_edits, &[]),
318             "Completion with disjoint edits fails the validation even with empty extra edits"
319         );
320
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,
326             }));
327         completion_with_joint_edits.additional_text_edits = Some(vec![joint_edit]);
328         assert!(
329             !all_edits_are_disjoint(&completion_with_joint_edits, &[]),
330             "Completion with disjoint edits fails the validation even with empty extra edits"
331         );
332     }
333
334     #[test]
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(),
339         );
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(),
343         );
344         let joint_edit = lsp_types::TextEdit::new(
345             Range::new(Position::new(1, 1), Position::new(5, 5)),
346             "new_text".to_string(),
347         );
348
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;
353
354         assert!(
355             all_edits_are_disjoint(&completion_with_disjoint_edits, &[]),
356             "Completion with disjoint edits is valid"
357         );
358         assert!(
359             !all_edits_are_disjoint(&completion_with_disjoint_edits, &[joint_edit]),
360             "Completion with disjoint edits and joint extra edit is invalid"
361         );
362         assert!(
363             all_edits_are_disjoint(&completion_with_disjoint_edits, &[disjoint_edit_2]),
364             "Completion with disjoint edits and joint extra edit is valid"
365         );
366     }
367 }