]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/handlers.rs
2680e5f08bce63d30067695b13ccff6f5c53449d
[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             id: None,
810             group: None,
811             kind: Some(CodeActionKind::QUICKFIX),
812             edit: Some(edit),
813             is_preferred: Some(false),
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.resolve_code_action {
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, 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_resolve_code_action(
871     mut snap: GlobalStateSnapshot,
872     params: lsp_ext::ResolveCodeActionParams,
873 ) -> Result<Option<lsp_ext::SnippetWorkspaceEdit>> {
874     let _p = profile::span("handle_resolve_code_action");
875     let file_id = from_proto::file_id(&snap, &params.code_action_params.text_document.uri)?;
876     let line_index = snap.analysis.file_line_index(file_id)?;
877     let range = from_proto::text_range(&line_index, params.code_action_params.range);
878     let frange = FileRange { file_id, range };
879
880     snap.config.assist.allowed = params
881         .code_action_params
882         .context
883         .only
884         .map(|it| it.into_iter().filter_map(from_proto::assist_kind).collect());
885
886     let assists = snap.analysis.resolved_assists(&snap.config.assist, frange)?;
887     let (id, index) = split_once(&params.id, ':').unwrap();
888     let index = index.parse::<usize>().unwrap();
889     let assist = &assists[index];
890     assert!(assist.assist.id.0 == id);
891     Ok(to_proto::resolved_code_action(&snap, assist.clone())?.edit)
892 }
893
894 pub(crate) fn handle_code_lens(
895     snap: GlobalStateSnapshot,
896     params: lsp_types::CodeLensParams,
897 ) -> Result<Option<Vec<CodeLens>>> {
898     let _p = profile::span("handle_code_lens");
899     let mut lenses: Vec<CodeLens> = Default::default();
900
901     if snap.config.lens.none() {
902         // early return before any db query!
903         return Ok(Some(lenses));
904     }
905
906     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
907     let line_index = snap.analysis.file_line_index(file_id)?;
908     let cargo_spec = CargoTargetSpec::for_file(&snap, file_id)?;
909
910     if snap.config.lens.runnable() {
911         // Gather runnables
912         for runnable in snap.analysis.runnables(file_id)? {
913             if should_skip_target(&runnable, cargo_spec.as_ref()) {
914                 continue;
915             }
916
917             let action = runnable.action();
918             let range = to_proto::range(&line_index, runnable.nav.full_range);
919             let r = to_proto::runnable(&snap, file_id, runnable)?;
920             if snap.config.lens.run {
921                 let lens = CodeLens {
922                     range,
923                     command: Some(run_single_command(&r, action.run_title)),
924                     data: None,
925                 };
926                 lenses.push(lens);
927             }
928
929             if action.debugee && snap.config.lens.debug {
930                 let debug_lens =
931                     CodeLens { range, command: Some(debug_single_command(&r)), data: None };
932                 lenses.push(debug_lens);
933             }
934         }
935     }
936
937     if snap.config.lens.implementations {
938         // Handle impls
939         lenses.extend(
940             snap.analysis
941                 .file_structure(file_id)?
942                 .into_iter()
943                 .filter(|it| {
944                     matches!(
945                         it.kind,
946                         SyntaxKind::TRAIT
947                             | SyntaxKind::STRUCT
948                             | SyntaxKind::ENUM
949                             | SyntaxKind::UNION
950                     )
951                 })
952                 .map(|it| {
953                     let range = to_proto::range(&line_index, it.node_range);
954                     let pos = range.start;
955                     let lens_params = lsp_types::request::GotoImplementationParams {
956                         text_document_position_params: lsp_types::TextDocumentPositionParams::new(
957                             params.text_document.clone(),
958                             pos,
959                         ),
960                         work_done_progress_params: Default::default(),
961                         partial_result_params: Default::default(),
962                     };
963                     CodeLens {
964                         range,
965                         command: None,
966                         data: Some(to_value(CodeLensResolveData::Impls(lens_params)).unwrap()),
967                     }
968                 }),
969         );
970     }
971
972     if snap.config.lens.references() {
973         lenses.extend(snap.analysis.find_all_methods(file_id)?.into_iter().map(|it| {
974             let range = to_proto::range(&line_index, it.range);
975             let position = to_proto::position(&line_index, it.range.start());
976             let lens_params =
977                 lsp_types::TextDocumentPositionParams::new(params.text_document.clone(), position);
978
979             CodeLens {
980                 range,
981                 command: None,
982                 data: Some(to_value(CodeLensResolveData::References(lens_params)).unwrap()),
983             }
984         }));
985     }
986
987     Ok(Some(lenses))
988 }
989
990 #[derive(Debug, Serialize, Deserialize)]
991 #[serde(rename_all = "camelCase")]
992 enum CodeLensResolveData {
993     Impls(lsp_types::request::GotoImplementationParams),
994     References(lsp_types::TextDocumentPositionParams),
995 }
996
997 pub(crate) fn handle_code_lens_resolve(
998     snap: GlobalStateSnapshot,
999     code_lens: CodeLens,
1000 ) -> Result<CodeLens> {
1001     let _p = profile::span("handle_code_lens_resolve");
1002     let data = code_lens.data.unwrap();
1003     let resolve = from_json::<Option<CodeLensResolveData>>("CodeLensResolveData", data)?;
1004     match resolve {
1005         Some(CodeLensResolveData::Impls(lens_params)) => {
1006             let locations: Vec<Location> =
1007                 match handle_goto_implementation(snap, lens_params.clone())? {
1008                     Some(lsp_types::GotoDefinitionResponse::Scalar(loc)) => vec![loc],
1009                     Some(lsp_types::GotoDefinitionResponse::Array(locs)) => locs,
1010                     Some(lsp_types::GotoDefinitionResponse::Link(links)) => links
1011                         .into_iter()
1012                         .map(|link| Location::new(link.target_uri, link.target_selection_range))
1013                         .collect(),
1014                     _ => vec![],
1015                 };
1016
1017             let title = implementation_title(locations.len());
1018             let cmd = show_references_command(
1019                 title,
1020                 &lens_params.text_document_position_params.text_document.uri,
1021                 code_lens.range.start,
1022                 locations,
1023             );
1024             Ok(CodeLens { range: code_lens.range, command: Some(cmd), data: None })
1025         }
1026         Some(CodeLensResolveData::References(doc_position)) => {
1027             let position = from_proto::file_position(&snap, doc_position.clone())?;
1028             let locations = snap
1029                 .analysis
1030                 .find_all_refs(position, None)
1031                 .unwrap_or(None)
1032                 .map(|r| {
1033                     r.references()
1034                         .iter()
1035                         .filter_map(|it| to_proto::location(&snap, it.file_range).ok())
1036                         .collect_vec()
1037                 })
1038                 .unwrap_or_default();
1039
1040             let title = reference_title(locations.len());
1041             let cmd = if locations.is_empty() {
1042                 Command { title, command: "".into(), arguments: None }
1043             } else {
1044                 show_references_command(
1045                     title,
1046                     &doc_position.text_document.uri,
1047                     code_lens.range.start,
1048                     locations,
1049                 )
1050             };
1051
1052             Ok(CodeLens { range: code_lens.range, command: Some(cmd), data: None })
1053         }
1054         None => Ok(CodeLens {
1055             range: code_lens.range,
1056             command: Some(Command { title: "Error".into(), ..Default::default() }),
1057             data: None,
1058         }),
1059     }
1060 }
1061
1062 pub(crate) fn handle_document_highlight(
1063     snap: GlobalStateSnapshot,
1064     params: lsp_types::DocumentHighlightParams,
1065 ) -> Result<Option<Vec<DocumentHighlight>>> {
1066     let _p = profile::span("handle_document_highlight");
1067     let position = from_proto::file_position(&snap, params.text_document_position_params)?;
1068     let line_index = snap.analysis.file_line_index(position.file_id)?;
1069
1070     let refs = match snap
1071         .analysis
1072         .find_all_refs(position, Some(SearchScope::single_file(position.file_id)))?
1073     {
1074         None => return Ok(None),
1075         Some(refs) => refs,
1076     };
1077
1078     let res = refs
1079         .into_iter()
1080         .filter(|reference| reference.file_range.file_id == position.file_id)
1081         .map(|reference| DocumentHighlight {
1082             range: to_proto::range(&line_index, reference.file_range.range),
1083             kind: reference.access.map(to_proto::document_highlight_kind),
1084         })
1085         .collect();
1086     Ok(Some(res))
1087 }
1088
1089 pub(crate) fn handle_ssr(
1090     snap: GlobalStateSnapshot,
1091     params: lsp_ext::SsrParams,
1092 ) -> Result<lsp_types::WorkspaceEdit> {
1093     let _p = profile::span("handle_ssr");
1094     let selections = params
1095         .selections
1096         .iter()
1097         .map(|range| from_proto::file_range(&snap, params.position.text_document.clone(), *range))
1098         .collect::<Result<Vec<_>, _>>()?;
1099     let position = from_proto::file_position(&snap, params.position)?;
1100     let source_change = snap.analysis.structural_search_replace(
1101         &params.query,
1102         params.parse_only,
1103         position,
1104         selections,
1105     )??;
1106     to_proto::workspace_edit(&snap, source_change)
1107 }
1108
1109 pub(crate) fn publish_diagnostics(
1110     snap: &GlobalStateSnapshot,
1111     file_id: FileId,
1112 ) -> Result<Vec<Diagnostic>> {
1113     let _p = profile::span("publish_diagnostics");
1114     let line_index = snap.analysis.file_line_index(file_id)?;
1115
1116     let diagnostics: Vec<Diagnostic> = snap
1117         .analysis
1118         .diagnostics(&snap.config.diagnostics, file_id)?
1119         .into_iter()
1120         .map(|d| Diagnostic {
1121             range: to_proto::range(&line_index, d.range),
1122             severity: Some(to_proto::diagnostic_severity(d.severity)),
1123             code: None,
1124             source: Some("rust-analyzer".to_string()),
1125             message: d.message,
1126             related_information: None,
1127             tags: if d.unused { Some(vec![DiagnosticTag::Unnecessary]) } else { None },
1128         })
1129         .collect();
1130     Ok(diagnostics)
1131 }
1132
1133 pub(crate) fn handle_inlay_hints(
1134     snap: GlobalStateSnapshot,
1135     params: InlayHintsParams,
1136 ) -> Result<Vec<InlayHint>> {
1137     let _p = profile::span("handle_inlay_hints");
1138     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
1139     let line_index = snap.analysis.file_line_index(file_id)?;
1140     Ok(snap
1141         .analysis
1142         .inlay_hints(file_id, &snap.config.inlay_hints)?
1143         .into_iter()
1144         .map(|it| to_proto::inlay_hint(&line_index, it))
1145         .collect())
1146 }
1147
1148 pub(crate) fn handle_call_hierarchy_prepare(
1149     snap: GlobalStateSnapshot,
1150     params: CallHierarchyPrepareParams,
1151 ) -> Result<Option<Vec<CallHierarchyItem>>> {
1152     let _p = profile::span("handle_call_hierarchy_prepare");
1153     let position = from_proto::file_position(&snap, params.text_document_position_params)?;
1154
1155     let nav_info = match snap.analysis.call_hierarchy(position)? {
1156         None => return Ok(None),
1157         Some(it) => it,
1158     };
1159
1160     let RangeInfo { range: _, info: navs } = nav_info;
1161     let res = navs
1162         .into_iter()
1163         .filter(|it| it.kind == SyntaxKind::FN)
1164         .map(|it| to_proto::call_hierarchy_item(&snap, it))
1165         .collect::<Result<Vec<_>>>()?;
1166
1167     Ok(Some(res))
1168 }
1169
1170 pub(crate) fn handle_call_hierarchy_incoming(
1171     snap: GlobalStateSnapshot,
1172     params: CallHierarchyIncomingCallsParams,
1173 ) -> Result<Option<Vec<CallHierarchyIncomingCall>>> {
1174     let _p = profile::span("handle_call_hierarchy_incoming");
1175     let item = params.item;
1176
1177     let doc = TextDocumentIdentifier::new(item.uri);
1178     let frange = from_proto::file_range(&snap, doc, item.selection_range)?;
1179     let fpos = FilePosition { file_id: frange.file_id, offset: frange.range.start() };
1180
1181     let call_items = match snap.analysis.incoming_calls(fpos)? {
1182         None => return Ok(None),
1183         Some(it) => it,
1184     };
1185
1186     let mut res = vec![];
1187
1188     for call_item in call_items.into_iter() {
1189         let file_id = call_item.target.file_id;
1190         let line_index = snap.analysis.file_line_index(file_id)?;
1191         let item = to_proto::call_hierarchy_item(&snap, call_item.target)?;
1192         res.push(CallHierarchyIncomingCall {
1193             from: item,
1194             from_ranges: call_item
1195                 .ranges
1196                 .into_iter()
1197                 .map(|it| to_proto::range(&line_index, it))
1198                 .collect(),
1199         });
1200     }
1201
1202     Ok(Some(res))
1203 }
1204
1205 pub(crate) fn handle_call_hierarchy_outgoing(
1206     snap: GlobalStateSnapshot,
1207     params: CallHierarchyOutgoingCallsParams,
1208 ) -> Result<Option<Vec<CallHierarchyOutgoingCall>>> {
1209     let _p = profile::span("handle_call_hierarchy_outgoing");
1210     let item = params.item;
1211
1212     let doc = TextDocumentIdentifier::new(item.uri);
1213     let frange = from_proto::file_range(&snap, doc, item.selection_range)?;
1214     let fpos = FilePosition { file_id: frange.file_id, offset: frange.range.start() };
1215
1216     let call_items = match snap.analysis.outgoing_calls(fpos)? {
1217         None => return Ok(None),
1218         Some(it) => it,
1219     };
1220
1221     let mut res = vec![];
1222
1223     for call_item in call_items.into_iter() {
1224         let file_id = call_item.target.file_id;
1225         let line_index = snap.analysis.file_line_index(file_id)?;
1226         let item = to_proto::call_hierarchy_item(&snap, call_item.target)?;
1227         res.push(CallHierarchyOutgoingCall {
1228             to: item,
1229             from_ranges: call_item
1230                 .ranges
1231                 .into_iter()
1232                 .map(|it| to_proto::range(&line_index, it))
1233                 .collect(),
1234         });
1235     }
1236
1237     Ok(Some(res))
1238 }
1239
1240 pub(crate) fn handle_semantic_tokens_full(
1241     snap: GlobalStateSnapshot,
1242     params: SemanticTokensParams,
1243 ) -> Result<Option<SemanticTokensResult>> {
1244     let _p = profile::span("handle_semantic_tokens_full");
1245
1246     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
1247     let text = snap.analysis.file_text(file_id)?;
1248     let line_index = snap.analysis.file_line_index(file_id)?;
1249
1250     let highlights = snap.analysis.highlight(file_id)?;
1251     let semantic_tokens = to_proto::semantic_tokens(&text, &line_index, highlights);
1252
1253     // Unconditionally cache the tokens
1254     snap.semantic_tokens_cache.lock().insert(params.text_document.uri, semantic_tokens.clone());
1255
1256     Ok(Some(semantic_tokens.into()))
1257 }
1258
1259 pub(crate) fn handle_semantic_tokens_full_delta(
1260     snap: GlobalStateSnapshot,
1261     params: SemanticTokensDeltaParams,
1262 ) -> Result<Option<SemanticTokensFullDeltaResult>> {
1263     let _p = profile::span("handle_semantic_tokens_full_delta");
1264
1265     let file_id = from_proto::file_id(&snap, &params.text_document.uri)?;
1266     let text = snap.analysis.file_text(file_id)?;
1267     let line_index = snap.analysis.file_line_index(file_id)?;
1268
1269     let highlights = snap.analysis.highlight(file_id)?;
1270
1271     let semantic_tokens = to_proto::semantic_tokens(&text, &line_index, highlights);
1272
1273     let mut cache = snap.semantic_tokens_cache.lock();
1274     let cached_tokens = cache.entry(params.text_document.uri).or_default();
1275
1276     if let Some(prev_id) = &cached_tokens.result_id {
1277         if *prev_id == params.previous_result_id {
1278             let delta = to_proto::semantic_token_delta(&cached_tokens, &semantic_tokens);
1279             *cached_tokens = semantic_tokens;
1280             return Ok(Some(delta.into()));
1281         }
1282     }
1283
1284     *cached_tokens = semantic_tokens.clone();
1285
1286     Ok(Some(semantic_tokens.into()))
1287 }
1288
1289 pub(crate) fn handle_semantic_tokens_range(
1290     snap: GlobalStateSnapshot,
1291     params: SemanticTokensRangeParams,
1292 ) -> Result<Option<SemanticTokensRangeResult>> {
1293     let _p = profile::span("handle_semantic_tokens_range");
1294
1295     let frange = from_proto::file_range(&snap, params.text_document, params.range)?;
1296     let text = snap.analysis.file_text(frange.file_id)?;
1297     let line_index = snap.analysis.file_line_index(frange.file_id)?;
1298
1299     let highlights = snap.analysis.highlight_range(frange)?;
1300     let semantic_tokens = to_proto::semantic_tokens(&text, &line_index, highlights);
1301     Ok(Some(semantic_tokens.into()))
1302 }
1303
1304 pub(crate) fn handle_open_docs(
1305     snap: GlobalStateSnapshot,
1306     params: lsp_types::TextDocumentPositionParams,
1307 ) -> Result<Option<lsp_types::Url>> {
1308     let _p = profile::span("handle_open_docs");
1309     let position = from_proto::file_position(&snap, params)?;
1310
1311     let remote = snap.analysis.external_docs(position)?;
1312
1313     Ok(remote.and_then(|remote| Url::parse(&remote).ok()))
1314 }
1315
1316 fn implementation_title(count: usize) -> String {
1317     if count == 1 {
1318         "1 implementation".into()
1319     } else {
1320         format!("{} implementations", count)
1321     }
1322 }
1323
1324 fn reference_title(count: usize) -> String {
1325     if count == 1 {
1326         "1 reference".into()
1327     } else {
1328         format!("{} references", count)
1329     }
1330 }
1331
1332 fn show_references_command(
1333     title: String,
1334     uri: &lsp_types::Url,
1335     position: lsp_types::Position,
1336     locations: Vec<lsp_types::Location>,
1337 ) -> Command {
1338     // We cannot use the 'editor.action.showReferences' command directly
1339     // because that command requires vscode types which we convert in the handler
1340     // on the client side.
1341
1342     Command {
1343         title,
1344         command: "rust-analyzer.showReferences".into(),
1345         arguments: Some(vec![
1346             to_value(uri).unwrap(),
1347             to_value(position).unwrap(),
1348             to_value(locations).unwrap(),
1349         ]),
1350     }
1351 }
1352
1353 fn run_single_command(runnable: &lsp_ext::Runnable, title: &str) -> Command {
1354     Command {
1355         title: title.to_string(),
1356         command: "rust-analyzer.runSingle".into(),
1357         arguments: Some(vec![to_value(runnable).unwrap()]),
1358     }
1359 }
1360
1361 fn debug_single_command(runnable: &lsp_ext::Runnable) -> Command {
1362     Command {
1363         title: "Debug".into(),
1364         command: "rust-analyzer.debugSingle".into(),
1365         arguments: Some(vec![to_value(runnable).unwrap()]),
1366     }
1367 }
1368
1369 fn goto_location_command(snap: &GlobalStateSnapshot, nav: &NavigationTarget) -> Option<Command> {
1370     let value = if snap.config.client_caps.location_link {
1371         let link = to_proto::location_link(snap, None, nav.clone()).ok()?;
1372         to_value(link).ok()?
1373     } else {
1374         let range = FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() };
1375         let location = to_proto::location(snap, range).ok()?;
1376         to_value(location).ok()?
1377     };
1378
1379     Some(Command {
1380         title: nav.name.to_string(),
1381         command: "rust-analyzer.gotoLocation".into(),
1382         arguments: Some(vec![value]),
1383     })
1384 }
1385
1386 fn to_command_link(command: Command, tooltip: String) -> lsp_ext::CommandLink {
1387     lsp_ext::CommandLink { tooltip: Some(tooltip), command }
1388 }
1389
1390 fn show_impl_command_link(
1391     snap: &GlobalStateSnapshot,
1392     position: &FilePosition,
1393 ) -> Option<lsp_ext::CommandLinkGroup> {
1394     if snap.config.hover.implementations {
1395         if let Some(nav_data) = snap.analysis.goto_implementation(*position).unwrap_or(None) {
1396             let uri = to_proto::url(snap, position.file_id);
1397             let line_index = snap.analysis.file_line_index(position.file_id).ok()?;
1398             let position = to_proto::position(&line_index, position.offset);
1399             let locations: Vec<_> = nav_data
1400                 .info
1401                 .into_iter()
1402                 .filter_map(|nav| to_proto::location_from_nav(snap, nav).ok())
1403                 .collect();
1404             let title = implementation_title(locations.len());
1405             let command = show_references_command(title, &uri, position, locations);
1406
1407             return Some(lsp_ext::CommandLinkGroup {
1408                 commands: vec![to_command_link(command, "Go to implementations".into())],
1409                 ..Default::default()
1410             });
1411         }
1412     }
1413     None
1414 }
1415
1416 fn runnable_action_links(
1417     snap: &GlobalStateSnapshot,
1418     file_id: FileId,
1419     runnable: Runnable,
1420 ) -> Option<lsp_ext::CommandLinkGroup> {
1421     let cargo_spec = CargoTargetSpec::for_file(&snap, file_id).ok()?;
1422     if !snap.config.hover.runnable() || should_skip_target(&runnable, cargo_spec.as_ref()) {
1423         return None;
1424     }
1425
1426     let action: &'static _ = runnable.action();
1427     to_proto::runnable(snap, file_id, runnable).ok().map(|r| {
1428         let mut group = lsp_ext::CommandLinkGroup::default();
1429
1430         if snap.config.hover.run {
1431             let run_command = run_single_command(&r, action.run_title);
1432             group.commands.push(to_command_link(run_command, r.label.clone()));
1433         }
1434
1435         if snap.config.hover.debug {
1436             let dbg_command = debug_single_command(&r);
1437             group.commands.push(to_command_link(dbg_command, r.label));
1438         }
1439
1440         group
1441     })
1442 }
1443
1444 fn goto_type_action_links(
1445     snap: &GlobalStateSnapshot,
1446     nav_targets: &[HoverGotoTypeData],
1447 ) -> Option<lsp_ext::CommandLinkGroup> {
1448     if !snap.config.hover.goto_type_def || nav_targets.is_empty() {
1449         return None;
1450     }
1451
1452     Some(lsp_ext::CommandLinkGroup {
1453         title: Some("Go to ".into()),
1454         commands: nav_targets
1455             .iter()
1456             .filter_map(|it| {
1457                 goto_location_command(snap, &it.nav)
1458                     .map(|cmd| to_command_link(cmd, it.mod_path.clone()))
1459             })
1460             .collect(),
1461     })
1462 }
1463
1464 fn prepare_hover_actions(
1465     snap: &GlobalStateSnapshot,
1466     file_id: FileId,
1467     actions: &[HoverAction],
1468 ) -> Vec<lsp_ext::CommandLinkGroup> {
1469     if snap.config.hover.none() || !snap.config.client_caps.hover_actions {
1470         return Vec::new();
1471     }
1472
1473     actions
1474         .iter()
1475         .filter_map(|it| match it {
1476             HoverAction::Implementaion(position) => show_impl_command_link(snap, position),
1477             HoverAction::Runnable(r) => runnable_action_links(snap, file_id, r.clone()),
1478             HoverAction::GoToType(targets) => goto_type_action_links(snap, targets),
1479         })
1480         .collect()
1481 }
1482
1483 fn should_skip_target(runnable: &Runnable, cargo_spec: Option<&CargoTargetSpec>) -> bool {
1484     match runnable.kind {
1485         RunnableKind::Bin => {
1486             // Do not suggest binary run on other target than binary
1487             match &cargo_spec {
1488                 Some(spec) => !matches!(
1489                     spec.target_kind,
1490                     TargetKind::Bin | TargetKind::Example | TargetKind::Test
1491                 ),
1492                 None => true,
1493             }
1494         }
1495         _ => false,
1496     }
1497 }