]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/handlers.rs
Switch to upstream protocol for resolving code action
[rust.git] / 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 ide::{
11     FileId, FilePosition, FileRange, HoverAction, HoverGotoTypeData, NavigationTarget, Query,
12     RangeInfo, Runnable, RunnableKind, SearchScope, TextEdit,
13 };
14 use itertools::Itertools;
15 use lsp_server::ErrorCode;
16 use lsp_types::{
17     CallHierarchyIncomingCall, CallHierarchyIncomingCallsParams, CallHierarchyItem,
18     CallHierarchyOutgoingCall, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams,
19     CodeActionKind, CodeLens, Command, CompletionItem, Diagnostic, DiagnosticTag,
20     DocumentFormattingParams, DocumentHighlight, DocumentSymbol, FoldingRange, FoldingRangeParams,
21     HoverContents, Location, Position, PrepareRenameResponse, Range, RenameParams,
22     SemanticTokensDeltaParams, SemanticTokensFullDeltaResult, SemanticTokensParams,
23     SemanticTokensRangeParams, SemanticTokensRangeResult, SemanticTokensResult, SymbolInformation,
24     SymbolTag, TextDocumentIdentifier, Url, WorkspaceEdit,
25 };
26 use project_model::TargetKind;
27 use serde::{Deserialize, Serialize};
28 use serde_json::to_value;
29 use stdx::{format_to, split_once};
30 use syntax::{algo, ast, AstNode, SyntaxKind, TextRange, TextSize};
31
32 use crate::{
33     cargo_target_spec::CargoTargetSpec,
34     config::RustfmtConfig,
35     from_json, from_proto,
36     global_state::{GlobalState, GlobalStateSnapshot},
37     lsp_ext::{self, InlayHint, InlayHintsParams},
38     to_proto, LspError, Result,
39 };
40
41 pub(crate) fn handle_analyzer_status(
42     snap: GlobalStateSnapshot,
43     params: lsp_ext::AnalyzerStatusParams,
44 ) -> Result<String> {
45     let _p = profile::span("handle_analyzer_status");
46
47     let mut buf = String::new();
48
49     let mut file_id = None;
50     if let Some(tdi) = params.text_document {
51         match from_proto::file_id(&snap, &tdi.uri) {
52             Ok(it) => file_id = Some(it),
53             Err(_) => format_to!(buf, "file {} not found in vfs", tdi.uri),
54         }
55     }
56
57     if snap.workspaces.is_empty() {
58         buf.push_str("no workspaces\n")
59     } else {
60         buf.push_str("workspaces:\n");
61         for w in snap.workspaces.iter() {
62             format_to!(buf, "{} packages loaded\n", w.n_packages());
63         }
64     }
65     buf.push_str("\nanalysis:\n");
66     buf.push_str(
67         &snap
68             .analysis
69             .status(file_id)
70             .unwrap_or_else(|_| "Analysis retrieval was cancelled".to_owned()),
71     );
72     format_to!(buf, "\n\nrequests:\n");
73     let requests = snap.latest_requests.read();
74     for (is_last, r) in requests.iter() {
75         let mark = if is_last { "*" } else { " " };
76         format_to!(buf, "{}{:4} {:<36}{}ms\n", mark, r.id, r.method, r.duration.as_millis());
77     }
78     Ok(buf)
79 }
80
81 pub(crate) fn handle_memory_usage(state: &mut GlobalState, _: ()) -> Result<String> {
82     let _p = profile::span("handle_memory_usage");
83     let mem = state.analysis_host.per_query_memory_usage();
84
85     let mut out = String::new();
86     for (name, bytes) in mem {
87         format_to!(out, "{:>8} {}\n", bytes, name);
88     }
89     Ok(out)
90 }
91
92 pub(crate) fn handle_syntax_tree(
93     snap: GlobalStateSnapshot,
94     params: lsp_ext::SyntaxTreeParams,
95 ) -> Result<String> {
96     let _p = profile::span("handle_syntax_tree");
97     let id = from_proto::file_id(&snap, &params.text_document.uri)?;
98     let line_index = snap.analysis.file_line_index(id)?;
99     let text_range = params.range.map(|r| from_proto::text_range(&line_index, r));
100     let res = snap.analysis.syntax_tree(id, text_range)?;
101     Ok(res)
102 }
103
104 pub(crate) fn handle_expand_macro(
105     snap: GlobalStateSnapshot,
106     params: lsp_ext::ExpandMacroParams,
107 ) -> Result<Option<lsp_ext::ExpandedMacro>> {
108     let _p = profile::span("handle_expand_macro");
109     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
110     let line_index = snap.analysis.file_line_index(file_id)?;
111     let offset = from_proto::offset(&line_index, params.position);
112
113     let res = snap.analysis.expand_macro(FilePosition { file_id, offset })?;
114     Ok(res.map(|it| lsp_ext::ExpandedMacro { name: it.name, expansion: it.expansion }))
115 }
116
117 pub(crate) fn handle_selection_range(
118     snap: GlobalStateSnapshot,
119     params: lsp_types::SelectionRangeParams,
120 ) -> Result<Option<Vec<lsp_types::SelectionRange>>> {
121     let _p = profile::span("handle_selection_range");
122     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
123     let line_index = snap.analysis.file_line_index(file_id)?;
124     let res: Result<Vec<lsp_types::SelectionRange>> = params
125         .positions
126         .into_iter()
127         .map(|position| {
128             let offset = from_proto::offset(&line_index, position);
129             let mut ranges = Vec::new();
130             {
131                 let mut range = TextRange::new(offset, offset);
132                 loop {
133                     ranges.push(range);
134                     let frange = FileRange { file_id, range };
135                     let next = snap.analysis.extend_selection(frange)?;
136                     if next == range {
137                         break;
138                     } else {
139                         range = next
140                     }
141                 }
142             }
143             let mut range = lsp_types::SelectionRange {
144                 range: to_proto::range(&line_index, *ranges.last().unwrap()),
145                 parent: None,
146             };
147             for &r in ranges.iter().rev().skip(1) {
148                 range = lsp_types::SelectionRange {
149                     range: to_proto::range(&line_index, r),
150                     parent: Some(Box::new(range)),
151                 }
152             }
153             Ok(range)
154         })
155         .collect();
156
157     Ok(Some(res?))
158 }
159
160 pub(crate) fn handle_matching_brace(
161     snap: GlobalStateSnapshot,
162     params: lsp_ext::MatchingBraceParams,
163 ) -> Result<Vec<Position>> {
164     let _p = profile::span("handle_matching_brace");
165     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
166     let line_index = snap.analysis.file_line_index(file_id)?;
167     let res = params
168         .positions
169         .into_iter()
170         .map(|position| {
171             let offset = from_proto::offset(&line_index, position);
172             let offset = match snap.analysis.matching_brace(FilePosition { file_id, offset }) {
173                 Ok(Some(matching_brace_offset)) => matching_brace_offset,
174                 Err(_) | Ok(None) => offset,
175             };
176             to_proto::position(&line_index, offset)
177         })
178         .collect();
179     Ok(res)
180 }
181
182 pub(crate) fn handle_join_lines(
183     snap: GlobalStateSnapshot,
184     params: lsp_ext::JoinLinesParams,
185 ) -> Result<Vec<lsp_types::TextEdit>> {
186     let _p = profile::span("handle_join_lines");
187     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
188     let line_index = snap.analysis.file_line_index(file_id)?;
189     let line_endings = snap.file_line_endings(file_id);
190     let mut res = TextEdit::default();
191     for range in params.ranges {
192         let range = from_proto::text_range(&line_index, range);
193         let edit = snap.analysis.join_lines(FileRange { file_id, range })?;
194         match res.union(edit) {
195             Ok(()) => (),
196             Err(_edit) => {
197                 // just ignore overlapping edits
198             }
199         }
200     }
201     let res = to_proto::text_edit_vec(&line_index, line_endings, res);
202     Ok(res)
203 }
204
205 pub(crate) fn handle_on_enter(
206     snap: GlobalStateSnapshot,
207     params: lsp_types::TextDocumentPositionParams,
208 ) -> Result<Option<Vec<lsp_ext::SnippetTextEdit>>> {
209     let _p = profile::span("handle_on_enter");
210     let position = from_proto::file_position(&snap, params)?;
211     let edit = match snap.analysis.on_enter(position)? {
212         None => return Ok(None),
213         Some(it) => it,
214     };
215     let line_index = snap.analysis.file_line_index(position.file_id)?;
216     let line_endings = snap.file_line_endings(position.file_id);
217     let edit = to_proto::snippet_text_edit_vec(&line_index, line_endings, true, edit);
218     Ok(Some(edit))
219 }
220
221 // Don't forget to add new trigger characters to `ServerCapabilities` in `caps.rs`.
222 pub(crate) fn handle_on_type_formatting(
223     snap: GlobalStateSnapshot,
224     params: lsp_types::DocumentOnTypeFormattingParams,
225 ) -> Result<Option<Vec<lsp_types::TextEdit>>> {
226     let _p = profile::span("handle_on_type_formatting");
227     let mut position = from_proto::file_position(&snap, params.text_document_position)?;
228     let line_index = snap.analysis.file_line_index(position.file_id)?;
229     let line_endings = snap.file_line_endings(position.file_id);
230
231     // in `ide`, the `on_type` invariant is that
232     // `text.char_at(position) == typed_char`.
233     position.offset -= TextSize::of('.');
234     let char_typed = params.ch.chars().next().unwrap_or('\0');
235     assert!({
236         let text = snap.analysis.file_text(position.file_id)?;
237         text[usize::from(position.offset)..].starts_with(char_typed)
238     });
239
240     // We have an assist that inserts ` ` after typing `->` in `fn foo() ->{`,
241     // but it requires precise cursor positioning to work, and one can't
242     // position the cursor with on_type formatting. So, let's just toggle this
243     // feature off here, hoping that we'll enable it one day, ðŸ˜¿.
244     if char_typed == '>' {
245         return Ok(None);
246     }
247
248     let edit = snap.analysis.on_char_typed(position, char_typed)?;
249     let mut edit = match edit {
250         Some(it) => it,
251         None => return Ok(None),
252     };
253
254     // This should be a single-file edit
255     let edit = edit.source_file_edits.pop().unwrap();
256
257     let change = to_proto::text_edit_vec(&line_index, line_endings, edit.edit);
258     Ok(Some(change))
259 }
260
261 pub(crate) fn handle_document_symbol(
262     snap: GlobalStateSnapshot,
263     params: lsp_types::DocumentSymbolParams,
264 ) -> Result<Option<lsp_types::DocumentSymbolResponse>> {
265     let _p = profile::span("handle_document_symbol");
266     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
267     let line_index = snap.analysis.file_line_index(file_id)?;
268
269     let mut parents: Vec<(DocumentSymbol, Option<usize>)> = Vec::new();
270
271     for symbol in snap.analysis.file_structure(file_id)? {
272         let mut tags = Vec::new();
273         if symbol.deprecated {
274             tags.push(SymbolTag::Deprecated)
275         };
276
277         #[allow(deprecated)]
278         let doc_symbol = DocumentSymbol {
279             name: symbol.label,
280             detail: symbol.detail,
281             kind: to_proto::symbol_kind(symbol.kind),
282             tags: Some(tags),
283             deprecated: Some(symbol.deprecated),
284             range: to_proto::range(&line_index, symbol.node_range),
285             selection_range: to_proto::range(&line_index, symbol.navigation_range),
286             children: None,
287         };
288         parents.push((doc_symbol, symbol.parent));
289     }
290
291     // Builds hierarchy from a flat list, in reverse order (so that indices
292     // makes sense)
293     let document_symbols = {
294         let mut acc = Vec::new();
295         while let Some((mut node, parent_idx)) = parents.pop() {
296             if let Some(children) = &mut node.children {
297                 children.reverse();
298             }
299             let parent = match parent_idx {
300                 None => &mut acc,
301                 Some(i) => parents[i].0.children.get_or_insert_with(Vec::new),
302             };
303             parent.push(node);
304         }
305         acc.reverse();
306         acc
307     };
308
309     let res = if snap.config.client_caps.hierarchical_symbols {
310         document_symbols.into()
311     } else {
312         let url = to_proto::url(&snap, file_id);
313         let mut symbol_information = Vec::<SymbolInformation>::new();
314         for symbol in document_symbols {
315             flatten_document_symbol(&symbol, None, &url, &mut symbol_information);
316         }
317         symbol_information.into()
318     };
319     return Ok(Some(res));
320
321     fn flatten_document_symbol(
322         symbol: &DocumentSymbol,
323         container_name: Option<String>,
324         url: &Url,
325         res: &mut Vec<SymbolInformation>,
326     ) {
327         let mut tags = Vec::new();
328
329         #[allow(deprecated)]
330         match symbol.deprecated {
331             Some(true) => tags.push(SymbolTag::Deprecated),
332             _ => {}
333         }
334
335         #[allow(deprecated)]
336         res.push(SymbolInformation {
337             name: symbol.name.clone(),
338             kind: symbol.kind,
339             tags: Some(tags),
340             deprecated: symbol.deprecated,
341             location: Location::new(url.clone(), symbol.range),
342             container_name,
343         });
344
345         for child in symbol.children.iter().flatten() {
346             flatten_document_symbol(child, Some(symbol.name.clone()), url, res);
347         }
348     }
349 }
350
351 pub(crate) fn handle_workspace_symbol(
352     snap: GlobalStateSnapshot,
353     params: lsp_types::WorkspaceSymbolParams,
354 ) -> Result<Option<Vec<SymbolInformation>>> {
355     let _p = profile::span("handle_workspace_symbol");
356     let all_symbols = params.query.contains('#');
357     let libs = params.query.contains('*');
358     let query = {
359         let query: String = params.query.chars().filter(|&c| c != '#' && c != '*').collect();
360         let mut q = Query::new(query);
361         if !all_symbols {
362             q.only_types();
363         }
364         if libs {
365             q.libs();
366         }
367         q.limit(128);
368         q
369     };
370     let mut res = exec_query(&snap, query)?;
371     if res.is_empty() && !all_symbols {
372         let mut query = Query::new(params.query);
373         query.limit(128);
374         res = exec_query(&snap, query)?;
375     }
376
377     return Ok(Some(res));
378
379     fn exec_query(snap: &GlobalStateSnapshot, query: Query) -> Result<Vec<SymbolInformation>> {
380         let mut res = Vec::new();
381         for nav in snap.analysis.symbol_search(query)? {
382             let container_name = nav.container_name.as_ref().map(|v| v.to_string());
383
384             #[allow(deprecated)]
385             let info = SymbolInformation {
386                 name: nav.name.to_string(),
387                 kind: to_proto::symbol_kind(nav.kind),
388                 tags: None,
389                 location: to_proto::location_from_nav(snap, nav)?,
390                 container_name,
391                 deprecated: None,
392             };
393             res.push(info);
394         }
395         Ok(res)
396     }
397 }
398
399 pub(crate) fn handle_goto_definition(
400     snap: GlobalStateSnapshot,
401     params: lsp_types::GotoDefinitionParams,
402 ) -> Result<Option<lsp_types::GotoDefinitionResponse>> {
403     let _p = profile::span("handle_goto_definition");
404     let position = from_proto::file_position(&snap, params.text_document_position_params)?;
405     let nav_info = match snap.analysis.goto_definition(position)? {
406         None => return Ok(None),
407         Some(it) => it,
408     };
409     let src = FileRange { file_id: position.file_id, range: nav_info.range };
410     let res = to_proto::goto_definition_response(&snap, Some(src), nav_info.info)?;
411     Ok(Some(res))
412 }
413
414 pub(crate) fn handle_goto_implementation(
415     snap: GlobalStateSnapshot,
416     params: lsp_types::request::GotoImplementationParams,
417 ) -> Result<Option<lsp_types::request::GotoImplementationResponse>> {
418     let _p = profile::span("handle_goto_implementation");
419     let position = from_proto::file_position(&snap, params.text_document_position_params)?;
420     let nav_info = match snap.analysis.goto_implementation(position)? {
421         None => return Ok(None),
422         Some(it) => it,
423     };
424     let src = FileRange { file_id: position.file_id, range: nav_info.range };
425     let res = to_proto::goto_definition_response(&snap, Some(src), nav_info.info)?;
426     Ok(Some(res))
427 }
428
429 pub(crate) fn handle_goto_type_definition(
430     snap: GlobalStateSnapshot,
431     params: lsp_types::request::GotoTypeDefinitionParams,
432 ) -> Result<Option<lsp_types::request::GotoTypeDefinitionResponse>> {
433     let _p = profile::span("handle_goto_type_definition");
434     let position = from_proto::file_position(&snap, params.text_document_position_params)?;
435     let nav_info = match snap.analysis.goto_type_definition(position)? {
436         None => return Ok(None),
437         Some(it) => it,
438     };
439     let src = FileRange { file_id: position.file_id, range: nav_info.range };
440     let res = to_proto::goto_definition_response(&snap, Some(src), nav_info.info)?;
441     Ok(Some(res))
442 }
443
444 pub(crate) fn handle_parent_module(
445     snap: GlobalStateSnapshot,
446     params: lsp_types::TextDocumentPositionParams,
447 ) -> Result<Option<lsp_types::GotoDefinitionResponse>> {
448     let _p = profile::span("handle_parent_module");
449     let position = from_proto::file_position(&snap, params)?;
450     let navs = snap.analysis.parent_module(position)?;
451     let res = to_proto::goto_definition_response(&snap, None, navs)?;
452     Ok(Some(res))
453 }
454
455 pub(crate) fn handle_runnables(
456     snap: GlobalStateSnapshot,
457     params: lsp_ext::RunnablesParams,
458 ) -> Result<Vec<lsp_ext::Runnable>> {
459     let _p = profile::span("handle_runnables");
460     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
461     let line_index = snap.analysis.file_line_index(file_id)?;
462     let offset = params.position.map(|it| from_proto::offset(&line_index, it));
463     let cargo_spec = CargoTargetSpec::for_file(&snap, file_id)?;
464
465     let expect_test = match offset {
466         Some(offset) => {
467             let source_file = snap.analysis.parse(file_id)?;
468             algo::find_node_at_offset::<ast::MacroCall>(source_file.syntax(), offset)
469                 .and_then(|it| it.path()?.segment()?.name_ref())
470                 .map_or(false, |it| it.text() == "expect" || it.text() == "expect_file")
471         }
472         None => false,
473     };
474
475     let mut res = Vec::new();
476     for runnable in snap.analysis.runnables(file_id)? {
477         if let Some(offset) = offset {
478             if !runnable.nav.full_range.contains_inclusive(offset) {
479                 continue;
480             }
481         }
482         if should_skip_target(&runnable, cargo_spec.as_ref()) {
483             continue;
484         }
485         let mut runnable = to_proto::runnable(&snap, file_id, runnable)?;
486         if expect_test {
487             runnable.label = format!("{} + expect", runnable.label);
488             runnable.args.expect_test = Some(true);
489         }
490         res.push(runnable);
491     }
492
493     // Add `cargo check` and `cargo test` for all targets of the whole package
494     let config = &snap.config.runnables;
495     match cargo_spec {
496         Some(spec) => {
497             for &cmd in ["check", "test"].iter() {
498                 res.push(lsp_ext::Runnable {
499                     label: format!("cargo {} -p {} --all-targets", cmd, spec.package),
500                     location: None,
501                     kind: lsp_ext::RunnableKind::Cargo,
502                     args: lsp_ext::CargoRunnable {
503                         workspace_root: Some(spec.workspace_root.clone().into()),
504                         override_cargo: config.override_cargo.clone(),
505                         cargo_args: vec![
506                             cmd.to_string(),
507                             "--package".to_string(),
508                             spec.package.clone(),
509                             "--all-targets".to_string(),
510                         ],
511                         cargo_extra_args: config.cargo_extra_args.clone(),
512                         executable_args: Vec::new(),
513                         expect_test: None,
514                     },
515                 })
516             }
517         }
518         None => {
519             res.push(lsp_ext::Runnable {
520                 label: "cargo check --workspace".to_string(),
521                 location: None,
522                 kind: lsp_ext::RunnableKind::Cargo,
523                 args: lsp_ext::CargoRunnable {
524                     workspace_root: None,
525                     override_cargo: config.override_cargo.clone(),
526                     cargo_args: vec!["check".to_string(), "--workspace".to_string()],
527                     cargo_extra_args: config.cargo_extra_args.clone(),
528                     executable_args: Vec::new(),
529                     expect_test: None,
530                 },
531             });
532         }
533     }
534     Ok(res)
535 }
536
537 pub(crate) fn handle_completion(
538     snap: GlobalStateSnapshot,
539     params: lsp_types::CompletionParams,
540 ) -> Result<Option<lsp_types::CompletionResponse>> {
541     let _p = profile::span("handle_completion");
542     let position = from_proto::file_position(&snap, params.text_document_position)?;
543     let completion_triggered_after_single_colon = {
544         let mut res = false;
545         if let Some(ctx) = params.context {
546             if ctx.trigger_character.unwrap_or_default() == ":" {
547                 let source_file = snap.analysis.parse(position.file_id)?;
548                 let syntax = source_file.syntax();
549                 let text = syntax.text();
550                 if let Some(next_char) = text.char_at(position.offset) {
551                     let diff = TextSize::of(next_char) + TextSize::of(':');
552                     let prev_char = position.offset - diff;
553                     if text.char_at(prev_char) != Some(':') {
554                         res = true;
555                     }
556                 }
557             }
558         }
559         res
560     };
561     if completion_triggered_after_single_colon {
562         return Ok(None);
563     }
564
565     let items = match snap.analysis.completions(&snap.config.completion, position)? {
566         None => return Ok(None),
567         Some(items) => items,
568     };
569     let line_index = snap.analysis.file_line_index(position.file_id)?;
570     let line_endings = snap.file_line_endings(position.file_id);
571     let items: Vec<CompletionItem> = items
572         .into_iter()
573         .flat_map(|item| to_proto::completion_item(&line_index, line_endings, item))
574         .collect();
575
576     Ok(Some(items.into()))
577 }
578
579 pub(crate) fn handle_folding_range(
580     snap: GlobalStateSnapshot,
581     params: FoldingRangeParams,
582 ) -> Result<Option<Vec<FoldingRange>>> {
583     let _p = profile::span("handle_folding_range");
584     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
585     let folds = snap.analysis.folding_ranges(file_id)?;
586     let text = snap.analysis.file_text(file_id)?;
587     let line_index = snap.analysis.file_line_index(file_id)?;
588     let line_folding_only = snap.config.client_caps.line_folding_only;
589     let res = folds
590         .into_iter()
591         .map(|it| to_proto::folding_range(&*text, &line_index, line_folding_only, it))
592         .collect();
593     Ok(Some(res))
594 }
595
596 pub(crate) fn handle_signature_help(
597     snap: GlobalStateSnapshot,
598     params: lsp_types::SignatureHelpParams,
599 ) -> Result<Option<lsp_types::SignatureHelp>> {
600     let _p = profile::span("handle_signature_help");
601     let position = from_proto::file_position(&snap, params.text_document_position_params)?;
602     let call_info = match snap.analysis.call_info(position)? {
603         Some(it) => it,
604         None => return Ok(None),
605     };
606     let concise = !snap.config.call_info_full;
607     let res = to_proto::signature_help(
608         call_info,
609         concise,
610         snap.config.client_caps.signature_help_label_offsets,
611     );
612     Ok(Some(res))
613 }
614
615 pub(crate) fn handle_hover(
616     snap: GlobalStateSnapshot,
617     params: lsp_types::HoverParams,
618 ) -> Result<Option<lsp_ext::Hover>> {
619     let _p = profile::span("handle_hover");
620     let position = from_proto::file_position(&snap, params.text_document_position_params)?;
621     let info = match snap.analysis.hover(
622         position,
623         snap.config.hover.links_in_hover,
624         snap.config.hover.markdown,
625     )? {
626         None => return Ok(None),
627         Some(info) => info,
628     };
629     let line_index = snap.analysis.file_line_index(position.file_id)?;
630     let range = to_proto::range(&line_index, info.range);
631     let hover = lsp_ext::Hover {
632         hover: lsp_types::Hover {
633             contents: HoverContents::Markup(to_proto::markup_content(info.info.markup)),
634             range: Some(range),
635         },
636         actions: prepare_hover_actions(&snap, position.file_id, &info.info.actions),
637     };
638
639     Ok(Some(hover))
640 }
641
642 pub(crate) fn handle_prepare_rename(
643     snap: GlobalStateSnapshot,
644     params: lsp_types::TextDocumentPositionParams,
645 ) -> Result<Option<PrepareRenameResponse>> {
646     let _p = profile::span("handle_prepare_rename");
647     let position = from_proto::file_position(&snap, params)?;
648
649     let change = snap.analysis.rename(position, "dummy")??;
650     let line_index = snap.analysis.file_line_index(position.file_id)?;
651     let range = to_proto::range(&line_index, change.range);
652     Ok(Some(PrepareRenameResponse::Range(range)))
653 }
654
655 pub(crate) fn handle_rename(
656     snap: GlobalStateSnapshot,
657     params: RenameParams,
658 ) -> Result<Option<WorkspaceEdit>> {
659     let _p = profile::span("handle_rename");
660     let position = from_proto::file_position(&snap, params.text_document_position)?;
661
662     if params.new_name.is_empty() {
663         return Err(LspError::new(
664             ErrorCode::InvalidParams as i32,
665             "New Name cannot be empty".into(),
666         )
667         .into());
668     }
669
670     let change = snap.analysis.rename(position, &*params.new_name)??;
671     let workspace_edit = to_proto::workspace_edit(&snap, change.info)?;
672     Ok(Some(workspace_edit))
673 }
674
675 pub(crate) fn handle_references(
676     snap: GlobalStateSnapshot,
677     params: lsp_types::ReferenceParams,
678 ) -> Result<Option<Vec<Location>>> {
679     let _p = profile::span("handle_references");
680     let position = from_proto::file_position(&snap, params.text_document_position)?;
681
682     let refs = match snap.analysis.find_all_refs(position, None)? {
683         None => return Ok(None),
684         Some(refs) => refs,
685     };
686
687     let locations = if params.context.include_declaration {
688         refs.into_iter()
689             .filter_map(|reference| to_proto::location(&snap, reference.file_range).ok())
690             .collect()
691     } else {
692         // Only iterate over the references if include_declaration was false
693         refs.references()
694             .iter()
695             .filter_map(|reference| to_proto::location(&snap, reference.file_range).ok())
696             .collect()
697     };
698
699     Ok(Some(locations))
700 }
701
702 pub(crate) fn handle_formatting(
703     snap: GlobalStateSnapshot,
704     params: DocumentFormattingParams,
705 ) -> Result<Option<Vec<lsp_types::TextEdit>>> {
706     let _p = profile::span("handle_formatting");
707     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
708     let file = snap.analysis.file_text(file_id)?;
709     let crate_ids = snap.analysis.crate_for(file_id)?;
710
711     let file_line_index = snap.analysis.file_line_index(file_id)?;
712     let end_position = to_proto::position(&file_line_index, TextSize::of(file.as_str()));
713
714     let mut rustfmt = match &snap.config.rustfmt {
715         RustfmtConfig::Rustfmt { extra_args } => {
716             let mut cmd = process::Command::new(toolchain::rustfmt());
717             cmd.args(extra_args);
718             if let Some(&crate_id) = crate_ids.first() {
719                 // Assume all crates are in the same edition
720                 let edition = snap.analysis.crate_edition(crate_id)?;
721                 cmd.arg("--edition");
722                 cmd.arg(edition.to_string());
723             }
724             cmd
725         }
726         RustfmtConfig::CustomCommand { command, args } => {
727             let mut cmd = process::Command::new(command);
728             cmd.args(args);
729             cmd
730         }
731     };
732
733     let mut rustfmt = rustfmt.stdin(Stdio::piped()).stdout(Stdio::piped()).spawn()?;
734
735     rustfmt.stdin.as_mut().unwrap().write_all(file.as_bytes())?;
736
737     let output = rustfmt.wait_with_output()?;
738     let captured_stdout = String::from_utf8(output.stdout)?;
739
740     if !output.status.success() {
741         match output.status.code() {
742             Some(1) => {
743                 // While `rustfmt` doesn't have a specific exit code for parse errors this is the
744                 // likely cause exiting with 1. Most Language Servers swallow parse errors on
745                 // formatting because otherwise an error is surfaced to the user on top of the
746                 // syntax error diagnostics they're already receiving. This is especially jarring
747                 // if they have format on save enabled.
748                 log::info!("rustfmt exited with status 1, assuming parse error and ignoring");
749                 return Ok(None);
750             }
751             _ => {
752                 // Something else happened - e.g. `rustfmt` is missing or caught a signal
753                 return Err(LspError::new(
754                     -32900,
755                     format!(
756                         r#"rustfmt exited with:
757                            Status: {}
758                            stdout: {}"#,
759                         output.status, captured_stdout,
760                     ),
761                 )
762                 .into());
763             }
764         }
765     }
766
767     if *file == captured_stdout {
768         // The document is already formatted correctly -- no edits needed.
769         Ok(None)
770     } else {
771         Ok(Some(vec![lsp_types::TextEdit {
772             range: Range::new(Position::new(0, 0), end_position),
773             new_text: captured_stdout,
774         }]))
775     }
776 }
777
778 fn handle_fixes(
779     snap: &GlobalStateSnapshot,
780     params: &lsp_types::CodeActionParams,
781     res: &mut Vec<lsp_ext::CodeAction>,
782 ) -> Result<()> {
783     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
784     let line_index = snap.analysis.file_line_index(file_id)?;
785     let range = from_proto::text_range(&line_index, params.range);
786
787     match &params.context.only {
788         Some(v) => {
789             if !v.iter().any(|it| {
790                 it == &lsp_types::CodeActionKind::EMPTY
791                     || it == &lsp_types::CodeActionKind::QUICKFIX
792             }) {
793                 return Ok(());
794             }
795         }
796         None => {}
797     };
798
799     let diagnostics = snap.analysis.diagnostics(&snap.config.diagnostics, file_id)?;
800
801     for fix in diagnostics
802         .into_iter()
803         .filter_map(|d| d.fix)
804         .filter(|fix| fix.fix_trigger_range.intersect(range).is_some())
805     {
806         let edit = to_proto::snippet_workspace_edit(&snap, fix.source_change)?;
807         let action = lsp_ext::CodeAction {
808             title: fix.label.to_string(),
809             group: None,
810             kind: Some(CodeActionKind::QUICKFIX),
811             edit: Some(edit),
812             is_preferred: Some(false),
813             data: None,
814         };
815         res.push(action);
816     }
817
818     for fix in snap.check_fixes.get(&file_id).into_iter().flatten() {
819         let fix_range = from_proto::text_range(&line_index, fix.range);
820         if fix_range.intersect(range).is_none() {
821             continue;
822         }
823         res.push(fix.action.clone());
824     }
825     Ok(())
826 }
827
828 pub(crate) fn handle_code_action(
829     mut snap: GlobalStateSnapshot,
830     params: lsp_types::CodeActionParams,
831 ) -> Result<Option<Vec<lsp_ext::CodeAction>>> {
832     let _p = profile::span("handle_code_action");
833     // We intentionally don't support command-based actions, as those either
834     // requires custom client-code anyway, or requires server-initiated edits.
835     // Server initiated edits break causality, so we avoid those as well.
836     if !snap.config.client_caps.code_action_literals {
837         return Ok(None);
838     }
839
840     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
841     let line_index = snap.analysis.file_line_index(file_id)?;
842     let range = from_proto::text_range(&line_index, params.range);
843     let frange = FileRange { file_id, range };
844
845     snap.config.assist.allowed = params
846         .clone()
847         .context
848         .only
849         .map(|it| it.into_iter().filter_map(from_proto::assist_kind).collect());
850
851     let mut res: Vec<lsp_ext::CodeAction> = Vec::new();
852
853     handle_fixes(&snap, &params, &mut res)?;
854
855     if snap.config.client_caps.code_action_resolve {
856         for (index, assist) in
857             snap.analysis.unresolved_assists(&snap.config.assist, frange)?.into_iter().enumerate()
858         {
859             res.push(to_proto::unresolved_code_action(&snap, params.clone(), assist, index)?);
860         }
861     } else {
862         for assist in snap.analysis.resolved_assists(&snap.config.assist, frange)?.into_iter() {
863             res.push(to_proto::resolved_code_action(&snap, assist)?);
864         }
865     }
866
867     Ok(Some(res))
868 }
869
870 pub(crate) fn handle_code_action_resolve(
871     mut snap: GlobalStateSnapshot,
872     mut code_action: lsp_ext::CodeAction,
873 ) -> Result<lsp_ext::CodeAction> {
874     let _p = profile::span("handle_code_action_resolve");
875     let params = match code_action.data.take() {
876         Some(it) => it,
877         None => Err("can't resolve code action without data")?,
878     };
879
880     let file_id = from_proto::file_id(&snap, &params.code_action_params.text_document.uri)?;
881     let line_index = snap.analysis.file_line_index(file_id)?;
882     let range = from_proto::text_range(&line_index, params.code_action_params.range);
883     let frange = FileRange { file_id, range };
884
885     snap.config.assist.allowed = params
886         .code_action_params
887         .context
888         .only
889         .map(|it| it.into_iter().filter_map(from_proto::assist_kind).collect());
890
891     let assists = snap.analysis.resolved_assists(&snap.config.assist, frange)?;
892     let (id, index) = split_once(&params.id, ':').unwrap();
893     let index = index.parse::<usize>().unwrap();
894     let assist = &assists[index];
895     assert!(assist.assist.id.0 == id);
896     let edit = to_proto::resolved_code_action(&snap, assist.clone())?.edit;
897     code_action.edit = edit;
898     Ok(code_action)
899 }
900
901 pub(crate) fn handle_code_lens(
902     snap: GlobalStateSnapshot,
903     params: lsp_types::CodeLensParams,
904 ) -> Result<Option<Vec<CodeLens>>> {
905     let _p = profile::span("handle_code_lens");
906     let mut lenses: Vec<CodeLens> = Default::default();
907
908     if snap.config.lens.none() {
909         // early return before any db query!
910         return Ok(Some(lenses));
911     }
912
913     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
914     let line_index = snap.analysis.file_line_index(file_id)?;
915     let cargo_spec = CargoTargetSpec::for_file(&snap, file_id)?;
916
917     if snap.config.lens.runnable() {
918         // Gather runnables
919         for runnable in snap.analysis.runnables(file_id)? {
920             if should_skip_target(&runnable, cargo_spec.as_ref()) {
921                 continue;
922             }
923
924             let action = runnable.action();
925             let range = to_proto::range(&line_index, runnable.nav.full_range);
926             let r = to_proto::runnable(&snap, file_id, runnable)?;
927             if snap.config.lens.run {
928                 let lens = CodeLens {
929                     range,
930                     command: Some(run_single_command(&r, action.run_title)),
931                     data: None,
932                 };
933                 lenses.push(lens);
934             }
935
936             if action.debugee && snap.config.lens.debug {
937                 let debug_lens =
938                     CodeLens { range, command: Some(debug_single_command(&r)), data: None };
939                 lenses.push(debug_lens);
940             }
941         }
942     }
943
944     if snap.config.lens.implementations {
945         // Handle impls
946         lenses.extend(
947             snap.analysis
948                 .file_structure(file_id)?
949                 .into_iter()
950                 .filter(|it| {
951                     matches!(
952                         it.kind,
953                         SyntaxKind::TRAIT
954                             | SyntaxKind::STRUCT
955                             | SyntaxKind::ENUM
956                             | SyntaxKind::UNION
957                     )
958                 })
959                 .map(|it| {
960                     let range = to_proto::range(&line_index, it.node_range);
961                     let pos = range.start;
962                     let lens_params = lsp_types::request::GotoImplementationParams {
963                         text_document_position_params: lsp_types::TextDocumentPositionParams::new(
964                             params.text_document.clone(),
965                             pos,
966                         ),
967                         work_done_progress_params: Default::default(),
968                         partial_result_params: Default::default(),
969                     };
970                     CodeLens {
971                         range,
972                         command: None,
973                         data: Some(to_value(CodeLensResolveData::Impls(lens_params)).unwrap()),
974                     }
975                 }),
976         );
977     }
978
979     if snap.config.lens.references() {
980         lenses.extend(snap.analysis.find_all_methods(file_id)?.into_iter().map(|it| {
981             let range = to_proto::range(&line_index, it.range);
982             let position = to_proto::position(&line_index, it.range.start());
983             let lens_params =
984                 lsp_types::TextDocumentPositionParams::new(params.text_document.clone(), position);
985
986             CodeLens {
987                 range,
988                 command: None,
989                 data: Some(to_value(CodeLensResolveData::References(lens_params)).unwrap()),
990             }
991         }));
992     }
993
994     Ok(Some(lenses))
995 }
996
997 #[derive(Debug, Serialize, Deserialize)]
998 #[serde(rename_all = "camelCase")]
999 enum CodeLensResolveData {
1000     Impls(lsp_types::request::GotoImplementationParams),
1001     References(lsp_types::TextDocumentPositionParams),
1002 }
1003
1004 pub(crate) fn handle_code_lens_resolve(
1005     snap: GlobalStateSnapshot,
1006     code_lens: CodeLens,
1007 ) -> Result<CodeLens> {
1008     let _p = profile::span("handle_code_lens_resolve");
1009     let data = code_lens.data.unwrap();
1010     let resolve = from_json::<Option<CodeLensResolveData>>("CodeLensResolveData", data)?;
1011     match resolve {
1012         Some(CodeLensResolveData::Impls(lens_params)) => {
1013             let locations: Vec<Location> =
1014                 match handle_goto_implementation(snap, lens_params.clone())? {
1015                     Some(lsp_types::GotoDefinitionResponse::Scalar(loc)) => vec![loc],
1016                     Some(lsp_types::GotoDefinitionResponse::Array(locs)) => locs,
1017                     Some(lsp_types::GotoDefinitionResponse::Link(links)) => links
1018                         .into_iter()
1019                         .map(|link| Location::new(link.target_uri, link.target_selection_range))
1020                         .collect(),
1021                     _ => vec![],
1022                 };
1023
1024             let title = implementation_title(locations.len());
1025             let cmd = show_references_command(
1026                 title,
1027                 &lens_params.text_document_position_params.text_document.uri,
1028                 code_lens.range.start,
1029                 locations,
1030             );
1031             Ok(CodeLens { range: code_lens.range, command: Some(cmd), data: None })
1032         }
1033         Some(CodeLensResolveData::References(doc_position)) => {
1034             let position = from_proto::file_position(&snap, doc_position.clone())?;
1035             let locations = snap
1036                 .analysis
1037                 .find_all_refs(position, None)
1038                 .unwrap_or(None)
1039                 .map(|r| {
1040                     r.references()
1041                         .iter()
1042                         .filter_map(|it| to_proto::location(&snap, it.file_range).ok())
1043                         .collect_vec()
1044                 })
1045                 .unwrap_or_default();
1046
1047             let title = reference_title(locations.len());
1048             let cmd = if locations.is_empty() {
1049                 Command { title, command: "".into(), arguments: None }
1050             } else {
1051                 show_references_command(
1052                     title,
1053                     &doc_position.text_document.uri,
1054                     code_lens.range.start,
1055                     locations,
1056                 )
1057             };
1058
1059             Ok(CodeLens { range: code_lens.range, command: Some(cmd), data: None })
1060         }
1061         None => Ok(CodeLens {
1062             range: code_lens.range,
1063             command: Some(Command { title: "Error".into(), ..Default::default() }),
1064             data: None,
1065         }),
1066     }
1067 }
1068
1069 pub(crate) fn handle_document_highlight(
1070     snap: GlobalStateSnapshot,
1071     params: lsp_types::DocumentHighlightParams,
1072 ) -> Result<Option<Vec<DocumentHighlight>>> {
1073     let _p = profile::span("handle_document_highlight");
1074     let position = from_proto::file_position(&snap, params.text_document_position_params)?;
1075     let line_index = snap.analysis.file_line_index(position.file_id)?;
1076
1077     let refs = match snap
1078         .analysis
1079         .find_all_refs(position, Some(SearchScope::single_file(position.file_id)))?
1080     {
1081         None => return Ok(None),
1082         Some(refs) => refs,
1083     };
1084
1085     let res = refs
1086         .into_iter()
1087         .filter(|reference| reference.file_range.file_id == position.file_id)
1088         .map(|reference| DocumentHighlight {
1089             range: to_proto::range(&line_index, reference.file_range.range),
1090             kind: reference.access.map(to_proto::document_highlight_kind),
1091         })
1092         .collect();
1093     Ok(Some(res))
1094 }
1095
1096 pub(crate) fn handle_ssr(
1097     snap: GlobalStateSnapshot,
1098     params: lsp_ext::SsrParams,
1099 ) -> Result<lsp_types::WorkspaceEdit> {
1100     let _p = profile::span("handle_ssr");
1101     let selections = params
1102         .selections
1103         .iter()
1104         .map(|range| from_proto::file_range(&snap, params.position.text_document.clone(), *range))
1105         .collect::<Result<Vec<_>, _>>()?;
1106     let position = from_proto::file_position(&snap, params.position)?;
1107     let source_change = snap.analysis.structural_search_replace(
1108         &params.query,
1109         params.parse_only,
1110         position,
1111         selections,
1112     )??;
1113     to_proto::workspace_edit(&snap, source_change)
1114 }
1115
1116 pub(crate) fn publish_diagnostics(
1117     snap: &GlobalStateSnapshot,
1118     file_id: FileId,
1119 ) -> Result<Vec<Diagnostic>> {
1120     let _p = profile::span("publish_diagnostics");
1121     let line_index = snap.analysis.file_line_index(file_id)?;
1122
1123     let diagnostics: Vec<Diagnostic> = snap
1124         .analysis
1125         .diagnostics(&snap.config.diagnostics, file_id)?
1126         .into_iter()
1127         .map(|d| Diagnostic {
1128             range: to_proto::range(&line_index, d.range),
1129             severity: Some(to_proto::diagnostic_severity(d.severity)),
1130             code: None,
1131             code_description: None,
1132             source: Some("rust-analyzer".to_string()),
1133             message: d.message,
1134             related_information: None,
1135             tags: if d.unused { Some(vec![DiagnosticTag::Unnecessary]) } else { None },
1136             data: None,
1137         })
1138         .collect();
1139     Ok(diagnostics)
1140 }
1141
1142 pub(crate) fn handle_inlay_hints(
1143     snap: GlobalStateSnapshot,
1144     params: InlayHintsParams,
1145 ) -> Result<Vec<InlayHint>> {
1146     let _p = profile::span("handle_inlay_hints");
1147     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
1148     let line_index = snap.analysis.file_line_index(file_id)?;
1149     Ok(snap
1150         .analysis
1151         .inlay_hints(file_id, &snap.config.inlay_hints)?
1152         .into_iter()
1153         .map(|it| to_proto::inlay_hint(&line_index, it))
1154         .collect())
1155 }
1156
1157 pub(crate) fn handle_call_hierarchy_prepare(
1158     snap: GlobalStateSnapshot,
1159     params: CallHierarchyPrepareParams,
1160 ) -> Result<Option<Vec<CallHierarchyItem>>> {
1161     let _p = profile::span("handle_call_hierarchy_prepare");
1162     let position = from_proto::file_position(&snap, params.text_document_position_params)?;
1163
1164     let nav_info = match snap.analysis.call_hierarchy(position)? {
1165         None => return Ok(None),
1166         Some(it) => it,
1167     };
1168
1169     let RangeInfo { range: _, info: navs } = nav_info;
1170     let res = navs
1171         .into_iter()
1172         .filter(|it| it.kind == SyntaxKind::FN)
1173         .map(|it| to_proto::call_hierarchy_item(&snap, it))
1174         .collect::<Result<Vec<_>>>()?;
1175
1176     Ok(Some(res))
1177 }
1178
1179 pub(crate) fn handle_call_hierarchy_incoming(
1180     snap: GlobalStateSnapshot,
1181     params: CallHierarchyIncomingCallsParams,
1182 ) -> Result<Option<Vec<CallHierarchyIncomingCall>>> {
1183     let _p = profile::span("handle_call_hierarchy_incoming");
1184     let item = params.item;
1185
1186     let doc = TextDocumentIdentifier::new(item.uri);
1187     let frange = from_proto::file_range(&snap, doc, item.selection_range)?;
1188     let fpos = FilePosition { file_id: frange.file_id, offset: frange.range.start() };
1189
1190     let call_items = match snap.analysis.incoming_calls(fpos)? {
1191         None => return Ok(None),
1192         Some(it) => it,
1193     };
1194
1195     let mut res = vec![];
1196
1197     for call_item in call_items.into_iter() {
1198         let file_id = call_item.target.file_id;
1199         let line_index = snap.analysis.file_line_index(file_id)?;
1200         let item = to_proto::call_hierarchy_item(&snap, call_item.target)?;
1201         res.push(CallHierarchyIncomingCall {
1202             from: item,
1203             from_ranges: call_item
1204                 .ranges
1205                 .into_iter()
1206                 .map(|it| to_proto::range(&line_index, it))
1207                 .collect(),
1208         });
1209     }
1210
1211     Ok(Some(res))
1212 }
1213
1214 pub(crate) fn handle_call_hierarchy_outgoing(
1215     snap: GlobalStateSnapshot,
1216     params: CallHierarchyOutgoingCallsParams,
1217 ) -> Result<Option<Vec<CallHierarchyOutgoingCall>>> {
1218     let _p = profile::span("handle_call_hierarchy_outgoing");
1219     let item = params.item;
1220
1221     let doc = TextDocumentIdentifier::new(item.uri);
1222     let frange = from_proto::file_range(&snap, doc, item.selection_range)?;
1223     let fpos = FilePosition { file_id: frange.file_id, offset: frange.range.start() };
1224
1225     let call_items = match snap.analysis.outgoing_calls(fpos)? {
1226         None => return Ok(None),
1227         Some(it) => it,
1228     };
1229
1230     let mut res = vec![];
1231
1232     for call_item in call_items.into_iter() {
1233         let file_id = call_item.target.file_id;
1234         let line_index = snap.analysis.file_line_index(file_id)?;
1235         let item = to_proto::call_hierarchy_item(&snap, call_item.target)?;
1236         res.push(CallHierarchyOutgoingCall {
1237             to: item,
1238             from_ranges: call_item
1239                 .ranges
1240                 .into_iter()
1241                 .map(|it| to_proto::range(&line_index, it))
1242                 .collect(),
1243         });
1244     }
1245
1246     Ok(Some(res))
1247 }
1248
1249 pub(crate) fn handle_semantic_tokens_full(
1250     snap: GlobalStateSnapshot,
1251     params: SemanticTokensParams,
1252 ) -> Result<Option<SemanticTokensResult>> {
1253     let _p = profile::span("handle_semantic_tokens_full");
1254
1255     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
1256     let text = snap.analysis.file_text(file_id)?;
1257     let line_index = snap.analysis.file_line_index(file_id)?;
1258
1259     let highlights = snap.analysis.highlight(file_id)?;
1260     let semantic_tokens = to_proto::semantic_tokens(&text, &line_index, highlights);
1261
1262     // Unconditionally cache the tokens
1263     snap.semantic_tokens_cache.lock().insert(params.text_document.uri, semantic_tokens.clone());
1264
1265     Ok(Some(semantic_tokens.into()))
1266 }
1267
1268 pub(crate) fn handle_semantic_tokens_full_delta(
1269     snap: GlobalStateSnapshot,
1270     params: SemanticTokensDeltaParams,
1271 ) -> Result<Option<SemanticTokensFullDeltaResult>> {
1272     let _p = profile::span("handle_semantic_tokens_full_delta");
1273
1274     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
1275     let text = snap.analysis.file_text(file_id)?;
1276     let line_index = snap.analysis.file_line_index(file_id)?;
1277
1278     let highlights = snap.analysis.highlight(file_id)?;
1279
1280     let semantic_tokens = to_proto::semantic_tokens(&text, &line_index, highlights);
1281
1282     let mut cache = snap.semantic_tokens_cache.lock();
1283     let cached_tokens = cache.entry(params.text_document.uri).or_default();
1284
1285     if let Some(prev_id) = &cached_tokens.result_id {
1286         if *prev_id == params.previous_result_id {
1287             let delta = to_proto::semantic_token_delta(&cached_tokens, &semantic_tokens);
1288             *cached_tokens = semantic_tokens;
1289             return Ok(Some(delta.into()));
1290         }
1291     }
1292
1293     *cached_tokens = semantic_tokens.clone();
1294
1295     Ok(Some(semantic_tokens.into()))
1296 }
1297
1298 pub(crate) fn handle_semantic_tokens_range(
1299     snap: GlobalStateSnapshot,
1300     params: SemanticTokensRangeParams,
1301 ) -> Result<Option<SemanticTokensRangeResult>> {
1302     let _p = profile::span("handle_semantic_tokens_range");
1303
1304     let frange = from_proto::file_range(&snap, params.text_document, params.range)?;
1305     let text = snap.analysis.file_text(frange.file_id)?;
1306     let line_index = snap.analysis.file_line_index(frange.file_id)?;
1307
1308     let highlights = snap.analysis.highlight_range(frange)?;
1309     let semantic_tokens = to_proto::semantic_tokens(&text, &line_index, highlights);
1310     Ok(Some(semantic_tokens.into()))
1311 }
1312
1313 pub(crate) fn handle_open_docs(
1314     snap: GlobalStateSnapshot,
1315     params: lsp_types::TextDocumentPositionParams,
1316 ) -> Result<Option<lsp_types::Url>> {
1317     let _p = profile::span("handle_open_docs");
1318     let position = from_proto::file_position(&snap, params)?;
1319
1320     let remote = snap.analysis.external_docs(position)?;
1321
1322     Ok(remote.and_then(|remote| Url::parse(&remote).ok()))
1323 }
1324
1325 fn implementation_title(count: usize) -> String {
1326     if count == 1 {
1327         "1 implementation".into()
1328     } else {
1329         format!("{} implementations", count)
1330     }
1331 }
1332
1333 fn reference_title(count: usize) -> String {
1334     if count == 1 {
1335         "1 reference".into()
1336     } else {
1337         format!("{} references", count)
1338     }
1339 }
1340
1341 fn show_references_command(
1342     title: String,
1343     uri: &lsp_types::Url,
1344     position: lsp_types::Position,
1345     locations: Vec<lsp_types::Location>,
1346 ) -> Command {
1347     // We cannot use the 'editor.action.showReferences' command directly
1348     // because that command requires vscode types which we convert in the handler
1349     // on the client side.
1350
1351     Command {
1352         title,
1353         command: "rust-analyzer.showReferences".into(),
1354         arguments: Some(vec![
1355             to_value(uri).unwrap(),
1356             to_value(position).unwrap(),
1357             to_value(locations).unwrap(),
1358         ]),
1359     }
1360 }
1361
1362 fn run_single_command(runnable: &lsp_ext::Runnable, title: &str) -> Command {
1363     Command {
1364         title: title.to_string(),
1365         command: "rust-analyzer.runSingle".into(),
1366         arguments: Some(vec![to_value(runnable).unwrap()]),
1367     }
1368 }
1369
1370 fn debug_single_command(runnable: &lsp_ext::Runnable) -> Command {
1371     Command {
1372         title: "Debug".into(),
1373         command: "rust-analyzer.debugSingle".into(),
1374         arguments: Some(vec![to_value(runnable).unwrap()]),
1375     }
1376 }
1377
1378 fn goto_location_command(snap: &GlobalStateSnapshot, nav: &NavigationTarget) -> Option<Command> {
1379     let value = if snap.config.client_caps.location_link {
1380         let link = to_proto::location_link(snap, None, nav.clone()).ok()?;
1381         to_value(link).ok()?
1382     } else {
1383         let range = FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() };
1384         let location = to_proto::location(snap, range).ok()?;
1385         to_value(location).ok()?
1386     };
1387
1388     Some(Command {
1389         title: nav.name.to_string(),
1390         command: "rust-analyzer.gotoLocation".into(),
1391         arguments: Some(vec![value]),
1392     })
1393 }
1394
1395 fn to_command_link(command: Command, tooltip: String) -> lsp_ext::CommandLink {
1396     lsp_ext::CommandLink { tooltip: Some(tooltip), command }
1397 }
1398
1399 fn show_impl_command_link(
1400     snap: &GlobalStateSnapshot,
1401     position: &FilePosition,
1402 ) -> Option<lsp_ext::CommandLinkGroup> {
1403     if snap.config.hover.implementations {
1404         if let Some(nav_data) = snap.analysis.goto_implementation(*position).unwrap_or(None) {
1405             let uri = to_proto::url(snap, position.file_id);
1406             let line_index = snap.analysis.file_line_index(position.file_id).ok()?;
1407             let position = to_proto::position(&line_index, position.offset);
1408             let locations: Vec<_> = nav_data
1409                 .info
1410                 .into_iter()
1411                 .filter_map(|nav| to_proto::location_from_nav(snap, nav).ok())
1412                 .collect();
1413             let title = implementation_title(locations.len());
1414             let command = show_references_command(title, &uri, position, locations);
1415
1416             return Some(lsp_ext::CommandLinkGroup {
1417                 commands: vec![to_command_link(command, "Go to implementations".into())],
1418                 ..Default::default()
1419             });
1420         }
1421     }
1422     None
1423 }
1424
1425 fn runnable_action_links(
1426     snap: &GlobalStateSnapshot,
1427     file_id: FileId,
1428     runnable: Runnable,
1429 ) -> Option<lsp_ext::CommandLinkGroup> {
1430     let cargo_spec = CargoTargetSpec::for_file(&snap, file_id).ok()?;
1431     if !snap.config.hover.runnable() || should_skip_target(&runnable, cargo_spec.as_ref()) {
1432         return None;
1433     }
1434
1435     let action: &'static _ = runnable.action();
1436     to_proto::runnable(snap, file_id, runnable).ok().map(|r| {
1437         let mut group = lsp_ext::CommandLinkGroup::default();
1438
1439         if snap.config.hover.run {
1440             let run_command = run_single_command(&r, action.run_title);
1441             group.commands.push(to_command_link(run_command, r.label.clone()));
1442         }
1443
1444         if snap.config.hover.debug {
1445             let dbg_command = debug_single_command(&r);
1446             group.commands.push(to_command_link(dbg_command, r.label));
1447         }
1448
1449         group
1450     })
1451 }
1452
1453 fn goto_type_action_links(
1454     snap: &GlobalStateSnapshot,
1455     nav_targets: &[HoverGotoTypeData],
1456 ) -> Option<lsp_ext::CommandLinkGroup> {
1457     if !snap.config.hover.goto_type_def || nav_targets.is_empty() {
1458         return None;
1459     }
1460
1461     Some(lsp_ext::CommandLinkGroup {
1462         title: Some("Go to ".into()),
1463         commands: nav_targets
1464             .iter()
1465             .filter_map(|it| {
1466                 goto_location_command(snap, &it.nav)
1467                     .map(|cmd| to_command_link(cmd, it.mod_path.clone()))
1468             })
1469             .collect(),
1470     })
1471 }
1472
1473 fn prepare_hover_actions(
1474     snap: &GlobalStateSnapshot,
1475     file_id: FileId,
1476     actions: &[HoverAction],
1477 ) -> Vec<lsp_ext::CommandLinkGroup> {
1478     if snap.config.hover.none() || !snap.config.client_caps.hover_actions {
1479         return Vec::new();
1480     }
1481
1482     actions
1483         .iter()
1484         .filter_map(|it| match it {
1485             HoverAction::Implementaion(position) => show_impl_command_link(snap, position),
1486             HoverAction::Runnable(r) => runnable_action_links(snap, file_id, r.clone()),
1487             HoverAction::GoToType(targets) => goto_type_action_links(snap, targets),
1488         })
1489         .collect()
1490 }
1491
1492 fn should_skip_target(runnable: &Runnable, cargo_spec: Option<&CargoTargetSpec>) -> bool {
1493     match runnable.kind {
1494         RunnableKind::Bin => {
1495             // Do not suggest binary run on other target than binary
1496             match &cargo_spec {
1497                 Some(spec) => !matches!(
1498                     spec.target_kind,
1499                     TargetKind::Bin | TargetKind::Example | TargetKind::Test
1500                 ),
1501                 None => true,
1502             }
1503         }
1504         _ => false,
1505     }
1506 }