Skip to main content

rust_analyzer/lsp/
utils.rs

1//! Utilities for LSP-related boilerplate code.
2use std::{mem, ops::Range, vec};
3
4use lsp_server::Notification;
5use lsp_types::{MessageActionItem, Request};
6use triomphe::Arc;
7use vfs::LineEndings;
8
9use crate::{
10    global_state::GlobalState,
11    line_index::{LineIndex, PositionEncoding},
12    lsp::{LspError, from_proto},
13    lsp_ext,
14};
15
16pub(crate) fn invalid_params_error(message: String) -> LspError {
17    LspError { code: lsp_server::ErrorCode::InvalidParams as i32, message }
18}
19
20pub(crate) fn notification_is<N: lsp_types::Notification>(notification: &Notification) -> bool {
21    notification.method.as_str() == N::METHOD.as_str()
22}
23
24#[derive(Debug, Eq, PartialEq)]
25pub(crate) enum Progress {
26    Begin,
27    Report,
28    End,
29}
30
31impl Progress {
32    pub(crate) fn fraction(done: usize, total: usize) -> f64 {
33        assert!(done <= total);
34        done as f64 / total.max(1) as f64
35    }
36}
37
38impl GlobalState {
39    pub(crate) fn show_message(
40        &mut self,
41        kind: lsp_types::MessageType,
42        message: String,
43        show_open_log_button: bool,
44    ) {
45        match self.config.open_server_logs() && show_open_log_button {
46            true => self.send_request::<lsp_types::ShowMessageRequest>(
47                lsp_types::ShowMessageRequestParams {
48                    kind,
49                    message,
50                    actions: Some(vec![lsp_types::MessageActionItem {
51                        title: "Open server logs".to_owned(),
52                        properties: Default::default(),
53                    }]),
54                },
55                |this, resp| {
56                    let lsp_server::Response { error: None, result: Some(result), .. } = resp
57                    else {
58                        return;
59                    };
60                    if let Ok(Some(_item)) = crate::from_json::<Option<MessageActionItem>>(
61                        lsp_types::ShowMessageRequest::METHOD.as_str(),
62                        &result,
63                    ) {
64                        this.send_notification::<lsp_ext::OpenServerLogsNotification>(());
65                    }
66                },
67            ),
68            false => self.send_notification::<lsp_types::ShowMessageNotification>(
69                lsp_types::ShowMessageParams { kind, message },
70            ),
71        }
72    }
73
74    /// If `additional_info` is [`Some`], appends a note to the notification telling to check the logs.
75    /// This will always log `message` + `additional_info` to the server's error log.
76    pub(crate) fn show_and_log_error(&mut self, message: String, additional_info: Option<String>) {
77        match additional_info {
78            Some(additional_info) => {
79                tracing::error!("{message}:\n{additional_info}");
80                self.show_message(
81                    lsp_types::MessageType::Error,
82                    message,
83                    tracing::enabled!(tracing::Level::ERROR),
84                );
85            }
86            None => {
87                tracing::error!("{message}");
88                self.send_notification::<lsp_types::ShowMessageNotification>(
89                    lsp_types::ShowMessageParams { kind: lsp_types::MessageType::Error, message },
90                );
91            }
92        }
93    }
94
95    /// rust-analyzer is resilient -- if it fails, this doesn't usually affect
96    /// the user experience. Part of that is that we deliberately hide panics
97    /// from the user.
98    ///
99    /// We do however want to pester rust-analyzer developers with panics and
100    /// other "you really gotta fix that" messages. The current strategy is to
101    /// be noisy for "from source" builds or when profiling is enabled.
102    ///
103    /// It's unclear if making from source `cargo xtask install` builds more
104    /// panicky is a good idea, let's see if we can keep our awesome bleeding
105    /// edge users from being upset!
106    pub(crate) fn poke_rust_analyzer_developer(&mut self, message: String) {
107        let from_source_build = option_env!("POKE_RA_DEVS").is_some();
108        if from_source_build {
109            self.show_and_log_error(message, None);
110        }
111    }
112
113    pub(crate) fn report_progress(
114        &mut self,
115        title: &str,
116        state: Progress,
117        message: Option<String>,
118        fraction: Option<f64>,
119        cancel_token: Option<String>,
120    ) {
121        if !self.config.work_done_progress() {
122            return;
123        }
124        let percentage = fraction.map(|f| {
125            assert!((0.0..=1.0).contains(&f));
126            (f * 100.0) as u32
127        });
128        let cancellable = Some(cancel_token.is_some());
129        let token = lsp_types::ProgressToken::String(
130            cancel_token.unwrap_or_else(|| format!("rustAnalyzer/{title}")),
131        );
132        tracing::debug!(?token, ?state, "report_progress {message:?}");
133        match state {
134            Progress::Begin => {
135                self.send_request::<lsp_types::WorkDoneProgressCreateRequest>(
136                    lsp_types::WorkDoneProgressCreateParams { token: token.clone() },
137                    |_, _| (),
138                );
139
140                self.send_notification::<lsp_types::ProgressNotification>(
141                    lsp_types::ProgressParams {
142                        token,
143                        value: serde_json::to_value(lsp_types::WorkDoneProgressBegin {
144                            title: title.into(),
145                            cancellable,
146                            message,
147                            percentage,
148                        })
149                        .unwrap(),
150                    },
151                );
152            }
153            Progress::Report => {
154                self.send_notification::<lsp_types::ProgressNotification>(
155                    lsp_types::ProgressParams {
156                        token,
157                        value: serde_json::to_value(lsp_types::WorkDoneProgressReport {
158                            cancellable,
159                            message,
160                            percentage,
161                        })
162                        .unwrap(),
163                    },
164                );
165            }
166            Progress::End => {
167                self.send_notification::<lsp_types::ProgressNotification>(
168                    lsp_types::ProgressParams {
169                        token,
170                        value: serde_json::to_value(lsp_types::WorkDoneProgressEnd { message })
171                            .unwrap(),
172                    },
173                );
174            }
175        }
176    }
177}
178
179pub(crate) fn apply_document_changes(
180    encoding: PositionEncoding,
181    file_contents: &str,
182    mut content_changes: Vec<lsp_types::TextDocumentContentChangeEvent>,
183) -> String {
184    // If at least one of the changes is a full document change, use the last
185    // of them as the starting point and ignore all previous changes.
186    let (mut text, r_partial_changes);
187    match content_changes.iter_mut().rev().try_fold(Vec::new(), |mut acc, change| match change {
188        lsp_types::TextDocumentContentChangeEvent::TextDocumentContentChangePartial(partial) => {
189            acc.push(partial);
190            Ok(acc)
191        }
192        lsp_types::TextDocumentContentChangeEvent::TextDocumentContentChangeWholeDocument(
193            whole,
194        ) => Err((whole, acc)),
195    }) {
196        Err((whole_document, reversed_partial_changes)) => {
197            text = mem::take(&mut whole_document.text);
198            r_partial_changes = reversed_partial_changes;
199        }
200        Ok(partials) => {
201            text = file_contents.to_owned();
202            r_partial_changes = partials;
203        }
204    }
205    if r_partial_changes.is_empty() {
206        return text;
207    }
208
209    let mut line_index = LineIndex {
210        // the index will be overwritten in the bottom loop's first iteration
211        index: Arc::new(ide::LineIndex::new(&text)),
212        // We don't care about line endings here.
213        endings: LineEndings::Unix,
214        encoding,
215    };
216
217    // The changes we got must be applied sequentially, but can cross lines so we
218    // have to keep our line index updated.
219    // Some clients (e.g. Code) sort the ranges in reverse. As an optimization, we
220    // remember the last valid line in the index and only rebuild it if needed.
221    // The VFS will normalize the end of lines to `\n`.
222    let mut index_valid = !0u32;
223    for change in r_partial_changes.iter().rev() {
224        if index_valid <= change.range.end.line {
225            *Arc::make_mut(&mut line_index.index) = ide::LineIndex::new(&text);
226        }
227        index_valid = change.range.start.line;
228        if let Ok(range) = from_proto::text_range(&line_index, change.range) {
229            text.replace_range(Range::<usize>::from(range), &change.text);
230        }
231    }
232    text
233}
234
235/// Checks that the edits inside the completion and the additional edits do not overlap.
236/// LSP explicitly forbids the additional edits to overlap both with the main edit and themselves.
237pub(crate) fn all_edits_are_disjoint(
238    completion: &lsp_types::CompletionItem,
239    additional_edits: &[lsp_types::TextEdit],
240) -> bool {
241    let mut edit_ranges = Vec::new();
242    match completion.text_edit.as_ref() {
243        Some(lsp_types::CompletionItemTextEdit::TextEdit(edit)) => {
244            edit_ranges.push(edit.range);
245        }
246        Some(lsp_types::CompletionItemTextEdit::InsertReplaceEdit(edit)) => {
247            let replace = edit.replace;
248            let insert = edit.insert;
249            if replace.start != insert.start
250                || insert.start > insert.end
251                || insert.end > replace.end
252            {
253                // insert has to be a prefix of replace but it is not
254                return false;
255            }
256            edit_ranges.push(replace);
257        }
258        None => {}
259    }
260    if let Some(additional_changes) = completion.additional_text_edits.as_ref() {
261        edit_ranges.extend(additional_changes.iter().map(|edit| edit.range));
262    };
263    edit_ranges.extend(additional_edits.iter().map(|edit| edit.range));
264    edit_ranges.sort_by_key(|range| (range.start, range.end));
265    edit_ranges
266        .iter()
267        .zip(edit_ranges.iter().skip(1))
268        .all(|(previous, next)| previous.end <= next.start)
269}
270
271#[cfg(test)]
272mod tests {
273    use ide_db::line_index::WideEncoding;
274    use lsp_types::{CompletionItem, InsertReplaceEdit, Position, Range};
275
276    use super::*;
277
278    #[test]
279    fn test_apply_document_changes() {
280        macro_rules! c {
281            [$($sl:expr, $sc:expr; $el:expr, $ec:expr => $text:expr),+] => {
282                vec![$(::lsp_types::TextDocumentContentChangeEvent::TextDocumentContentChangePartial(lsp_types::TextDocumentContentChangePartial {
283                    range: Range {
284                        start: Position { line: $sl, character: $sc },
285                        end: Position { line: $el, character: $ec },
286                    },
287                    text: String::from($text),
288                    ..Default::default()
289                })),+]
290            };
291        }
292
293        let encoding = PositionEncoding::Wide(WideEncoding::Utf16);
294        let text = apply_document_changes(encoding, "", vec![]);
295        assert_eq!(text, "");
296        let text = apply_document_changes(
297            encoding,
298            &text,
299            vec![
300                lsp_types::TextDocumentContentChangeEvent::TextDocumentContentChangeWholeDocument(
301                    lsp_types::TextDocumentContentChangeWholeDocument { text: String::from("the") },
302                ),
303            ],
304        );
305        assert_eq!(text, "the");
306        let text = apply_document_changes(encoding, &text, c![0, 3; 0, 3 => " quick"]);
307        assert_eq!(text, "the quick");
308        let text =
309            apply_document_changes(encoding, &text, c![0, 0; 0, 4 => "", 0, 5; 0, 5 => " foxes"]);
310        assert_eq!(text, "quick foxes");
311        let text = apply_document_changes(encoding, &text, c![0, 11; 0, 11 => "\ndream"]);
312        assert_eq!(text, "quick foxes\ndream");
313        let text = apply_document_changes(encoding, &text, c![1, 0; 1, 0 => "have "]);
314        assert_eq!(text, "quick foxes\nhave dream");
315        let text = apply_document_changes(
316            encoding,
317            &text,
318            c![0, 0; 0, 0 => "the ", 1, 4; 1, 4 => " quiet", 1, 16; 1, 16 => "s\n"],
319        );
320        assert_eq!(text, "the quick foxes\nhave quiet dreams\n");
321        let text =
322            apply_document_changes(encoding, &text, c![0, 15; 0, 15 => "\n", 2, 17; 2, 17 => "\n"]);
323        assert_eq!(text, "the quick foxes\n\nhave quiet dreams\n\n");
324        let text = apply_document_changes(
325            encoding,
326            &text,
327            c![1, 0; 1, 0 => "DREAM", 2, 0; 2, 0 => "they ", 3, 0; 3, 0 => "DON'T THEY?"],
328        );
329        assert_eq!(text, "the quick foxes\nDREAM\nthey have quiet dreams\nDON'T THEY?\n");
330        let text =
331            apply_document_changes(encoding, &text, c![0, 10; 1, 5 => "", 2, 0; 2, 12 => ""]);
332        assert_eq!(text, "the quick \nthey have quiet dreams\n");
333
334        let text = String::from("❤️");
335        let text = apply_document_changes(encoding, &text, c![0, 0; 0, 0 => "a"]);
336        assert_eq!(text, "a❤️");
337
338        let text = String::from("a\nb");
339        let text =
340            apply_document_changes(encoding, &text, c![0, 1; 1, 0 => "\nțc", 0, 1; 1, 1 => "d"]);
341        assert_eq!(text, "adcb");
342
343        let text = String::from("a\nb");
344        let text =
345            apply_document_changes(encoding, &text, c![0, 1; 1, 0 => "ț\nc", 0, 2; 0, 2 => "c"]);
346        assert_eq!(text, "ațc\ncb");
347    }
348
349    #[test]
350    fn empty_completion_disjoint_tests() {
351        let empty_completion = CompletionItem {
352            label: "label".to_owned(),
353            detail: Some("detail".to_owned()),
354            ..Default::default()
355        };
356
357        let disjoint_edit_1 = lsp_types::TextEdit::new(
358            Range::new(Position::new(2, 2), Position::new(3, 3)),
359            "new_text".to_owned(),
360        );
361        let disjoint_edit_2 = lsp_types::TextEdit::new(
362            Range::new(Position::new(3, 3), Position::new(4, 4)),
363            "new_text".to_owned(),
364        );
365
366        let joint_edit = lsp_types::TextEdit::new(
367            Range::new(Position::new(1, 1), Position::new(5, 5)),
368            "new_text".to_owned(),
369        );
370
371        assert!(
372            all_edits_are_disjoint(&empty_completion, &[]),
373            "Empty completion has all its edits disjoint"
374        );
375        assert!(
376            all_edits_are_disjoint(
377                &empty_completion,
378                &[disjoint_edit_1.clone(), disjoint_edit_2.clone()]
379            ),
380            "Empty completion is disjoint to whatever disjoint extra edits added"
381        );
382
383        assert!(
384            !all_edits_are_disjoint(
385                &empty_completion,
386                &[disjoint_edit_1, disjoint_edit_2, joint_edit]
387            ),
388            "Empty completion does not prevent joint extra edits from failing the validation"
389        );
390    }
391
392    #[test]
393    fn completion_with_joint_edits_disjoint_tests() {
394        let disjoint_edit = lsp_types::TextEdit::new(
395            Range::new(Position::new(1, 1), Position::new(2, 2)),
396            "new_text".to_owned(),
397        );
398        let disjoint_edit_2 = lsp_types::TextEdit::new(
399            Range::new(Position::new(2, 2), Position::new(3, 3)),
400            "new_text".to_owned(),
401        );
402        let joint_edit = lsp_types::TextEdit::new(
403            Range::new(Position::new(1, 1), Position::new(5, 5)),
404            "new_text".to_owned(),
405        );
406
407        let mut completion_with_joint_edits = CompletionItem {
408            label: "label".to_owned(),
409            detail: Some("detail".to_owned()),
410            additional_text_edits: Some(vec![disjoint_edit.clone(), joint_edit.clone()]),
411            ..Default::default()
412        };
413        assert!(
414            !all_edits_are_disjoint(&completion_with_joint_edits, &[]),
415            "Completion with disjoint edits fails the validation even with empty extra edits"
416        );
417
418        completion_with_joint_edits.text_edit =
419            Some(lsp_types::CompletionItemTextEdit::TextEdit(disjoint_edit.clone()));
420        completion_with_joint_edits.additional_text_edits = Some(vec![joint_edit.clone()]);
421        assert!(
422            !all_edits_are_disjoint(&completion_with_joint_edits, &[]),
423            "Completion with disjoint edits fails the validation even with empty extra edits"
424        );
425
426        completion_with_joint_edits.text_edit =
427            Some(lsp_types::CompletionItemTextEdit::InsertReplaceEdit(InsertReplaceEdit {
428                new_text: "new_text".to_owned(),
429                insert: disjoint_edit.range,
430                replace: disjoint_edit_2.range,
431            }));
432        completion_with_joint_edits.additional_text_edits = Some(vec![joint_edit]);
433        assert!(
434            !all_edits_are_disjoint(&completion_with_joint_edits, &[]),
435            "Completion with disjoint edits fails the validation even with empty extra edits"
436        );
437    }
438
439    #[test]
440    fn completion_with_disjoint_edits_disjoint_tests() {
441        let disjoint_edit = lsp_types::TextEdit::new(
442            Range::new(Position::new(1, 1), Position::new(2, 2)),
443            "new_text".to_owned(),
444        );
445        let disjoint_edit_2 = lsp_types::TextEdit::new(
446            Range::new(Position::new(2, 2), Position::new(3, 3)),
447            "new_text".to_owned(),
448        );
449        let joint_edit = lsp_types::TextEdit::new(
450            Range::new(Position::new(1, 1), Position::new(5, 5)),
451            "new_text".to_owned(),
452        );
453
454        let completion_with_disjoint_edits = CompletionItem {
455            label: "label".to_owned(),
456            detail: Some("detail".to_owned()),
457            text_edit: Some(lsp_types::CompletionItemTextEdit::TextEdit(disjoint_edit)),
458            ..Default::default()
459        };
460
461        assert!(
462            all_edits_are_disjoint(&completion_with_disjoint_edits, &[]),
463            "Completion with disjoint edits is valid"
464        );
465        assert!(
466            !all_edits_are_disjoint(&completion_with_disjoint_edits, &[joint_edit]),
467            "Completion with disjoint edits and joint extra edit is invalid"
468        );
469        assert!(
470            all_edits_are_disjoint(&completion_with_disjoint_edits, &[disjoint_edit_2]),
471            "Completion with disjoint edits and joint extra edit is valid"
472        );
473    }
474}