]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/rust-analyzer/src/handlers.rs
Auto merge of #100502 - chenyukang:fix-100478, r=jackh726
[rust.git] / src / tools / rust-analyzer / crates / rust-analyzer / src / handlers.rs
1 //! This module is responsible for implementing handlers for Language Server
2 //! Protocol. The majority of requests are fulfilled by calling into the
3 //! `ide` crate.
4
5 use std::{
6     io::Write as _,
7     process::{self, Stdio},
8 };
9
10 use anyhow::Context;
11 use ide::{
12     AnnotationConfig, AssistKind, AssistResolveStrategy, FileId, FilePosition, FileRange,
13     HoverAction, HoverGotoTypeData, Query, RangeInfo, Runnable, RunnableKind, SingleResolve,
14     SourceChange, TextEdit,
15 };
16 use ide_db::SymbolKind;
17 use lsp_server::ErrorCode;
18 use lsp_types::{
19     CallHierarchyIncomingCall, CallHierarchyIncomingCallsParams, CallHierarchyItem,
20     CallHierarchyOutgoingCall, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams,
21     CodeLens, CompletionItem, Diagnostic, DiagnosticTag, DocumentFormattingParams, FoldingRange,
22     FoldingRangeParams, HoverContents, InlayHint, InlayHintParams, Location, LocationLink,
23     NumberOrString, Position, PrepareRenameResponse, Range, RenameParams,
24     SemanticTokensDeltaParams, SemanticTokensFullDeltaResult, SemanticTokensParams,
25     SemanticTokensRangeParams, SemanticTokensRangeResult, SemanticTokensResult, SymbolInformation,
26     SymbolTag, TextDocumentIdentifier, Url, WorkspaceEdit,
27 };
28 use project_model::{ManifestPath, ProjectWorkspace, TargetKind};
29 use serde_json::json;
30 use stdx::{format_to, never};
31 use syntax::{algo, ast, AstNode, TextRange, TextSize, T};
32 use vfs::AbsPathBuf;
33
34 use crate::{
35     cargo_target_spec::CargoTargetSpec,
36     config::{RustfmtConfig, WorkspaceSymbolConfig},
37     diff::diff,
38     from_proto,
39     global_state::{GlobalState, GlobalStateSnapshot},
40     line_index::LineEndings,
41     lsp_ext::{self, PositionOrRange, ViewCrateGraphParams, WorkspaceSymbolParams},
42     lsp_utils::{all_edits_are_disjoint, invalid_params_error},
43     to_proto, LspError, Result,
44 };
45
46 pub(crate) fn handle_workspace_reload(state: &mut GlobalState, _: ()) -> Result<()> {
47     state.proc_macro_clients.clear();
48     state.proc_macro_changed = false;
49     state.fetch_workspaces_queue.request_op("reload workspace request".to_string());
50     state.fetch_build_data_queue.request_op("reload workspace request".to_string());
51     Ok(())
52 }
53
54 pub(crate) fn handle_cancel_flycheck(state: &mut GlobalState, _: ()) -> Result<()> {
55     let _p = profile::span("handle_stop_flycheck");
56     state.flycheck.iter().for_each(|flycheck| flycheck.cancel());
57     Ok(())
58 }
59
60 pub(crate) fn handle_analyzer_status(
61     snap: GlobalStateSnapshot,
62     params: lsp_ext::AnalyzerStatusParams,
63 ) -> Result<String> {
64     let _p = profile::span("handle_analyzer_status");
65
66     let mut buf = String::new();
67
68     let mut file_id = None;
69     if let Some(tdi) = params.text_document {
70         match from_proto::file_id(&snap, &tdi.uri) {
71             Ok(it) => file_id = Some(it),
72             Err(_) => format_to!(buf, "file {} not found in vfs", tdi.uri),
73         }
74     }
75
76     if snap.workspaces.is_empty() {
77         buf.push_str("No workspaces\n")
78     } else {
79         buf.push_str("Workspaces:\n");
80         format_to!(
81             buf,
82             "Loaded {:?} packages across {} workspace{}.\n",
83             snap.workspaces.iter().map(|w| w.n_packages()).sum::<usize>(),
84             snap.workspaces.len(),
85             if snap.workspaces.len() == 1 { "" } else { "s" }
86         );
87     }
88     buf.push_str("\nAnalysis:\n");
89     buf.push_str(
90         &snap
91             .analysis
92             .status(file_id)
93             .unwrap_or_else(|_| "Analysis retrieval was cancelled".to_owned()),
94     );
95     Ok(buf)
96 }
97
98 pub(crate) fn handle_memory_usage(state: &mut GlobalState, _: ()) -> Result<String> {
99     let _p = profile::span("handle_memory_usage");
100     let mut mem = state.analysis_host.per_query_memory_usage();
101     mem.push(("Remaining".into(), profile::memory_usage().allocated));
102
103     let mut out = String::new();
104     for (name, bytes) in mem {
105         format_to!(out, "{:>8} {}\n", bytes, name);
106     }
107     Ok(out)
108 }
109
110 pub(crate) fn handle_shuffle_crate_graph(state: &mut GlobalState, _: ()) -> Result<()> {
111     state.analysis_host.shuffle_crate_graph();
112     Ok(())
113 }
114
115 pub(crate) fn handle_syntax_tree(
116     snap: GlobalStateSnapshot,
117     params: lsp_ext::SyntaxTreeParams,
118 ) -> Result<String> {
119     let _p = profile::span("handle_syntax_tree");
120     let id = from_proto::file_id(&snap, &params.text_document.uri)?;
121     let line_index = snap.file_line_index(id)?;
122     let text_range = params.range.and_then(|r| from_proto::text_range(&line_index, r).ok());
123     let res = snap.analysis.syntax_tree(id, text_range)?;
124     Ok(res)
125 }
126
127 pub(crate) fn handle_view_hir(
128     snap: GlobalStateSnapshot,
129     params: lsp_types::TextDocumentPositionParams,
130 ) -> Result<String> {
131     let _p = profile::span("handle_view_hir");
132     let position = from_proto::file_position(&snap, params)?;
133     let res = snap.analysis.view_hir(position)?;
134     Ok(res)
135 }
136
137 pub(crate) fn handle_view_file_text(
138     snap: GlobalStateSnapshot,
139     params: lsp_types::TextDocumentIdentifier,
140 ) -> Result<String> {
141     let file_id = from_proto::file_id(&snap, &params.uri)?;
142     Ok(snap.analysis.file_text(file_id)?.to_string())
143 }
144
145 pub(crate) fn handle_view_item_tree(
146     snap: GlobalStateSnapshot,
147     params: lsp_ext::ViewItemTreeParams,
148 ) -> Result<String> {
149     let _p = profile::span("handle_view_item_tree");
150     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
151     let res = snap.analysis.view_item_tree(file_id)?;
152     Ok(res)
153 }
154
155 pub(crate) fn handle_view_crate_graph(
156     snap: GlobalStateSnapshot,
157     params: ViewCrateGraphParams,
158 ) -> Result<String> {
159     let _p = profile::span("handle_view_crate_graph");
160     let dot = snap.analysis.view_crate_graph(params.full)??;
161     Ok(dot)
162 }
163
164 pub(crate) fn handle_expand_macro(
165     snap: GlobalStateSnapshot,
166     params: lsp_ext::ExpandMacroParams,
167 ) -> Result<Option<lsp_ext::ExpandedMacro>> {
168     let _p = profile::span("handle_expand_macro");
169     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
170     let line_index = snap.file_line_index(file_id)?;
171     let offset = from_proto::offset(&line_index, params.position)?;
172
173     let res = snap.analysis.expand_macro(FilePosition { file_id, offset })?;
174     Ok(res.map(|it| lsp_ext::ExpandedMacro { name: it.name, expansion: it.expansion }))
175 }
176
177 pub(crate) fn handle_selection_range(
178     snap: GlobalStateSnapshot,
179     params: lsp_types::SelectionRangeParams,
180 ) -> Result<Option<Vec<lsp_types::SelectionRange>>> {
181     let _p = profile::span("handle_selection_range");
182     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
183     let line_index = snap.file_line_index(file_id)?;
184     let res: Result<Vec<lsp_types::SelectionRange>> = params
185         .positions
186         .into_iter()
187         .map(|position| {
188             let offset = from_proto::offset(&line_index, position)?;
189             let mut ranges = Vec::new();
190             {
191                 let mut range = TextRange::new(offset, offset);
192                 loop {
193                     ranges.push(range);
194                     let frange = FileRange { file_id, range };
195                     let next = snap.analysis.extend_selection(frange)?;
196                     if next == range {
197                         break;
198                     } else {
199                         range = next
200                     }
201                 }
202             }
203             let mut range = lsp_types::SelectionRange {
204                 range: to_proto::range(&line_index, *ranges.last().unwrap()),
205                 parent: None,
206             };
207             for &r in ranges.iter().rev().skip(1) {
208                 range = lsp_types::SelectionRange {
209                     range: to_proto::range(&line_index, r),
210                     parent: Some(Box::new(range)),
211                 }
212             }
213             Ok(range)
214         })
215         .collect();
216
217     Ok(Some(res?))
218 }
219
220 pub(crate) fn handle_matching_brace(
221     snap: GlobalStateSnapshot,
222     params: lsp_ext::MatchingBraceParams,
223 ) -> Result<Vec<Position>> {
224     let _p = profile::span("handle_matching_brace");
225     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
226     let line_index = snap.file_line_index(file_id)?;
227     params
228         .positions
229         .into_iter()
230         .map(|position| {
231             let offset = from_proto::offset(&line_index, position);
232             offset.map(|offset| {
233                 let offset = match snap.analysis.matching_brace(FilePosition { file_id, offset }) {
234                     Ok(Some(matching_brace_offset)) => matching_brace_offset,
235                     Err(_) | Ok(None) => offset,
236                 };
237                 to_proto::position(&line_index, offset)
238             })
239         })
240         .collect()
241 }
242
243 pub(crate) fn handle_join_lines(
244     snap: GlobalStateSnapshot,
245     params: lsp_ext::JoinLinesParams,
246 ) -> Result<Vec<lsp_types::TextEdit>> {
247     let _p = profile::span("handle_join_lines");
248
249     let config = snap.config.join_lines();
250     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
251     let line_index = snap.file_line_index(file_id)?;
252
253     let mut res = TextEdit::default();
254     for range in params.ranges {
255         let range = from_proto::text_range(&line_index, range)?;
256         let edit = snap.analysis.join_lines(&config, FileRange { file_id, range })?;
257         match res.union(edit) {
258             Ok(()) => (),
259             Err(_edit) => {
260                 // just ignore overlapping edits
261             }
262         }
263     }
264
265     Ok(to_proto::text_edit_vec(&line_index, res))
266 }
267
268 pub(crate) fn handle_on_enter(
269     snap: GlobalStateSnapshot,
270     params: lsp_types::TextDocumentPositionParams,
271 ) -> Result<Option<Vec<lsp_ext::SnippetTextEdit>>> {
272     let _p = profile::span("handle_on_enter");
273     let position = from_proto::file_position(&snap, params)?;
274     let edit = match snap.analysis.on_enter(position)? {
275         None => return Ok(None),
276         Some(it) => it,
277     };
278     let line_index = snap.file_line_index(position.file_id)?;
279     let edit = to_proto::snippet_text_edit_vec(&line_index, true, edit);
280     Ok(Some(edit))
281 }
282
283 pub(crate) fn handle_on_type_formatting(
284     snap: GlobalStateSnapshot,
285     params: lsp_types::DocumentOnTypeFormattingParams,
286 ) -> Result<Option<Vec<lsp_ext::SnippetTextEdit>>> {
287     let _p = profile::span("handle_on_type_formatting");
288     let mut position = from_proto::file_position(&snap, params.text_document_position)?;
289     let line_index = snap.file_line_index(position.file_id)?;
290
291     // in `ide`, the `on_type` invariant is that
292     // `text.char_at(position) == typed_char`.
293     position.offset -= TextSize::of('.');
294     let char_typed = params.ch.chars().next().unwrap_or('\0');
295
296     let text = snap.analysis.file_text(position.file_id)?;
297     if stdx::never!(!text[usize::from(position.offset)..].starts_with(char_typed)) {
298         return Ok(None);
299     }
300
301     // We have an assist that inserts ` ` after typing `->` in `fn foo() ->{`,
302     // but it requires precise cursor positioning to work, and one can't
303     // position the cursor with on_type formatting. So, let's just toggle this
304     // feature off here, hoping that we'll enable it one day, ðŸ˜¿.
305     if char_typed == '>' {
306         return Ok(None);
307     }
308
309     let edit =
310         snap.analysis.on_char_typed(position, char_typed, snap.config.typing_autoclose_angle())?;
311     let edit = match edit {
312         Some(it) => it,
313         None => return Ok(None),
314     };
315
316     // This should be a single-file edit
317     let (_, text_edit) = edit.source_file_edits.into_iter().next().unwrap();
318
319     let change = to_proto::snippet_text_edit_vec(&line_index, edit.is_snippet, text_edit);
320     Ok(Some(change))
321 }
322
323 pub(crate) fn handle_document_symbol(
324     snap: GlobalStateSnapshot,
325     params: lsp_types::DocumentSymbolParams,
326 ) -> Result<Option<lsp_types::DocumentSymbolResponse>> {
327     let _p = profile::span("handle_document_symbol");
328     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
329     let line_index = snap.file_line_index(file_id)?;
330
331     let mut parents: Vec<(lsp_types::DocumentSymbol, Option<usize>)> = Vec::new();
332
333     for symbol in snap.analysis.file_structure(file_id)? {
334         let mut tags = Vec::new();
335         if symbol.deprecated {
336             tags.push(SymbolTag::DEPRECATED)
337         };
338
339         #[allow(deprecated)]
340         let doc_symbol = lsp_types::DocumentSymbol {
341             name: symbol.label,
342             detail: symbol.detail,
343             kind: to_proto::structure_node_kind(symbol.kind),
344             tags: Some(tags),
345             deprecated: Some(symbol.deprecated),
346             range: to_proto::range(&line_index, symbol.node_range),
347             selection_range: to_proto::range(&line_index, symbol.navigation_range),
348             children: None,
349         };
350         parents.push((doc_symbol, symbol.parent));
351     }
352
353     // Builds hierarchy from a flat list, in reverse order (so that indices
354     // makes sense)
355     let document_symbols = {
356         let mut acc = Vec::new();
357         while let Some((mut node, parent_idx)) = parents.pop() {
358             if let Some(children) = &mut node.children {
359                 children.reverse();
360             }
361             let parent = match parent_idx {
362                 None => &mut acc,
363                 Some(i) => parents[i].0.children.get_or_insert_with(Vec::new),
364             };
365             parent.push(node);
366         }
367         acc.reverse();
368         acc
369     };
370
371     let res = if snap.config.hierarchical_symbols() {
372         document_symbols.into()
373     } else {
374         let url = to_proto::url(&snap, file_id);
375         let mut symbol_information = Vec::<SymbolInformation>::new();
376         for symbol in document_symbols {
377             flatten_document_symbol(&symbol, None, &url, &mut symbol_information);
378         }
379         symbol_information.into()
380     };
381     return Ok(Some(res));
382
383     fn flatten_document_symbol(
384         symbol: &lsp_types::DocumentSymbol,
385         container_name: Option<String>,
386         url: &Url,
387         res: &mut Vec<SymbolInformation>,
388     ) {
389         let mut tags = Vec::new();
390
391         #[allow(deprecated)]
392         if let Some(true) = symbol.deprecated {
393             tags.push(SymbolTag::DEPRECATED)
394         }
395
396         #[allow(deprecated)]
397         res.push(SymbolInformation {
398             name: symbol.name.clone(),
399             kind: symbol.kind,
400             tags: Some(tags),
401             deprecated: symbol.deprecated,
402             location: Location::new(url.clone(), symbol.range),
403             container_name,
404         });
405
406         for child in symbol.children.iter().flatten() {
407             flatten_document_symbol(child, Some(symbol.name.clone()), url, res);
408         }
409     }
410 }
411
412 pub(crate) fn handle_workspace_symbol(
413     snap: GlobalStateSnapshot,
414     params: WorkspaceSymbolParams,
415 ) -> Result<Option<Vec<SymbolInformation>>> {
416     let _p = profile::span("handle_workspace_symbol");
417
418     let config = snap.config.workspace_symbol();
419     let (all_symbols, libs) = decide_search_scope_and_kind(&params, &config);
420     let limit = config.search_limit;
421
422     let query = {
423         let query: String = params.query.chars().filter(|&c| c != '#' && c != '*').collect();
424         let mut q = Query::new(query);
425         if !all_symbols {
426             q.only_types();
427         }
428         if libs {
429             q.libs();
430         }
431         q.limit(limit);
432         q
433     };
434     let mut res = exec_query(&snap, query)?;
435     if res.is_empty() && !all_symbols {
436         let mut query = Query::new(params.query);
437         query.limit(limit);
438         res = exec_query(&snap, query)?;
439     }
440
441     return Ok(Some(res));
442
443     fn decide_search_scope_and_kind(
444         params: &WorkspaceSymbolParams,
445         config: &WorkspaceSymbolConfig,
446     ) -> (bool, bool) {
447         // Support old-style parsing of markers in the query.
448         let mut all_symbols = params.query.contains('#');
449         let mut libs = params.query.contains('*');
450
451         // If no explicit marker was set, check request params. If that's also empty
452         // use global config.
453         if !all_symbols {
454             let search_kind = match params.search_kind {
455                 Some(ref search_kind) => search_kind,
456                 None => &config.search_kind,
457             };
458             all_symbols = match search_kind {
459                 lsp_ext::WorkspaceSymbolSearchKind::OnlyTypes => false,
460                 lsp_ext::WorkspaceSymbolSearchKind::AllSymbols => true,
461             }
462         }
463
464         if !libs {
465             let search_scope = match params.search_scope {
466                 Some(ref search_scope) => search_scope,
467                 None => &config.search_scope,
468             };
469             libs = match search_scope {
470                 lsp_ext::WorkspaceSymbolSearchScope::Workspace => false,
471                 lsp_ext::WorkspaceSymbolSearchScope::WorkspaceAndDependencies => true,
472             }
473         }
474
475         (all_symbols, libs)
476     }
477
478     fn exec_query(snap: &GlobalStateSnapshot, query: Query) -> Result<Vec<SymbolInformation>> {
479         let mut res = Vec::new();
480         for nav in snap.analysis.symbol_search(query)? {
481             let container_name = nav.container_name.as_ref().map(|v| v.to_string());
482
483             #[allow(deprecated)]
484             let info = SymbolInformation {
485                 name: nav.name.to_string(),
486                 kind: nav
487                     .kind
488                     .map(to_proto::symbol_kind)
489                     .unwrap_or(lsp_types::SymbolKind::VARIABLE),
490                 tags: None,
491                 location: to_proto::location_from_nav(snap, nav)?,
492                 container_name,
493                 deprecated: None,
494             };
495             res.push(info);
496         }
497         Ok(res)
498     }
499 }
500
501 pub(crate) fn handle_will_rename_files(
502     snap: GlobalStateSnapshot,
503     params: lsp_types::RenameFilesParams,
504 ) -> Result<Option<lsp_types::WorkspaceEdit>> {
505     let _p = profile::span("handle_will_rename_files");
506
507     let source_changes: Vec<SourceChange> = params
508         .files
509         .into_iter()
510         .filter_map(|file_rename| {
511             let from = Url::parse(&file_rename.old_uri).ok()?;
512             let to = Url::parse(&file_rename.new_uri).ok()?;
513
514             let from_path = from.to_file_path().ok()?;
515             let to_path = to.to_file_path().ok()?;
516
517             // Limit to single-level moves for now.
518             match (from_path.parent(), to_path.parent()) {
519                 (Some(p1), Some(p2)) if p1 == p2 => {
520                     if from_path.is_dir() {
521                         // add '/' to end of url -- from `file://path/to/folder` to `file://path/to/folder/`
522                         let mut old_folder_name = from_path.file_stem()?.to_str()?.to_string();
523                         old_folder_name.push('/');
524                         let from_with_trailing_slash = from.join(&old_folder_name).ok()?;
525
526                         let imitate_from_url = from_with_trailing_slash.join("mod.rs").ok()?;
527                         let new_file_name = to_path.file_name()?.to_str()?;
528                         Some((
529                             snap.url_to_file_id(&imitate_from_url).ok()?,
530                             new_file_name.to_string(),
531                         ))
532                     } else {
533                         let old_name = from_path.file_stem()?.to_str()?;
534                         let new_name = to_path.file_stem()?.to_str()?;
535                         match (old_name, new_name) {
536                             ("mod", _) => None,
537                             (_, "mod") => None,
538                             _ => Some((snap.url_to_file_id(&from).ok()?, new_name.to_string())),
539                         }
540                     }
541                 }
542                 _ => None,
543             }
544         })
545         .filter_map(|(file_id, new_name)| {
546             snap.analysis.will_rename_file(file_id, &new_name).ok()?
547         })
548         .collect();
549
550     // Drop file system edits since we're just renaming things on the same level
551     let mut source_changes = source_changes.into_iter();
552     let mut source_change = source_changes.next().unwrap_or_default();
553     source_change.file_system_edits.clear();
554     // no collect here because we want to merge text edits on same file ids
555     source_change.extend(source_changes.flat_map(|it| it.source_file_edits));
556     if source_change.source_file_edits.is_empty() {
557         Ok(None)
558     } else {
559         to_proto::workspace_edit(&snap, source_change).map(Some)
560     }
561 }
562
563 pub(crate) fn handle_goto_definition(
564     snap: GlobalStateSnapshot,
565     params: lsp_types::GotoDefinitionParams,
566 ) -> Result<Option<lsp_types::GotoDefinitionResponse>> {
567     let _p = profile::span("handle_goto_definition");
568     let position = from_proto::file_position(&snap, params.text_document_position_params)?;
569     let nav_info = match snap.analysis.goto_definition(position)? {
570         None => return Ok(None),
571         Some(it) => it,
572     };
573     let src = FileRange { file_id: position.file_id, range: nav_info.range };
574     let res = to_proto::goto_definition_response(&snap, Some(src), nav_info.info)?;
575     Ok(Some(res))
576 }
577
578 pub(crate) fn handle_goto_declaration(
579     snap: GlobalStateSnapshot,
580     params: lsp_types::request::GotoDeclarationParams,
581 ) -> Result<Option<lsp_types::request::GotoDeclarationResponse>> {
582     let _p = profile::span("handle_goto_declaration");
583     let position = from_proto::file_position(&snap, params.text_document_position_params.clone())?;
584     let nav_info = match snap.analysis.goto_declaration(position)? {
585         None => return handle_goto_definition(snap, params),
586         Some(it) => it,
587     };
588     let src = FileRange { file_id: position.file_id, range: nav_info.range };
589     let res = to_proto::goto_definition_response(&snap, Some(src), nav_info.info)?;
590     Ok(Some(res))
591 }
592
593 pub(crate) fn handle_goto_implementation(
594     snap: GlobalStateSnapshot,
595     params: lsp_types::request::GotoImplementationParams,
596 ) -> Result<Option<lsp_types::request::GotoImplementationResponse>> {
597     let _p = profile::span("handle_goto_implementation");
598     let position = from_proto::file_position(&snap, params.text_document_position_params)?;
599     let nav_info = match snap.analysis.goto_implementation(position)? {
600         None => return Ok(None),
601         Some(it) => it,
602     };
603     let src = FileRange { file_id: position.file_id, range: nav_info.range };
604     let res = to_proto::goto_definition_response(&snap, Some(src), nav_info.info)?;
605     Ok(Some(res))
606 }
607
608 pub(crate) fn handle_goto_type_definition(
609     snap: GlobalStateSnapshot,
610     params: lsp_types::request::GotoTypeDefinitionParams,
611 ) -> Result<Option<lsp_types::request::GotoTypeDefinitionResponse>> {
612     let _p = profile::span("handle_goto_type_definition");
613     let position = from_proto::file_position(&snap, params.text_document_position_params)?;
614     let nav_info = match snap.analysis.goto_type_definition(position)? {
615         None => return Ok(None),
616         Some(it) => it,
617     };
618     let src = FileRange { file_id: position.file_id, range: nav_info.range };
619     let res = to_proto::goto_definition_response(&snap, Some(src), nav_info.info)?;
620     Ok(Some(res))
621 }
622
623 pub(crate) fn handle_parent_module(
624     snap: GlobalStateSnapshot,
625     params: lsp_types::TextDocumentPositionParams,
626 ) -> Result<Option<lsp_types::GotoDefinitionResponse>> {
627     let _p = profile::span("handle_parent_module");
628     if let Ok(file_path) = &params.text_document.uri.to_file_path() {
629         if file_path.file_name().unwrap_or_default() == "Cargo.toml" {
630             // search workspaces for parent packages or fallback to workspace root
631             let abs_path_buf = match AbsPathBuf::try_from(file_path.to_path_buf()).ok() {
632                 Some(abs_path_buf) => abs_path_buf,
633                 None => return Ok(None),
634             };
635
636             let manifest_path = match ManifestPath::try_from(abs_path_buf).ok() {
637                 Some(manifest_path) => manifest_path,
638                 None => return Ok(None),
639             };
640
641             let links: Vec<LocationLink> = snap
642                 .workspaces
643                 .iter()
644                 .filter_map(|ws| match ws {
645                     ProjectWorkspace::Cargo { cargo, .. } => cargo.parent_manifests(&manifest_path),
646                     _ => None,
647                 })
648                 .flatten()
649                 .map(|parent_manifest_path| LocationLink {
650                     origin_selection_range: None,
651                     target_uri: to_proto::url_from_abs_path(&parent_manifest_path),
652                     target_range: Range::default(),
653                     target_selection_range: Range::default(),
654                 })
655                 .collect::<_>();
656             return Ok(Some(links.into()));
657         }
658
659         // check if invoked at the crate root
660         let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
661         let crate_id = match snap.analysis.crate_for(file_id)?.first() {
662             Some(&crate_id) => crate_id,
663             None => return Ok(None),
664         };
665         let cargo_spec = match CargoTargetSpec::for_file(&snap, file_id)? {
666             Some(it) => it,
667             None => return Ok(None),
668         };
669
670         if snap.analysis.crate_root(crate_id)? == file_id {
671             let cargo_toml_url = to_proto::url_from_abs_path(&cargo_spec.cargo_toml);
672             let res = vec![LocationLink {
673                 origin_selection_range: None,
674                 target_uri: cargo_toml_url,
675                 target_range: Range::default(),
676                 target_selection_range: Range::default(),
677             }]
678             .into();
679             return Ok(Some(res));
680         }
681     }
682
683     // locate parent module by semantics
684     let position = from_proto::file_position(&snap, params)?;
685     let navs = snap.analysis.parent_module(position)?;
686     let res = to_proto::goto_definition_response(&snap, None, navs)?;
687     Ok(Some(res))
688 }
689
690 pub(crate) fn handle_runnables(
691     snap: GlobalStateSnapshot,
692     params: lsp_ext::RunnablesParams,
693 ) -> Result<Vec<lsp_ext::Runnable>> {
694     let _p = profile::span("handle_runnables");
695     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
696     let line_index = snap.file_line_index(file_id)?;
697     let offset = params.position.and_then(|it| from_proto::offset(&line_index, it).ok());
698     let cargo_spec = CargoTargetSpec::for_file(&snap, file_id)?;
699
700     let expect_test = match offset {
701         Some(offset) => {
702             let source_file = snap.analysis.parse(file_id)?;
703             algo::find_node_at_offset::<ast::MacroCall>(source_file.syntax(), offset)
704                 .and_then(|it| it.path()?.segment()?.name_ref())
705                 .map_or(false, |it| it.text() == "expect" || it.text() == "expect_file")
706         }
707         None => false,
708     };
709
710     let mut res = Vec::new();
711     for runnable in snap.analysis.runnables(file_id)? {
712         if should_skip_for_offset(&runnable, offset) {
713             continue;
714         }
715         if should_skip_target(&runnable, cargo_spec.as_ref()) {
716             continue;
717         }
718         let mut runnable = to_proto::runnable(&snap, runnable)?;
719         if expect_test {
720             runnable.label = format!("{} + expect", runnable.label);
721             runnable.args.expect_test = Some(true);
722         }
723         res.push(runnable);
724     }
725
726     // Add `cargo check` and `cargo test` for all targets of the whole package
727     let config = snap.config.runnables();
728     match cargo_spec {
729         Some(spec) => {
730             for cmd in ["check", "test"] {
731                 res.push(lsp_ext::Runnable {
732                     label: format!("cargo {} -p {} --all-targets", cmd, spec.package),
733                     location: None,
734                     kind: lsp_ext::RunnableKind::Cargo,
735                     args: lsp_ext::CargoRunnable {
736                         workspace_root: Some(spec.workspace_root.clone().into()),
737                         override_cargo: config.override_cargo.clone(),
738                         cargo_args: vec![
739                             cmd.to_string(),
740                             "--package".to_string(),
741                             spec.package.clone(),
742                             "--all-targets".to_string(),
743                         ],
744                         cargo_extra_args: config.cargo_extra_args.clone(),
745                         executable_args: Vec::new(),
746                         expect_test: None,
747                     },
748                 })
749             }
750         }
751         None => {
752             if !snap.config.linked_projects().is_empty()
753                 || !snap
754                     .config
755                     .discovered_projects
756                     .as_ref()
757                     .map(|projects| projects.is_empty())
758                     .unwrap_or(true)
759             {
760                 res.push(lsp_ext::Runnable {
761                     label: "cargo check --workspace".to_string(),
762                     location: None,
763                     kind: lsp_ext::RunnableKind::Cargo,
764                     args: lsp_ext::CargoRunnable {
765                         workspace_root: None,
766                         override_cargo: config.override_cargo,
767                         cargo_args: vec!["check".to_string(), "--workspace".to_string()],
768                         cargo_extra_args: config.cargo_extra_args,
769                         executable_args: Vec::new(),
770                         expect_test: None,
771                     },
772                 });
773             }
774         }
775     }
776     Ok(res)
777 }
778
779 fn should_skip_for_offset(runnable: &Runnable, offset: Option<TextSize>) -> bool {
780     match offset {
781         None => false,
782         _ if matches!(&runnable.kind, RunnableKind::TestMod { .. }) => false,
783         Some(offset) => !runnable.nav.full_range.contains_inclusive(offset),
784     }
785 }
786
787 pub(crate) fn handle_related_tests(
788     snap: GlobalStateSnapshot,
789     params: lsp_types::TextDocumentPositionParams,
790 ) -> Result<Vec<lsp_ext::TestInfo>> {
791     let _p = profile::span("handle_related_tests");
792     let position = from_proto::file_position(&snap, params)?;
793
794     let tests = snap.analysis.related_tests(position, None)?;
795     let mut res = Vec::new();
796     for it in tests {
797         if let Ok(runnable) = to_proto::runnable(&snap, it) {
798             res.push(lsp_ext::TestInfo { runnable })
799         }
800     }
801
802     Ok(res)
803 }
804
805 pub(crate) fn handle_completion(
806     snap: GlobalStateSnapshot,
807     params: lsp_types::CompletionParams,
808 ) -> Result<Option<lsp_types::CompletionResponse>> {
809     let _p = profile::span("handle_completion");
810     let text_document_position = params.text_document_position.clone();
811     let position = from_proto::file_position(&snap, params.text_document_position)?;
812     let completion_trigger_character =
813         params.context.and_then(|ctx| ctx.trigger_character).and_then(|s| s.chars().next());
814
815     if Some(':') == completion_trigger_character {
816         let source_file = snap.analysis.parse(position.file_id)?;
817         let left_token = source_file.syntax().token_at_offset(position.offset).left_biased();
818         let completion_triggered_after_single_colon = match left_token {
819             Some(left_token) => left_token.kind() == T![:],
820             None => true,
821         };
822         if completion_triggered_after_single_colon {
823             return Ok(None);
824         }
825     }
826
827     let completion_config = &snap.config.completion();
828     let items = match snap.analysis.completions(
829         completion_config,
830         position,
831         completion_trigger_character,
832     )? {
833         None => return Ok(None),
834         Some(items) => items,
835     };
836     let line_index = snap.file_line_index(position.file_id)?;
837
838     let items =
839         to_proto::completion_items(&snap.config, &line_index, text_document_position, items);
840
841     let completion_list = lsp_types::CompletionList { is_incomplete: true, items };
842     Ok(Some(completion_list.into()))
843 }
844
845 pub(crate) fn handle_completion_resolve(
846     snap: GlobalStateSnapshot,
847     mut original_completion: CompletionItem,
848 ) -> Result<CompletionItem> {
849     let _p = profile::span("handle_completion_resolve");
850
851     if !all_edits_are_disjoint(&original_completion, &[]) {
852         return Err(invalid_params_error(
853             "Received a completion with overlapping edits, this is not LSP-compliant".to_string(),
854         )
855         .into());
856     }
857
858     let data = match original_completion.data.take() {
859         Some(it) => it,
860         None => return Ok(original_completion),
861     };
862
863     let resolve_data: lsp_ext::CompletionResolveData = serde_json::from_value(data)?;
864
865     let file_id = from_proto::file_id(&snap, &resolve_data.position.text_document.uri)?;
866     let line_index = snap.file_line_index(file_id)?;
867     let offset = from_proto::offset(&line_index, resolve_data.position.position)?;
868
869     let additional_edits = snap
870         .analysis
871         .resolve_completion_edits(
872             &snap.config.completion(),
873             FilePosition { file_id, offset },
874             resolve_data
875                 .imports
876                 .into_iter()
877                 .map(|import| (import.full_import_path, import.imported_name)),
878         )?
879         .into_iter()
880         .flat_map(|edit| edit.into_iter().map(|indel| to_proto::text_edit(&line_index, indel)))
881         .collect::<Vec<_>>();
882
883     if !all_edits_are_disjoint(&original_completion, &additional_edits) {
884         return Err(LspError::new(
885             ErrorCode::InternalError as i32,
886             "Import edit overlaps with the original completion edits, this is not LSP-compliant"
887                 .into(),
888         )
889         .into());
890     }
891
892     if let Some(original_additional_edits) = original_completion.additional_text_edits.as_mut() {
893         original_additional_edits.extend(additional_edits.into_iter())
894     } else {
895         original_completion.additional_text_edits = Some(additional_edits);
896     }
897
898     Ok(original_completion)
899 }
900
901 pub(crate) fn handle_folding_range(
902     snap: GlobalStateSnapshot,
903     params: FoldingRangeParams,
904 ) -> Result<Option<Vec<FoldingRange>>> {
905     let _p = profile::span("handle_folding_range");
906     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
907     let folds = snap.analysis.folding_ranges(file_id)?;
908     let text = snap.analysis.file_text(file_id)?;
909     let line_index = snap.file_line_index(file_id)?;
910     let line_folding_only = snap.config.line_folding_only();
911     let res = folds
912         .into_iter()
913         .map(|it| to_proto::folding_range(&*text, &line_index, line_folding_only, it))
914         .collect();
915     Ok(Some(res))
916 }
917
918 pub(crate) fn handle_signature_help(
919     snap: GlobalStateSnapshot,
920     params: lsp_types::SignatureHelpParams,
921 ) -> Result<Option<lsp_types::SignatureHelp>> {
922     let _p = profile::span("handle_signature_help");
923     let position = from_proto::file_position(&snap, params.text_document_position_params)?;
924     let help = match snap.analysis.signature_help(position)? {
925         Some(it) => it,
926         None => return Ok(None),
927     };
928     let config = snap.config.call_info();
929     let res = to_proto::signature_help(help, config, snap.config.signature_help_label_offsets());
930     Ok(Some(res))
931 }
932
933 pub(crate) fn handle_hover(
934     snap: GlobalStateSnapshot,
935     params: lsp_ext::HoverParams,
936 ) -> Result<Option<lsp_ext::Hover>> {
937     let _p = profile::span("handle_hover");
938     let range = match params.position {
939         PositionOrRange::Position(position) => Range::new(position, position),
940         PositionOrRange::Range(range) => range,
941     };
942
943     let file_range = from_proto::file_range(&snap, params.text_document, range)?;
944     let info = match snap.analysis.hover(&snap.config.hover(), file_range)? {
945         None => return Ok(None),
946         Some(info) => info,
947     };
948
949     let line_index = snap.file_line_index(file_range.file_id)?;
950     let range = to_proto::range(&line_index, info.range);
951     let markup_kind =
952         snap.config.hover().documentation.map_or(ide::HoverDocFormat::Markdown, |kind| kind);
953     let hover = lsp_ext::Hover {
954         hover: lsp_types::Hover {
955             contents: HoverContents::Markup(to_proto::markup_content(
956                 info.info.markup,
957                 markup_kind,
958             )),
959             range: Some(range),
960         },
961         actions: if snap.config.hover_actions().none() {
962             Vec::new()
963         } else {
964             prepare_hover_actions(&snap, &info.info.actions)
965         },
966     };
967
968     Ok(Some(hover))
969 }
970
971 pub(crate) fn handle_prepare_rename(
972     snap: GlobalStateSnapshot,
973     params: lsp_types::TextDocumentPositionParams,
974 ) -> Result<Option<PrepareRenameResponse>> {
975     let _p = profile::span("handle_prepare_rename");
976     let position = from_proto::file_position(&snap, params)?;
977
978     let change = snap.analysis.prepare_rename(position)?.map_err(to_proto::rename_error)?;
979
980     let line_index = snap.file_line_index(position.file_id)?;
981     let range = to_proto::range(&line_index, change.range);
982     Ok(Some(PrepareRenameResponse::Range(range)))
983 }
984
985 pub(crate) fn handle_rename(
986     snap: GlobalStateSnapshot,
987     params: RenameParams,
988 ) -> Result<Option<WorkspaceEdit>> {
989     let _p = profile::span("handle_rename");
990     let position = from_proto::file_position(&snap, params.text_document_position)?;
991
992     let mut change =
993         snap.analysis.rename(position, &*params.new_name)?.map_err(to_proto::rename_error)?;
994
995     // this is kind of a hack to prevent double edits from happening when moving files
996     // When a module gets renamed by renaming the mod declaration this causes the file to move
997     // which in turn will trigger a WillRenameFiles request to the server for which we reply with a
998     // a second identical set of renames, the client will then apply both edits causing incorrect edits
999     // with this we only emit source_file_edits in the WillRenameFiles response which will do the rename instead
1000     // See https://github.com/microsoft/vscode-languageserver-node/issues/752 for more info
1001     if !change.file_system_edits.is_empty() && snap.config.will_rename() {
1002         change.source_file_edits.clear();
1003     }
1004     let workspace_edit = to_proto::workspace_edit(&snap, change)?;
1005     Ok(Some(workspace_edit))
1006 }
1007
1008 pub(crate) fn handle_references(
1009     snap: GlobalStateSnapshot,
1010     params: lsp_types::ReferenceParams,
1011 ) -> Result<Option<Vec<Location>>> {
1012     let _p = profile::span("handle_references");
1013     let position = from_proto::file_position(&snap, params.text_document_position)?;
1014
1015     let refs = match snap.analysis.find_all_refs(position, None)? {
1016         None => return Ok(None),
1017         Some(refs) => refs,
1018     };
1019
1020     let include_declaration = params.context.include_declaration;
1021     let locations = refs
1022         .into_iter()
1023         .flat_map(|refs| {
1024             let decl = if include_declaration {
1025                 refs.declaration.map(|decl| FileRange {
1026                     file_id: decl.nav.file_id,
1027                     range: decl.nav.focus_or_full_range(),
1028                 })
1029             } else {
1030                 None
1031             };
1032             refs.references
1033                 .into_iter()
1034                 .flat_map(|(file_id, refs)| {
1035                     refs.into_iter().map(move |(range, _)| FileRange { file_id, range })
1036                 })
1037                 .chain(decl)
1038         })
1039         .filter_map(|frange| to_proto::location(&snap, frange).ok())
1040         .collect();
1041
1042     Ok(Some(locations))
1043 }
1044
1045 pub(crate) fn handle_formatting(
1046     snap: GlobalStateSnapshot,
1047     params: DocumentFormattingParams,
1048 ) -> Result<Option<Vec<lsp_types::TextEdit>>> {
1049     let _p = profile::span("handle_formatting");
1050
1051     run_rustfmt(&snap, params.text_document, None)
1052 }
1053
1054 pub(crate) fn handle_range_formatting(
1055     snap: GlobalStateSnapshot,
1056     params: lsp_types::DocumentRangeFormattingParams,
1057 ) -> Result<Option<Vec<lsp_types::TextEdit>>> {
1058     let _p = profile::span("handle_range_formatting");
1059
1060     run_rustfmt(&snap, params.text_document, Some(params.range))
1061 }
1062
1063 pub(crate) fn handle_code_action(
1064     snap: GlobalStateSnapshot,
1065     params: lsp_types::CodeActionParams,
1066 ) -> Result<Option<Vec<lsp_ext::CodeAction>>> {
1067     let _p = profile::span("handle_code_action");
1068
1069     if !snap.config.code_action_literals() {
1070         // We intentionally don't support command-based actions, as those either
1071         // require either custom client-code or server-initiated edits. Server
1072         // initiated edits break causality, so we avoid those.
1073         return Ok(None);
1074     }
1075
1076     let line_index =
1077         snap.file_line_index(from_proto::file_id(&snap, &params.text_document.uri)?)?;
1078     let frange = from_proto::file_range(&snap, params.text_document.clone(), params.range)?;
1079
1080     let mut assists_config = snap.config.assist();
1081     assists_config.allowed = params
1082         .context
1083         .only
1084         .clone()
1085         .map(|it| it.into_iter().filter_map(from_proto::assist_kind).collect());
1086
1087     let mut res: Vec<lsp_ext::CodeAction> = Vec::new();
1088
1089     let code_action_resolve_cap = snap.config.code_action_resolve();
1090     let resolve = if code_action_resolve_cap {
1091         AssistResolveStrategy::None
1092     } else {
1093         AssistResolveStrategy::All
1094     };
1095     let assists = snap.analysis.assists_with_fixes(
1096         &assists_config,
1097         &snap.config.diagnostics(),
1098         resolve,
1099         frange,
1100     )?;
1101     for (index, assist) in assists.into_iter().enumerate() {
1102         let resolve_data =
1103             if code_action_resolve_cap { Some((index, params.clone())) } else { None };
1104         let code_action = to_proto::code_action(&snap, assist, resolve_data)?;
1105         res.push(code_action)
1106     }
1107
1108     // Fixes from `cargo check`.
1109     for fix in
1110         snap.check_fixes.values().filter_map(|it| it.get(&frange.file_id)).into_iter().flatten()
1111     {
1112         // FIXME: this mapping is awkward and shouldn't exist. Refactor
1113         // `snap.check_fixes` to not convert to LSP prematurely.
1114         let intersect_fix_range = fix
1115             .ranges
1116             .iter()
1117             .copied()
1118             .filter_map(|range| from_proto::text_range(&line_index, range).ok())
1119             .any(|fix_range| fix_range.intersect(frange.range).is_some());
1120         if intersect_fix_range {
1121             res.push(fix.action.clone());
1122         }
1123     }
1124
1125     Ok(Some(res))
1126 }
1127
1128 pub(crate) fn handle_code_action_resolve(
1129     snap: GlobalStateSnapshot,
1130     mut code_action: lsp_ext::CodeAction,
1131 ) -> Result<lsp_ext::CodeAction> {
1132     let _p = profile::span("handle_code_action_resolve");
1133     let params = match code_action.data.take() {
1134         Some(it) => it,
1135         None => return Err(invalid_params_error("code action without data".to_string()).into()),
1136     };
1137
1138     let file_id = from_proto::file_id(&snap, &params.code_action_params.text_document.uri)?;
1139     let line_index = snap.file_line_index(file_id)?;
1140     let range = from_proto::text_range(&line_index, params.code_action_params.range)?;
1141     let frange = FileRange { file_id, range };
1142
1143     let mut assists_config = snap.config.assist();
1144     assists_config.allowed = params
1145         .code_action_params
1146         .context
1147         .only
1148         .map(|it| it.into_iter().filter_map(from_proto::assist_kind).collect());
1149
1150     let (assist_index, assist_resolve) = match parse_action_id(&params.id) {
1151         Ok(parsed_data) => parsed_data,
1152         Err(e) => {
1153             return Err(invalid_params_error(format!(
1154                 "Failed to parse action id string '{}': {}",
1155                 params.id, e
1156             ))
1157             .into())
1158         }
1159     };
1160
1161     let expected_assist_id = assist_resolve.assist_id.clone();
1162     let expected_kind = assist_resolve.assist_kind;
1163
1164     let assists = snap.analysis.assists_with_fixes(
1165         &assists_config,
1166         &snap.config.diagnostics(),
1167         AssistResolveStrategy::Single(assist_resolve),
1168         frange,
1169     )?;
1170
1171     let assist = match assists.get(assist_index) {
1172         Some(assist) => assist,
1173         None => return Err(invalid_params_error(format!(
1174             "Failed to find the assist for index {} provided by the resolve request. Resolve request assist id: {}",
1175             assist_index, params.id,
1176         ))
1177         .into())
1178     };
1179     if assist.id.0 != expected_assist_id || assist.id.1 != expected_kind {
1180         return Err(invalid_params_error(format!(
1181             "Mismatching assist at index {} for the resolve parameters given. Resolve request assist id: {}, actual id: {:?}.",
1182             assist_index, params.id, assist.id
1183         ))
1184         .into());
1185     }
1186     let ca = to_proto::code_action(&snap, assist.clone(), None)?;
1187     code_action.edit = ca.edit;
1188     code_action.command = ca.command;
1189     Ok(code_action)
1190 }
1191
1192 fn parse_action_id(action_id: &str) -> Result<(usize, SingleResolve), String> {
1193     let id_parts = action_id.split(':').collect::<Vec<_>>();
1194     match id_parts.as_slice() {
1195         [assist_id_string, assist_kind_string, index_string] => {
1196             let assist_kind: AssistKind = assist_kind_string.parse()?;
1197             let index: usize = match index_string.parse() {
1198                 Ok(index) => index,
1199                 Err(e) => return Err(format!("Incorrect index string: {}", e)),
1200             };
1201             Ok((index, SingleResolve { assist_id: assist_id_string.to_string(), assist_kind }))
1202         }
1203         _ => Err("Action id contains incorrect number of segments".to_string()),
1204     }
1205 }
1206
1207 pub(crate) fn handle_code_lens(
1208     snap: GlobalStateSnapshot,
1209     params: lsp_types::CodeLensParams,
1210 ) -> Result<Option<Vec<CodeLens>>> {
1211     let _p = profile::span("handle_code_lens");
1212
1213     let lens_config = snap.config.lens();
1214     if lens_config.none() {
1215         // early return before any db query!
1216         return Ok(Some(Vec::default()));
1217     }
1218
1219     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
1220     let cargo_target_spec = CargoTargetSpec::for_file(&snap, file_id)?;
1221
1222     let annotations = snap.analysis.annotations(
1223         &AnnotationConfig {
1224             binary_target: cargo_target_spec
1225                 .map(|spec| {
1226                     matches!(
1227                         spec.target_kind,
1228                         TargetKind::Bin | TargetKind::Example | TargetKind::Test
1229                     )
1230                 })
1231                 .unwrap_or(false),
1232             annotate_runnables: lens_config.runnable(),
1233             annotate_impls: lens_config.implementations,
1234             annotate_references: lens_config.refs_adt,
1235             annotate_method_references: lens_config.method_refs,
1236             annotate_enum_variant_references: lens_config.enum_variant_refs,
1237         },
1238         file_id,
1239     )?;
1240
1241     let mut res = Vec::new();
1242     for a in annotations {
1243         to_proto::code_lens(&mut res, &snap, a)?;
1244     }
1245
1246     Ok(Some(res))
1247 }
1248
1249 pub(crate) fn handle_code_lens_resolve(
1250     snap: GlobalStateSnapshot,
1251     code_lens: CodeLens,
1252 ) -> Result<CodeLens> {
1253     let annotation = from_proto::annotation(&snap, code_lens.clone())?;
1254     let annotation = snap.analysis.resolve_annotation(annotation)?;
1255
1256     let mut acc = Vec::new();
1257     to_proto::code_lens(&mut acc, &snap, annotation)?;
1258
1259     let res = match acc.pop() {
1260         Some(it) if acc.is_empty() => it,
1261         _ => {
1262             never!();
1263             code_lens
1264         }
1265     };
1266
1267     Ok(res)
1268 }
1269
1270 pub(crate) fn handle_document_highlight(
1271     snap: GlobalStateSnapshot,
1272     params: lsp_types::DocumentHighlightParams,
1273 ) -> Result<Option<Vec<lsp_types::DocumentHighlight>>> {
1274     let _p = profile::span("handle_document_highlight");
1275     let position = from_proto::file_position(&snap, params.text_document_position_params)?;
1276     let line_index = snap.file_line_index(position.file_id)?;
1277
1278     let refs = match snap.analysis.highlight_related(snap.config.highlight_related(), position)? {
1279         None => return Ok(None),
1280         Some(refs) => refs,
1281     };
1282     let res = refs
1283         .into_iter()
1284         .map(|ide::HighlightedRange { range, category }| lsp_types::DocumentHighlight {
1285             range: to_proto::range(&line_index, range),
1286             kind: category.map(to_proto::document_highlight_kind),
1287         })
1288         .collect();
1289     Ok(Some(res))
1290 }
1291
1292 pub(crate) fn handle_ssr(
1293     snap: GlobalStateSnapshot,
1294     params: lsp_ext::SsrParams,
1295 ) -> Result<lsp_types::WorkspaceEdit> {
1296     let _p = profile::span("handle_ssr");
1297     let selections = params
1298         .selections
1299         .iter()
1300         .map(|range| from_proto::file_range(&snap, params.position.text_document.clone(), *range))
1301         .collect::<Result<Vec<_>, _>>()?;
1302     let position = from_proto::file_position(&snap, params.position)?;
1303     let source_change = snap.analysis.structural_search_replace(
1304         &params.query,
1305         params.parse_only,
1306         position,
1307         selections,
1308     )??;
1309     to_proto::workspace_edit(&snap, source_change)
1310 }
1311
1312 pub(crate) fn publish_diagnostics(
1313     snap: &GlobalStateSnapshot,
1314     file_id: FileId,
1315 ) -> Result<Vec<Diagnostic>> {
1316     let _p = profile::span("publish_diagnostics");
1317     let line_index = snap.file_line_index(file_id)?;
1318
1319     let diagnostics: Vec<Diagnostic> = snap
1320         .analysis
1321         .diagnostics(&snap.config.diagnostics(), AssistResolveStrategy::None, file_id)?
1322         .into_iter()
1323         .map(|d| Diagnostic {
1324             range: to_proto::range(&line_index, d.range),
1325             severity: Some(to_proto::diagnostic_severity(d.severity)),
1326             code: Some(NumberOrString::String(d.code.as_str().to_string())),
1327             code_description: Some(lsp_types::CodeDescription {
1328                 href: lsp_types::Url::parse(&format!(
1329                     "https://rust-analyzer.github.io/manual.html#{}",
1330                     d.code.as_str()
1331                 ))
1332                 .unwrap(),
1333             }),
1334             source: Some("rust-analyzer".to_string()),
1335             message: d.message,
1336             related_information: None,
1337             tags: if d.unused { Some(vec![DiagnosticTag::UNNECESSARY]) } else { None },
1338             data: None,
1339         })
1340         .collect();
1341     Ok(diagnostics)
1342 }
1343
1344 pub(crate) fn handle_inlay_hints(
1345     snap: GlobalStateSnapshot,
1346     params: InlayHintParams,
1347 ) -> Result<Option<Vec<InlayHint>>> {
1348     let _p = profile::span("handle_inlay_hints");
1349     let document_uri = &params.text_document.uri;
1350     let file_id = from_proto::file_id(&snap, document_uri)?;
1351     let line_index = snap.file_line_index(file_id)?;
1352     let range = from_proto::file_range(
1353         &snap,
1354         TextDocumentIdentifier::new(document_uri.to_owned()),
1355         params.range,
1356     )?;
1357     let inlay_hints_config = snap.config.inlay_hints();
1358     Ok(Some(
1359         snap.analysis
1360             .inlay_hints(&inlay_hints_config, file_id, Some(range))?
1361             .into_iter()
1362             .map(|it| {
1363                 to_proto::inlay_hint(&snap, &line_index, inlay_hints_config.render_colons, it)
1364             })
1365             .collect(),
1366     ))
1367 }
1368
1369 pub(crate) fn handle_inlay_hints_resolve(
1370     snap: GlobalStateSnapshot,
1371     mut hint: InlayHint,
1372 ) -> Result<InlayHint> {
1373     let _p = profile::span("handle_inlay_hints_resolve");
1374     let data = match hint.data.take() {
1375         Some(it) => it,
1376         None => return Ok(hint),
1377     };
1378
1379     let resolve_data: lsp_ext::InlayHintResolveData = serde_json::from_value(data)?;
1380
1381     let file_range = from_proto::file_range(
1382         &snap,
1383         resolve_data.text_document,
1384         match resolve_data.position {
1385             PositionOrRange::Position(pos) => Range::new(pos, pos),
1386             PositionOrRange::Range(range) => range,
1387         },
1388     )?;
1389     let info = match snap.analysis.hover(&snap.config.hover(), file_range)? {
1390         None => return Ok(hint),
1391         Some(info) => info,
1392     };
1393
1394     let markup_kind =
1395         snap.config.hover().documentation.map_or(ide::HoverDocFormat::Markdown, |kind| kind);
1396
1397     // FIXME: hover actions?
1398     hint.tooltip = Some(lsp_types::InlayHintTooltip::MarkupContent(to_proto::markup_content(
1399         info.info.markup,
1400         markup_kind,
1401     )));
1402     Ok(hint)
1403 }
1404
1405 pub(crate) fn handle_call_hierarchy_prepare(
1406     snap: GlobalStateSnapshot,
1407     params: CallHierarchyPrepareParams,
1408 ) -> Result<Option<Vec<CallHierarchyItem>>> {
1409     let _p = profile::span("handle_call_hierarchy_prepare");
1410     let position = from_proto::file_position(&snap, params.text_document_position_params)?;
1411
1412     let nav_info = match snap.analysis.call_hierarchy(position)? {
1413         None => return Ok(None),
1414         Some(it) => it,
1415     };
1416
1417     let RangeInfo { range: _, info: navs } = nav_info;
1418     let res = navs
1419         .into_iter()
1420         .filter(|it| it.kind == Some(SymbolKind::Function))
1421         .map(|it| to_proto::call_hierarchy_item(&snap, it))
1422         .collect::<Result<Vec<_>>>()?;
1423
1424     Ok(Some(res))
1425 }
1426
1427 pub(crate) fn handle_call_hierarchy_incoming(
1428     snap: GlobalStateSnapshot,
1429     params: CallHierarchyIncomingCallsParams,
1430 ) -> Result<Option<Vec<CallHierarchyIncomingCall>>> {
1431     let _p = profile::span("handle_call_hierarchy_incoming");
1432     let item = params.item;
1433
1434     let doc = TextDocumentIdentifier::new(item.uri);
1435     let frange = from_proto::file_range(&snap, doc, item.selection_range)?;
1436     let fpos = FilePosition { file_id: frange.file_id, offset: frange.range.start() };
1437
1438     let call_items = match snap.analysis.incoming_calls(fpos)? {
1439         None => return Ok(None),
1440         Some(it) => it,
1441     };
1442
1443     let mut res = vec![];
1444
1445     for call_item in call_items.into_iter() {
1446         let file_id = call_item.target.file_id;
1447         let line_index = snap.file_line_index(file_id)?;
1448         let item = to_proto::call_hierarchy_item(&snap, call_item.target)?;
1449         res.push(CallHierarchyIncomingCall {
1450             from: item,
1451             from_ranges: call_item
1452                 .ranges
1453                 .into_iter()
1454                 .map(|it| to_proto::range(&line_index, it))
1455                 .collect(),
1456         });
1457     }
1458
1459     Ok(Some(res))
1460 }
1461
1462 pub(crate) fn handle_call_hierarchy_outgoing(
1463     snap: GlobalStateSnapshot,
1464     params: CallHierarchyOutgoingCallsParams,
1465 ) -> Result<Option<Vec<CallHierarchyOutgoingCall>>> {
1466     let _p = profile::span("handle_call_hierarchy_outgoing");
1467     let item = params.item;
1468
1469     let doc = TextDocumentIdentifier::new(item.uri);
1470     let frange = from_proto::file_range(&snap, doc, item.selection_range)?;
1471     let fpos = FilePosition { file_id: frange.file_id, offset: frange.range.start() };
1472
1473     let call_items = match snap.analysis.outgoing_calls(fpos)? {
1474         None => return Ok(None),
1475         Some(it) => it,
1476     };
1477
1478     let mut res = vec![];
1479
1480     for call_item in call_items.into_iter() {
1481         let file_id = call_item.target.file_id;
1482         let line_index = snap.file_line_index(file_id)?;
1483         let item = to_proto::call_hierarchy_item(&snap, call_item.target)?;
1484         res.push(CallHierarchyOutgoingCall {
1485             to: item,
1486             from_ranges: call_item
1487                 .ranges
1488                 .into_iter()
1489                 .map(|it| to_proto::range(&line_index, it))
1490                 .collect(),
1491         });
1492     }
1493
1494     Ok(Some(res))
1495 }
1496
1497 pub(crate) fn handle_semantic_tokens_full(
1498     snap: GlobalStateSnapshot,
1499     params: SemanticTokensParams,
1500 ) -> Result<Option<SemanticTokensResult>> {
1501     let _p = profile::span("handle_semantic_tokens_full");
1502
1503     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
1504     let text = snap.analysis.file_text(file_id)?;
1505     let line_index = snap.file_line_index(file_id)?;
1506
1507     let mut highlight_config = snap.config.highlighting_config();
1508     // Avoid flashing a bunch of unresolved references when the proc-macro servers haven't been spawned yet.
1509     highlight_config.syntactic_name_ref_highlighting = !snap.proc_macros_loaded;
1510
1511     let highlights = snap.analysis.highlight(highlight_config, file_id)?;
1512     let semantic_tokens = to_proto::semantic_tokens(&text, &line_index, highlights);
1513
1514     // Unconditionally cache the tokens
1515     snap.semantic_tokens_cache.lock().insert(params.text_document.uri, semantic_tokens.clone());
1516
1517     Ok(Some(semantic_tokens.into()))
1518 }
1519
1520 pub(crate) fn handle_semantic_tokens_full_delta(
1521     snap: GlobalStateSnapshot,
1522     params: SemanticTokensDeltaParams,
1523 ) -> Result<Option<SemanticTokensFullDeltaResult>> {
1524     let _p = profile::span("handle_semantic_tokens_full_delta");
1525
1526     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
1527     let text = snap.analysis.file_text(file_id)?;
1528     let line_index = snap.file_line_index(file_id)?;
1529
1530     let mut highlight_config = snap.config.highlighting_config();
1531     // Avoid flashing a bunch of unresolved references when the proc-macro servers haven't been spawned yet.
1532     highlight_config.syntactic_name_ref_highlighting = !snap.proc_macros_loaded;
1533
1534     let highlights = snap.analysis.highlight(highlight_config, file_id)?;
1535     let semantic_tokens = to_proto::semantic_tokens(&text, &line_index, highlights);
1536
1537     let mut cache = snap.semantic_tokens_cache.lock();
1538     let cached_tokens = cache.entry(params.text_document.uri).or_default();
1539
1540     if let Some(prev_id) = &cached_tokens.result_id {
1541         if *prev_id == params.previous_result_id {
1542             let delta = to_proto::semantic_token_delta(cached_tokens, &semantic_tokens);
1543             *cached_tokens = semantic_tokens;
1544             return Ok(Some(delta.into()));
1545         }
1546     }
1547
1548     *cached_tokens = semantic_tokens.clone();
1549
1550     Ok(Some(semantic_tokens.into()))
1551 }
1552
1553 pub(crate) fn handle_semantic_tokens_range(
1554     snap: GlobalStateSnapshot,
1555     params: SemanticTokensRangeParams,
1556 ) -> Result<Option<SemanticTokensRangeResult>> {
1557     let _p = profile::span("handle_semantic_tokens_range");
1558
1559     let frange = from_proto::file_range(&snap, params.text_document, params.range)?;
1560     let text = snap.analysis.file_text(frange.file_id)?;
1561     let line_index = snap.file_line_index(frange.file_id)?;
1562
1563     let highlights = snap.analysis.highlight_range(snap.config.highlighting_config(), frange)?;
1564     let semantic_tokens = to_proto::semantic_tokens(&text, &line_index, highlights);
1565     Ok(Some(semantic_tokens.into()))
1566 }
1567
1568 pub(crate) fn handle_open_docs(
1569     snap: GlobalStateSnapshot,
1570     params: lsp_types::TextDocumentPositionParams,
1571 ) -> Result<Option<lsp_types::Url>> {
1572     let _p = profile::span("handle_open_docs");
1573     let position = from_proto::file_position(&snap, params)?;
1574
1575     let remote = snap.analysis.external_docs(position)?;
1576
1577     Ok(remote.and_then(|remote| Url::parse(&remote).ok()))
1578 }
1579
1580 pub(crate) fn handle_open_cargo_toml(
1581     snap: GlobalStateSnapshot,
1582     params: lsp_ext::OpenCargoTomlParams,
1583 ) -> Result<Option<lsp_types::GotoDefinitionResponse>> {
1584     let _p = profile::span("handle_open_cargo_toml");
1585     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
1586
1587     let cargo_spec = match CargoTargetSpec::for_file(&snap, file_id)? {
1588         Some(it) => it,
1589         None => return Ok(None),
1590     };
1591
1592     let cargo_toml_url = to_proto::url_from_abs_path(&cargo_spec.cargo_toml);
1593     let res: lsp_types::GotoDefinitionResponse =
1594         Location::new(cargo_toml_url, Range::default()).into();
1595     Ok(Some(res))
1596 }
1597
1598 pub(crate) fn handle_move_item(
1599     snap: GlobalStateSnapshot,
1600     params: lsp_ext::MoveItemParams,
1601 ) -> Result<Vec<lsp_ext::SnippetTextEdit>> {
1602     let _p = profile::span("handle_move_item");
1603     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
1604     let range = from_proto::file_range(&snap, params.text_document, params.range)?;
1605
1606     let direction = match params.direction {
1607         lsp_ext::MoveItemDirection::Up => ide::Direction::Up,
1608         lsp_ext::MoveItemDirection::Down => ide::Direction::Down,
1609     };
1610
1611     match snap.analysis.move_item(range, direction)? {
1612         Some(text_edit) => {
1613             let line_index = snap.file_line_index(file_id)?;
1614             Ok(to_proto::snippet_text_edit_vec(&line_index, true, text_edit))
1615         }
1616         None => Ok(vec![]),
1617     }
1618 }
1619
1620 fn to_command_link(command: lsp_types::Command, tooltip: String) -> lsp_ext::CommandLink {
1621     lsp_ext::CommandLink { tooltip: Some(tooltip), command }
1622 }
1623
1624 fn show_impl_command_link(
1625     snap: &GlobalStateSnapshot,
1626     position: &FilePosition,
1627 ) -> Option<lsp_ext::CommandLinkGroup> {
1628     if snap.config.hover_actions().implementations && snap.config.client_commands().show_reference {
1629         if let Some(nav_data) = snap.analysis.goto_implementation(*position).unwrap_or(None) {
1630             let uri = to_proto::url(snap, position.file_id);
1631             let line_index = snap.file_line_index(position.file_id).ok()?;
1632             let position = to_proto::position(&line_index, position.offset);
1633             let locations: Vec<_> = nav_data
1634                 .info
1635                 .into_iter()
1636                 .filter_map(|nav| to_proto::location_from_nav(snap, nav).ok())
1637                 .collect();
1638             let title = to_proto::implementation_title(locations.len());
1639             let command = to_proto::command::show_references(title, &uri, position, locations);
1640
1641             return Some(lsp_ext::CommandLinkGroup {
1642                 commands: vec![to_command_link(command, "Go to implementations".into())],
1643                 ..Default::default()
1644             });
1645         }
1646     }
1647     None
1648 }
1649
1650 fn show_ref_command_link(
1651     snap: &GlobalStateSnapshot,
1652     position: &FilePosition,
1653 ) -> Option<lsp_ext::CommandLinkGroup> {
1654     if snap.config.hover_actions().references && snap.config.client_commands().show_reference {
1655         if let Some(ref_search_res) = snap.analysis.find_all_refs(*position, None).unwrap_or(None) {
1656             let uri = to_proto::url(snap, position.file_id);
1657             let line_index = snap.file_line_index(position.file_id).ok()?;
1658             let position = to_proto::position(&line_index, position.offset);
1659             let locations: Vec<_> = ref_search_res
1660                 .into_iter()
1661                 .flat_map(|res| res.references)
1662                 .flat_map(|(file_id, ranges)| {
1663                     ranges.into_iter().filter_map(move |(range, _)| {
1664                         to_proto::location(snap, FileRange { file_id, range }).ok()
1665                     })
1666                 })
1667                 .collect();
1668             let title = to_proto::reference_title(locations.len());
1669             let command = to_proto::command::show_references(title, &uri, position, locations);
1670
1671             return Some(lsp_ext::CommandLinkGroup {
1672                 commands: vec![to_command_link(command, "Go to references".into())],
1673                 ..Default::default()
1674             });
1675         }
1676     }
1677     None
1678 }
1679
1680 fn runnable_action_links(
1681     snap: &GlobalStateSnapshot,
1682     runnable: Runnable,
1683 ) -> Option<lsp_ext::CommandLinkGroup> {
1684     let hover_actions_config = snap.config.hover_actions();
1685     if !hover_actions_config.runnable() {
1686         return None;
1687     }
1688
1689     let cargo_spec = CargoTargetSpec::for_file(snap, runnable.nav.file_id).ok()?;
1690     if should_skip_target(&runnable, cargo_spec.as_ref()) {
1691         return None;
1692     }
1693
1694     let client_commands_config = snap.config.client_commands();
1695     if !(client_commands_config.run_single || client_commands_config.debug_single) {
1696         return None;
1697     }
1698
1699     let title = runnable.title();
1700     let r = to_proto::runnable(snap, runnable).ok()?;
1701
1702     let mut group = lsp_ext::CommandLinkGroup::default();
1703
1704     if hover_actions_config.run && client_commands_config.run_single {
1705         let run_command = to_proto::command::run_single(&r, &title);
1706         group.commands.push(to_command_link(run_command, r.label.clone()));
1707     }
1708
1709     if hover_actions_config.debug && client_commands_config.debug_single {
1710         let dbg_command = to_proto::command::debug_single(&r);
1711         group.commands.push(to_command_link(dbg_command, r.label));
1712     }
1713
1714     Some(group)
1715 }
1716
1717 fn goto_type_action_links(
1718     snap: &GlobalStateSnapshot,
1719     nav_targets: &[HoverGotoTypeData],
1720 ) -> Option<lsp_ext::CommandLinkGroup> {
1721     if !snap.config.hover_actions().goto_type_def
1722         || nav_targets.is_empty()
1723         || !snap.config.client_commands().goto_location
1724     {
1725         return None;
1726     }
1727
1728     Some(lsp_ext::CommandLinkGroup {
1729         title: Some("Go to ".into()),
1730         commands: nav_targets
1731             .iter()
1732             .filter_map(|it| {
1733                 to_proto::command::goto_location(snap, &it.nav)
1734                     .map(|cmd| to_command_link(cmd, it.mod_path.clone()))
1735             })
1736             .collect(),
1737     })
1738 }
1739
1740 fn prepare_hover_actions(
1741     snap: &GlobalStateSnapshot,
1742     actions: &[HoverAction],
1743 ) -> Vec<lsp_ext::CommandLinkGroup> {
1744     actions
1745         .iter()
1746         .filter_map(|it| match it {
1747             HoverAction::Implementation(position) => show_impl_command_link(snap, position),
1748             HoverAction::Reference(position) => show_ref_command_link(snap, position),
1749             HoverAction::Runnable(r) => runnable_action_links(snap, r.clone()),
1750             HoverAction::GoToType(targets) => goto_type_action_links(snap, targets),
1751         })
1752         .collect()
1753 }
1754
1755 fn should_skip_target(runnable: &Runnable, cargo_spec: Option<&CargoTargetSpec>) -> bool {
1756     match runnable.kind {
1757         RunnableKind::Bin => {
1758             // Do not suggest binary run on other target than binary
1759             match &cargo_spec {
1760                 Some(spec) => !matches!(
1761                     spec.target_kind,
1762                     TargetKind::Bin | TargetKind::Example | TargetKind::Test
1763                 ),
1764                 None => true,
1765             }
1766         }
1767         _ => false,
1768     }
1769 }
1770
1771 fn run_rustfmt(
1772     snap: &GlobalStateSnapshot,
1773     text_document: TextDocumentIdentifier,
1774     range: Option<lsp_types::Range>,
1775 ) -> Result<Option<Vec<lsp_types::TextEdit>>> {
1776     let file_id = from_proto::file_id(snap, &text_document.uri)?;
1777     let file = snap.analysis.file_text(file_id)?;
1778     let crate_ids = snap.analysis.crate_for(file_id)?;
1779
1780     let line_index = snap.file_line_index(file_id)?;
1781
1782     let mut command = match snap.config.rustfmt() {
1783         RustfmtConfig::Rustfmt { extra_args, enable_range_formatting } => {
1784             let mut cmd = process::Command::new(toolchain::rustfmt());
1785             cmd.args(extra_args);
1786             // try to chdir to the file so we can respect `rustfmt.toml`
1787             // FIXME: use `rustfmt --config-path` once
1788             // https://github.com/rust-lang/rustfmt/issues/4660 gets fixed
1789             match text_document.uri.to_file_path() {
1790                 Ok(mut path) => {
1791                     // pop off file name
1792                     if path.pop() && path.is_dir() {
1793                         cmd.current_dir(path);
1794                     }
1795                 }
1796                 Err(_) => {
1797                     tracing::error!(
1798                         "Unable to get file path for {}, rustfmt.toml might be ignored",
1799                         text_document.uri
1800                     );
1801                 }
1802             }
1803             if let Some(&crate_id) = crate_ids.first() {
1804                 // Assume all crates are in the same edition
1805                 let edition = snap.analysis.crate_edition(crate_id)?;
1806                 cmd.arg("--edition");
1807                 cmd.arg(edition.to_string());
1808             }
1809
1810             if let Some(range) = range {
1811                 if !enable_range_formatting {
1812                     return Err(LspError::new(
1813                         ErrorCode::InvalidRequest as i32,
1814                         String::from(
1815                             "rustfmt range formatting is unstable. \
1816                             Opt-in by using a nightly build of rustfmt and setting \
1817                             `rustfmt.rangeFormatting.enable` to true in your LSP configuration",
1818                         ),
1819                     )
1820                     .into());
1821                 }
1822
1823                 let frange = from_proto::file_range(snap, text_document, range)?;
1824                 let start_line = line_index.index.line_col(frange.range.start()).line;
1825                 let end_line = line_index.index.line_col(frange.range.end()).line;
1826
1827                 cmd.arg("--unstable-features");
1828                 cmd.arg("--file-lines");
1829                 cmd.arg(
1830                     json!([{
1831                         "file": "stdin",
1832                         "range": [start_line, end_line]
1833                     }])
1834                     .to_string(),
1835                 );
1836             }
1837
1838             cmd
1839         }
1840         RustfmtConfig::CustomCommand { command, args } => {
1841             let mut cmd = process::Command::new(command);
1842             cmd.args(args);
1843             cmd
1844         }
1845     };
1846
1847     let mut rustfmt = command
1848         .stdin(Stdio::piped())
1849         .stdout(Stdio::piped())
1850         .stderr(Stdio::piped())
1851         .spawn()
1852         .context(format!("Failed to spawn {:?}", command))?;
1853
1854     rustfmt.stdin.as_mut().unwrap().write_all(file.as_bytes())?;
1855
1856     let output = rustfmt.wait_with_output()?;
1857     let captured_stdout = String::from_utf8(output.stdout)?;
1858     let captured_stderr = String::from_utf8(output.stderr).unwrap_or_default();
1859
1860     if !output.status.success() {
1861         let rustfmt_not_installed =
1862             captured_stderr.contains("not installed") || captured_stderr.contains("not available");
1863
1864         return match output.status.code() {
1865             Some(1) if !rustfmt_not_installed => {
1866                 // While `rustfmt` doesn't have a specific exit code for parse errors this is the
1867                 // likely cause exiting with 1. Most Language Servers swallow parse errors on
1868                 // formatting because otherwise an error is surfaced to the user on top of the
1869                 // syntax error diagnostics they're already receiving. This is especially jarring
1870                 // if they have format on save enabled.
1871                 tracing::warn!(
1872                     ?command,
1873                     %captured_stderr,
1874                     "rustfmt exited with status 1"
1875                 );
1876                 Ok(None)
1877             }
1878             _ => {
1879                 // Something else happened - e.g. `rustfmt` is missing or caught a signal
1880                 Err(LspError::new(
1881                     -32900,
1882                     format!(
1883                         r#"rustfmt exited with:
1884                            Status: {}
1885                            stdout: {}
1886                            stderr: {}"#,
1887                         output.status, captured_stdout, captured_stderr,
1888                     ),
1889                 )
1890                 .into())
1891             }
1892         };
1893     }
1894
1895     let (new_text, new_line_endings) = LineEndings::normalize(captured_stdout);
1896
1897     if line_index.endings != new_line_endings {
1898         // If line endings are different, send the entire file.
1899         // Diffing would not work here, as the line endings might be the only
1900         // difference.
1901         Ok(Some(to_proto::text_edit_vec(
1902             &line_index,
1903             TextEdit::replace(TextRange::up_to(TextSize::of(&*file)), new_text),
1904         )))
1905     } else if *file == new_text {
1906         // The document is already formatted correctly -- no edits needed.
1907         Ok(None)
1908     } else {
1909         Ok(Some(to_proto::text_edit_vec(&line_index, diff(&file, &new_text))))
1910     }
1911 }