1 //! This module is responsible for implementing handlers for Language Server
2 //! Protocol. The majority of requests are fulfilled by calling into the
7 process::{self, Stdio},
11 FileId, FilePosition, FileRange, HoverAction, HoverGotoTypeData, NavigationTarget, Query,
12 RangeInfo, Runnable, RunnableKind, SearchScope, TextEdit,
14 use itertools::Itertools;
15 use lsp_server::ErrorCode;
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,
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};
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,
41 pub(crate) fn handle_analyzer_status(
42 snap: GlobalStateSnapshot,
43 params: lsp_ext::AnalyzerStatusParams,
45 let _p = profile::span("handle_analyzer_status");
47 let mut buf = String::new();
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),
57 if snap.workspaces.is_empty() {
58 buf.push_str("no workspaces\n")
60 buf.push_str("workspaces:\n");
61 for w in snap.workspaces.iter() {
62 format_to!(buf, "{} packages loaded\n", w.n_packages());
65 buf.push_str("\nanalysis:\n");
70 .unwrap_or_else(|_| "Analysis retrieval was cancelled".to_owned()),
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());
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();
85 let mut out = String::new();
86 for (name, bytes) in mem {
87 format_to!(out, "{:>8} {}\n", bytes, name);
92 pub(crate) fn handle_syntax_tree(
93 snap: GlobalStateSnapshot,
94 params: lsp_ext::SyntaxTreeParams,
96 let _p = profile::span("handle_syntax_tree");
97 let id = from_proto::file_id(&snap, ¶ms.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)?;
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, ¶ms.text_document.uri)?;
110 let line_index = snap.analysis.file_line_index(file_id)?;
111 let offset = from_proto::offset(&line_index, params.position);
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 }))
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, ¶ms.text_document.uri)?;
123 let line_index = snap.analysis.file_line_index(file_id)?;
124 let res: Result<Vec<lsp_types::SelectionRange>> = params
128 let offset = from_proto::offset(&line_index, position);
129 let mut ranges = Vec::new();
131 let mut range = TextRange::new(offset, offset);
134 let frange = FileRange { file_id, range };
135 let next = snap.analysis.extend_selection(frange)?;
143 let mut range = lsp_types::SelectionRange {
144 range: to_proto::range(&line_index, *ranges.last().unwrap()),
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)),
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, ¶ms.text_document.uri)?;
166 let line_index = snap.analysis.file_line_index(file_id)?;
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,
176 to_proto::position(&line_index, offset)
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, ¶ms.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) {
197 // just ignore overlapping edits
201 let res = to_proto::text_edit_vec(&line_index, line_endings, res);
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),
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);
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);
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');
236 let text = snap.analysis.file_text(position.file_id)?;
237 text[usize::from(position.offset)..].starts_with(char_typed)
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 == '>' {
248 let edit = snap.analysis.on_char_typed(position, char_typed)?;
249 let mut edit = match edit {
251 None => return Ok(None),
254 // This should be a single-file edit
255 let edit = edit.source_file_edits.pop().unwrap();
257 let change = to_proto::text_edit_vec(&line_index, line_endings, edit.edit);
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, ¶ms.text_document.uri)?;
267 let line_index = snap.analysis.file_line_index(file_id)?;
269 let mut parents: Vec<(DocumentSymbol, Option<usize>)> = Vec::new();
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)
278 let doc_symbol = DocumentSymbol {
280 detail: symbol.detail,
281 kind: to_proto::symbol_kind(symbol.kind),
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),
288 parents.push((doc_symbol, symbol.parent));
291 // Builds hierarchy from a flat list, in reverse order (so that indices
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 {
299 let parent = match parent_idx {
301 Some(i) => parents[i].0.children.get_or_insert_with(Vec::new),
309 let res = if snap.config.client_caps.hierarchical_symbols {
310 document_symbols.into()
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);
317 symbol_information.into()
319 return Ok(Some(res));
321 fn flatten_document_symbol(
322 symbol: &DocumentSymbol,
323 container_name: Option<String>,
325 res: &mut Vec<SymbolInformation>,
327 let mut tags = Vec::new();
330 match symbol.deprecated {
331 Some(true) => tags.push(SymbolTag::Deprecated),
336 res.push(SymbolInformation {
337 name: symbol.name.clone(),
340 deprecated: symbol.deprecated,
341 location: Location::new(url.clone(), symbol.range),
345 for child in symbol.children.iter().flatten() {
346 flatten_document_symbol(child, Some(symbol.name.clone()), url, res);
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('*');
359 let query: String = params.query.chars().filter(|&c| c != '#' && c != '*').collect();
360 let mut q = Query::new(query);
370 let mut res = exec_query(&snap, query)?;
371 if res.is_empty() && !all_symbols {
372 let mut query = Query::new(params.query);
374 res = exec_query(&snap, query)?;
377 return Ok(Some(res));
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());
385 let info = SymbolInformation {
386 name: nav.name.to_string(),
387 kind: to_proto::symbol_kind(nav.kind),
389 location: to_proto::location_from_nav(snap, nav)?,
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),
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)?;
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),
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)?;
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),
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)?;
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)?;
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, ¶ms.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)?;
465 let expect_test = match 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")
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) {
482 if should_skip_target(&runnable, cargo_spec.as_ref()) {
485 let mut runnable = to_proto::runnable(&snap, file_id, runnable)?;
487 runnable.label = format!("{} + expect", runnable.label);
488 runnable.args.expect_test = Some(true);
493 // Add `cargo check` and `cargo test` for all targets of the whole package
494 let config = &snap.config.runnables;
497 for &cmd in ["check", "test"].iter() {
498 res.push(lsp_ext::Runnable {
499 label: format!("cargo {} -p {} --all-targets", cmd, spec.package),
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(),
507 "--package".to_string(),
508 spec.package.clone(),
509 "--all-targets".to_string(),
511 cargo_extra_args: config.cargo_extra_args.clone(),
512 executable_args: Vec::new(),
519 res.push(lsp_ext::Runnable {
520 label: "cargo check --workspace".to_string(),
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(),
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 = {
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(':') {
561 if completion_triggered_after_single_colon {
565 let items = match snap.analysis.completions(&snap.config.completion, position)? {
566 None => return Ok(None),
567 Some(items) => items,
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
573 .flat_map(|item| to_proto::completion_item(&line_index, line_endings, item))
576 Ok(Some(items.into()))
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, ¶ms.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;
591 .map(|it| to_proto::folding_range(&*text, &line_index, line_folding_only, it))
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)? {
604 None => return Ok(None),
606 let concise = !snap.config.call_info_full;
607 let res = to_proto::signature_help(
610 snap.config.client_caps.signature_help_label_offsets,
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(
623 snap.config.hover.links_in_hover,
624 snap.config.hover.markdown,
626 None => return Ok(None),
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)),
636 actions: prepare_hover_actions(&snap, position.file_id, &info.info.actions),
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)?;
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)))
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)?;
662 if params.new_name.is_empty() {
663 return Err(LspError::new(
664 ErrorCode::InvalidParams as i32,
665 "New Name cannot be empty".into(),
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))
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)?;
682 let refs = match snap.analysis.find_all_refs(position, None)? {
683 None => return Ok(None),
687 let locations = if params.context.include_declaration {
689 .filter_map(|reference| to_proto::location(&snap, reference.file_range).ok())
692 // Only iterate over the references if include_declaration was false
695 .filter_map(|reference| to_proto::location(&snap, reference.file_range).ok())
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, ¶ms.text_document.uri)?;
708 let file = snap.analysis.file_text(file_id)?;
709 let crate_ids = snap.analysis.crate_for(file_id)?;
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()));
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());
726 RustfmtConfig::CustomCommand { command, args } => {
727 let mut cmd = process::Command::new(command);
733 let mut rustfmt = rustfmt.stdin(Stdio::piped()).stdout(Stdio::piped()).spawn()?;
735 rustfmt.stdin.as_mut().unwrap().write_all(file.as_bytes())?;
737 let output = rustfmt.wait_with_output()?;
738 let captured_stdout = String::from_utf8(output.stdout)?;
740 if !output.status.success() {
741 match output.status.code() {
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");
752 // Something else happened - e.g. `rustfmt` is missing or caught a signal
753 return Err(LspError::new(
756 r#"rustfmt exited with:
759 output.status, captured_stdout,
767 if *file == captured_stdout {
768 // The document is already formatted correctly -- no edits needed.
771 Ok(Some(vec![lsp_types::TextEdit {
772 range: Range::new(Position::new(0, 0), end_position),
773 new_text: captured_stdout,
779 snap: &GlobalStateSnapshot,
780 params: &lsp_types::CodeActionParams,
781 res: &mut Vec<lsp_ext::CodeAction>,
783 let file_id = from_proto::file_id(&snap, ¶ms.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);
787 match ¶ms.context.only {
789 if !v.iter().any(|it| {
790 it == &lsp_types::CodeActionKind::EMPTY
791 || it == &lsp_types::CodeActionKind::QUICKFIX
799 let diagnostics = snap.analysis.diagnostics(&snap.config.diagnostics, file_id)?;
801 for fix in diagnostics
803 .filter_map(|d| d.fix)
804 .filter(|fix| fix.fix_trigger_range.intersect(range).is_some())
806 let edit = to_proto::snippet_workspace_edit(&snap, fix.source_change)?;
807 let action = lsp_ext::CodeAction {
808 title: fix.label.to_string(),
811 kind: Some(CodeActionKind::QUICKFIX),
813 is_preferred: Some(false),
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() {
823 res.push(fix.action.clone());
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 {
840 let file_id = from_proto::file_id(&snap, ¶ms.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 };
845 snap.config.assist.allowed = params
849 .map(|it| it.into_iter().filter_map(from_proto::assist_kind).collect());
851 let mut res: Vec<lsp_ext::CodeAction> = Vec::new();
853 handle_fixes(&snap, ¶ms, &mut res)?;
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()
859 res.push(to_proto::unresolved_code_action(&snap, assist, index)?);
862 for assist in snap.analysis.resolved_assists(&snap.config.assist, frange)?.into_iter() {
863 res.push(to_proto::resolved_code_action(&snap, assist)?);
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, ¶ms.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 };
880 snap.config.assist.allowed = params
884 .map(|it| it.into_iter().filter_map(from_proto::assist_kind).collect());
886 let assists = snap.analysis.resolved_assists(&snap.config.assist, frange)?;
887 let (id, index) = split_once(¶ms.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)
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();
901 if snap.config.lens.none() {
902 // early return before any db query!
903 return Ok(Some(lenses));
906 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
907 let line_index = snap.analysis.file_line_index(file_id)?;
908 let cargo_spec = CargoTargetSpec::for_file(&snap, file_id)?;
910 if snap.config.lens.runnable() {
912 for runnable in snap.analysis.runnables(file_id)? {
913 if should_skip_target(&runnable, cargo_spec.as_ref()) {
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 {
923 command: Some(run_single_command(&r, action.run_title)),
929 if action.debugee && snap.config.lens.debug {
931 CodeLens { range, command: Some(debug_single_command(&r)), data: None };
932 lenses.push(debug_lens);
937 if snap.config.lens.implementations {
941 .file_structure(file_id)?
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(),
960 work_done_progress_params: Default::default(),
961 partial_result_params: Default::default(),
966 data: Some(to_value(CodeLensResolveData::Impls(lens_params)).unwrap()),
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());
977 lsp_types::TextDocumentPositionParams::new(params.text_document.clone(), position);
982 data: Some(to_value(CodeLensResolveData::References(lens_params)).unwrap()),
990 #[derive(Debug, Serialize, Deserialize)]
991 #[serde(rename_all = "camelCase")]
992 enum CodeLensResolveData {
993 Impls(lsp_types::request::GotoImplementationParams),
994 References(lsp_types::TextDocumentPositionParams),
997 pub(crate) fn handle_code_lens_resolve(
998 snap: GlobalStateSnapshot,
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)?;
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
1012 .map(|link| Location::new(link.target_uri, link.target_selection_range))
1017 let title = implementation_title(locations.len());
1018 let cmd = show_references_command(
1020 &lens_params.text_document_position_params.text_document.uri,
1021 code_lens.range.start,
1024 Ok(CodeLens { range: code_lens.range, command: Some(cmd), data: None })
1026 Some(CodeLensResolveData::References(doc_position)) => {
1027 let position = from_proto::file_position(&snap, doc_position.clone())?;
1028 let locations = snap
1030 .find_all_refs(position, None)
1035 .filter_map(|it| to_proto::location(&snap, it.file_range).ok())
1038 .unwrap_or_default();
1040 let title = reference_title(locations.len());
1041 let cmd = if locations.is_empty() {
1042 Command { title, command: "".into(), arguments: None }
1044 show_references_command(
1046 &doc_position.text_document.uri,
1047 code_lens.range.start,
1052 Ok(CodeLens { range: code_lens.range, command: Some(cmd), data: None })
1054 None => Ok(CodeLens {
1055 range: code_lens.range,
1056 command: Some(Command { title: "Error".into(), ..Default::default() }),
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)?;
1070 let refs = match snap
1072 .find_all_refs(position, Some(SearchScope::single_file(position.file_id)))?
1074 None => return Ok(None),
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),
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
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(
1106 to_proto::workspace_edit(&snap, source_change)
1109 pub(crate) fn publish_diagnostics(
1110 snap: &GlobalStateSnapshot,
1112 ) -> Result<Vec<Diagnostic>> {
1113 let _p = profile::span("publish_diagnostics");
1114 let line_index = snap.analysis.file_line_index(file_id)?;
1116 let diagnostics: Vec<Diagnostic> = snap
1118 .diagnostics(&snap.config.diagnostics, file_id)?
1120 .map(|d| Diagnostic {
1121 range: to_proto::range(&line_index, d.range),
1122 severity: Some(to_proto::diagnostic_severity(d.severity)),
1124 source: Some("rust-analyzer".to_string()),
1126 related_information: None,
1127 tags: if d.unused { Some(vec![DiagnosticTag::Unnecessary]) } else { None },
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, ¶ms.text_document.uri)?;
1139 let line_index = snap.analysis.file_line_index(file_id)?;
1142 .inlay_hints(file_id, &snap.config.inlay_hints)?
1144 .map(|it| to_proto::inlay_hint(&line_index, it))
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)?;
1155 let nav_info = match snap.analysis.call_hierarchy(position)? {
1156 None => return Ok(None),
1160 let RangeInfo { range: _, info: navs } = nav_info;
1163 .filter(|it| it.kind == SyntaxKind::FN)
1164 .map(|it| to_proto::call_hierarchy_item(&snap, it))
1165 .collect::<Result<Vec<_>>>()?;
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;
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() };
1181 let call_items = match snap.analysis.incoming_calls(fpos)? {
1182 None => return Ok(None),
1186 let mut res = vec![];
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 {
1194 from_ranges: call_item
1197 .map(|it| to_proto::range(&line_index, it))
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;
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() };
1216 let call_items = match snap.analysis.outgoing_calls(fpos)? {
1217 None => return Ok(None),
1221 let mut res = vec![];
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 {
1229 from_ranges: call_item
1232 .map(|it| to_proto::range(&line_index, it))
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");
1246 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
1247 let text = snap.analysis.file_text(file_id)?;
1248 let line_index = snap.analysis.file_line_index(file_id)?;
1250 let highlights = snap.analysis.highlight(file_id)?;
1251 let semantic_tokens = to_proto::semantic_tokens(&text, &line_index, highlights);
1253 // Unconditionally cache the tokens
1254 snap.semantic_tokens_cache.lock().insert(params.text_document.uri, semantic_tokens.clone());
1256 Ok(Some(semantic_tokens.into()))
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");
1265 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
1266 let text = snap.analysis.file_text(file_id)?;
1267 let line_index = snap.analysis.file_line_index(file_id)?;
1269 let highlights = snap.analysis.highlight(file_id)?;
1271 let semantic_tokens = to_proto::semantic_tokens(&text, &line_index, highlights);
1273 let mut cache = snap.semantic_tokens_cache.lock();
1274 let cached_tokens = cache.entry(params.text_document.uri).or_default();
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()));
1284 *cached_tokens = semantic_tokens.clone();
1286 Ok(Some(semantic_tokens.into()))
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");
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)?;
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()))
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)?;
1311 let remote = snap.analysis.external_docs(position)?;
1313 Ok(remote.and_then(|remote| Url::parse(&remote).ok()))
1316 fn implementation_title(count: usize) -> String {
1318 "1 implementation".into()
1320 format!("{} implementations", count)
1324 fn reference_title(count: usize) -> String {
1326 "1 reference".into()
1328 format!("{} references", count)
1332 fn show_references_command(
1334 uri: &lsp_types::Url,
1335 position: lsp_types::Position,
1336 locations: Vec<lsp_types::Location>,
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.
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(),
1353 fn run_single_command(runnable: &lsp_ext::Runnable, title: &str) -> Command {
1355 title: title.to_string(),
1356 command: "rust-analyzer.runSingle".into(),
1357 arguments: Some(vec![to_value(runnable).unwrap()]),
1361 fn debug_single_command(runnable: &lsp_ext::Runnable) -> Command {
1363 title: "Debug".into(),
1364 command: "rust-analyzer.debugSingle".into(),
1365 arguments: Some(vec![to_value(runnable).unwrap()]),
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()?
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()?
1380 title: nav.name.to_string(),
1381 command: "rust-analyzer.gotoLocation".into(),
1382 arguments: Some(vec![value]),
1386 fn to_command_link(command: Command, tooltip: String) -> lsp_ext::CommandLink {
1387 lsp_ext::CommandLink { tooltip: Some(tooltip), command }
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
1402 .filter_map(|nav| to_proto::location_from_nav(snap, nav).ok())
1404 let title = implementation_title(locations.len());
1405 let command = show_references_command(title, &uri, position, locations);
1407 return Some(lsp_ext::CommandLinkGroup {
1408 commands: vec![to_command_link(command, "Go to implementations".into())],
1409 ..Default::default()
1416 fn runnable_action_links(
1417 snap: &GlobalStateSnapshot,
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()) {
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();
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()));
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));
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() {
1452 Some(lsp_ext::CommandLinkGroup {
1453 title: Some("Go to ".into()),
1454 commands: nav_targets
1457 goto_location_command(snap, &it.nav)
1458 .map(|cmd| to_command_link(cmd, it.mod_path.clone()))
1464 fn prepare_hover_actions(
1465 snap: &GlobalStateSnapshot,
1467 actions: &[HoverAction],
1468 ) -> Vec<lsp_ext::CommandLinkGroup> {
1469 if snap.config.hover.none() || !snap.config.client_caps.hover_actions {
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),
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
1488 Some(spec) => !matches!(
1490 TargetKind::Bin | TargetKind::Example | TargetKind::Test