]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/lsp_utils.rs
Merge #10147
[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     LspError,
12 };
13
14 pub(crate) fn invalid_params_error(message: String) -> LspError {
15     LspError { code: lsp_server::ErrorCode::InvalidParams as i32, message }
16 }
17
18 pub(crate) fn is_cancelled(e: &(dyn Error + 'static)) -> bool {
19     e.downcast_ref::<Cancelled>().is_some()
20 }
21
22 pub(crate) fn notification_is<N: lsp_types::notification::Notification>(
23     notification: &Notification,
24 ) -> bool {
25     notification.method == N::METHOD
26 }
27
28 #[derive(Debug, Eq, PartialEq)]
29 pub(crate) enum Progress {
30     Begin,
31     Report,
32     End,
33 }
34
35 impl Progress {
36     pub(crate) fn fraction(done: usize, total: usize) -> f64 {
37         assert!(done <= total);
38         done as f64 / total.max(1) as f64
39     }
40 }
41
42 impl GlobalState {
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 },
47         )
48     }
49
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
52     /// from the user.
53     ///
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.
57     ///
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)
66         }
67     }
68
69     pub(crate) fn report_progress(
70         &mut self,
71         title: &str,
72         state: Progress,
73         message: Option<String>,
74         fraction: Option<f64>,
75     ) {
76         if !self.config.work_done_progress() {
77             return;
78         }
79         let percentage = fraction.map(|f| {
80             assert!(0.0 <= f && f <= 1.0);
81             (f * 100.0) as u32
82         });
83         let token = lsp_types::ProgressToken::String(format!("rustAnalyzer/{}", title));
84         let work_done_progress = match state {
85             Progress::Begin => {
86                 self.send_request::<lsp_types::request::WorkDoneProgressCreate>(
87                     lsp_types::WorkDoneProgressCreateParams { token: token.clone() },
88                     |_, _| (),
89                 );
90
91                 lsp_types::WorkDoneProgress::Begin(lsp_types::WorkDoneProgressBegin {
92                     title: title.into(),
93                     cancellable: None,
94                     message,
95                     percentage,
96                 })
97             }
98             Progress::Report => {
99                 lsp_types::WorkDoneProgress::Report(lsp_types::WorkDoneProgressReport {
100                     cancellable: None,
101                     message,
102                     percentage,
103                 })
104             }
105             Progress::End => {
106                 lsp_types::WorkDoneProgress::End(lsp_types::WorkDoneProgressEnd { message })
107             }
108         };
109         self.send_notification::<lsp_types::notification::Progress>(lsp_types::ProgressParams {
110             token,
111             value: lsp_types::ProgressParamsValue::WorkDone(work_done_progress),
112         });
113     }
114 }
115
116 pub(crate) fn apply_document_changes(
117     old_text: &mut String,
118     content_changes: Vec<lsp_types::TextDocumentContentChangeEvent>,
119 ) {
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,
125     };
126
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`.
132     enum IndexValid {
133         All,
134         UpToLineExclusive(u32),
135     }
136
137     impl IndexValid {
138         fn covers(&self, line: u32) -> bool {
139             match *self {
140                 IndexValid::UpToLineExclusive(to) => to > line,
141                 _ => true,
142             }
143         }
144     }
145
146     let mut index_valid = IndexValid::All;
147     for change in content_changes {
148         match change.range {
149             Some(range) => {
150                 if !index_valid.covers(range.end.line) {
151                     line_index.index = Arc::new(ide::LineIndex::new(old_text));
152                 }
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);
156             }
157             None => {
158                 *old_text = change.text;
159                 index_valid = IndexValid::UpToLineExclusive(0);
160             }
161         }
162     }
163 }
164
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],
170 ) -> bool {
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);
175         }
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
182             {
183                 // insert has to be a prefix of replace but it is not
184                 return false;
185             }
186             edit_ranges.push(replace);
187         }
188         None => {}
189     }
190     if let Some(additional_changes) = completion.additional_text_edits.as_ref() {
191         edit_ranges.extend(additional_changes.iter().map(|edit| edit.range));
192     };
193     edit_ranges.extend(additional_edits.iter().map(|edit| edit.range));
194     edit_ranges.sort_by_key(|range| (range.start, range.end));
195     edit_ranges
196         .iter()
197         .zip(edit_ranges.iter().skip(1))
198         .all(|(previous, next)| previous.end <= next.start)
199 }
200
201 #[cfg(test)]
202 mod tests {
203     use lsp_types::{
204         CompletionItem, CompletionTextEdit, InsertReplaceEdit, Position, Range,
205         TextDocumentContentChangeEvent,
206     };
207
208     use super::*;
209
210     #[test]
211     fn test_apply_document_changes() {
212         macro_rules! c {
213             [$($sl:expr, $sc:expr; $el:expr, $ec:expr => $text:expr),+] => {
214                 vec![$(TextDocumentContentChangeEvent {
215                     range: Some(Range {
216                         start: Position { line: $sl, character: $sc },
217                         end: Position { line: $el, character: $ec },
218                     }),
219                     range_length: None,
220                     text: String::from($text),
221                 }),+]
222             };
223         }
224
225         let mut text = String::new();
226         apply_document_changes(&mut text, vec![]);
227         assert_eq!(text, "");
228         apply_document_changes(
229             &mut text,
230             vec![TextDocumentContentChangeEvent {
231                 range: None,
232                 range_length: None,
233                 text: String::from("the"),
234             }],
235         );
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(
246             &mut text,
247             c![0, 0; 0, 0 => "the ", 1, 4; 1, 4 => " quiet", 1, 16; 1, 16 => "s\n"],
248         );
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(
253             &mut text,
254             c![1, 0; 1, 0 => "DREAM", 2, 0; 2, 0 => "they ", 3, 0; 3, 0 => "DON'T THEY?"],
255         );
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");
259
260         text = String::from("❤️");
261         apply_document_changes(&mut text, c![0, 0; 0, 0 => "a"]);
262         assert_eq!(text, "a❤️");
263
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");
267
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");
271     }
272
273     #[test]
274     fn empty_completion_disjoint_tests() {
275         let empty_completion =
276             CompletionItem::new_simple("label".to_string(), "detail".to_string());
277
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(),
281         );
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(),
285         );
286
287         let joint_edit = lsp_types::TextEdit::new(
288             Range::new(Position::new(1, 1), Position::new(5, 5)),
289             "new_text".to_string(),
290         );
291
292         assert!(
293             all_edits_are_disjoint(&empty_completion, &[]),
294             "Empty completion has all its edits disjoint"
295         );
296         assert!(
297             all_edits_are_disjoint(
298                 &empty_completion,
299                 &[disjoint_edit_1.clone(), disjoint_edit_2.clone()]
300             ),
301             "Empty completion is disjoint to whatever disjoint extra edits added"
302         );
303
304         assert!(
305             !all_edits_are_disjoint(
306                 &empty_completion,
307                 &[disjoint_edit_1, disjoint_edit_2, joint_edit]
308             ),
309             "Empty completion does not prevent joint extra edits from failing the validation"
310         );
311     }
312
313     #[test]
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(),
318         );
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(),
322         );
323         let joint_edit = lsp_types::TextEdit::new(
324             Range::new(Position::new(1, 1), Position::new(5, 5)),
325             "new_text".to_string(),
326         );
327
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()]);
332         assert!(
333             !all_edits_are_disjoint(&completion_with_joint_edits, &[]),
334             "Completion with disjoint edits fails the validation even with empty extra edits"
335         );
336
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()]);
340         assert!(
341             !all_edits_are_disjoint(&completion_with_joint_edits, &[]),
342             "Completion with disjoint edits fails the validation even with empty extra edits"
343         );
344
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,
350             }));
351         completion_with_joint_edits.additional_text_edits = Some(vec![joint_edit]);
352         assert!(
353             !all_edits_are_disjoint(&completion_with_joint_edits, &[]),
354             "Completion with disjoint edits fails the validation even with empty extra edits"
355         );
356     }
357
358     #[test]
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(),
363         );
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(),
367         );
368         let joint_edit = lsp_types::TextEdit::new(
369             Range::new(Position::new(1, 1), Position::new(5, 5)),
370             "new_text".to_string(),
371         );
372
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;
377
378         assert!(
379             all_edits_are_disjoint(&completion_with_disjoint_edits, &[]),
380             "Completion with disjoint edits is valid"
381         );
382         assert!(
383             !all_edits_are_disjoint(&completion_with_disjoint_edits, &[joint_edit]),
384             "Completion with disjoint edits and joint extra edit is invalid"
385         );
386         assert!(
387             all_edits_are_disjoint(&completion_with_disjoint_edits, &[disjoint_edit_2]),
388             "Completion with disjoint edits and joint extra edit is valid"
389         );
390     }
391 }