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, NumberOrString, 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 let completion_list = lsp_types::CompletionList { is_incomplete: true, items };
577 Ok(Some(completion_list.into()))
580 pub(crate) fn handle_folding_range(
581 snap: GlobalStateSnapshot,
582 params: FoldingRangeParams,
583 ) -> Result<Option<Vec<FoldingRange>>> {
584 let _p = profile::span("handle_folding_range");
585 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
586 let folds = snap.analysis.folding_ranges(file_id)?;
587 let text = snap.analysis.file_text(file_id)?;
588 let line_index = snap.analysis.file_line_index(file_id)?;
589 let line_folding_only = snap.config.client_caps.line_folding_only;
592 .map(|it| to_proto::folding_range(&*text, &line_index, line_folding_only, it))
597 pub(crate) fn handle_signature_help(
598 snap: GlobalStateSnapshot,
599 params: lsp_types::SignatureHelpParams,
600 ) -> Result<Option<lsp_types::SignatureHelp>> {
601 let _p = profile::span("handle_signature_help");
602 let position = from_proto::file_position(&snap, params.text_document_position_params)?;
603 let call_info = match snap.analysis.call_info(position)? {
605 None => return Ok(None),
607 let concise = !snap.config.call_info_full;
608 let res = to_proto::signature_help(
611 snap.config.client_caps.signature_help_label_offsets,
616 pub(crate) fn handle_hover(
617 snap: GlobalStateSnapshot,
618 params: lsp_types::HoverParams,
619 ) -> Result<Option<lsp_ext::Hover>> {
620 let _p = profile::span("handle_hover");
621 let position = from_proto::file_position(&snap, params.text_document_position_params)?;
622 let info = match snap.analysis.hover(
624 snap.config.hover.links_in_hover,
625 snap.config.hover.markdown,
627 None => return Ok(None),
630 let line_index = snap.analysis.file_line_index(position.file_id)?;
631 let range = to_proto::range(&line_index, info.range);
632 let hover = lsp_ext::Hover {
633 hover: lsp_types::Hover {
634 contents: HoverContents::Markup(to_proto::markup_content(info.info.markup)),
637 actions: prepare_hover_actions(&snap, position.file_id, &info.info.actions),
643 pub(crate) fn handle_prepare_rename(
644 snap: GlobalStateSnapshot,
645 params: lsp_types::TextDocumentPositionParams,
646 ) -> Result<Option<PrepareRenameResponse>> {
647 let _p = profile::span("handle_prepare_rename");
648 let position = from_proto::file_position(&snap, params)?;
650 let change = snap.analysis.rename(position, "dummy")??;
651 let line_index = snap.analysis.file_line_index(position.file_id)?;
652 let range = to_proto::range(&line_index, change.range);
653 Ok(Some(PrepareRenameResponse::Range(range)))
656 pub(crate) fn handle_rename(
657 snap: GlobalStateSnapshot,
658 params: RenameParams,
659 ) -> Result<Option<WorkspaceEdit>> {
660 let _p = profile::span("handle_rename");
661 let position = from_proto::file_position(&snap, params.text_document_position)?;
663 if params.new_name.is_empty() {
664 return Err(LspError::new(
665 ErrorCode::InvalidParams as i32,
666 "New Name cannot be empty".into(),
671 let change = snap.analysis.rename(position, &*params.new_name)??;
672 let workspace_edit = to_proto::workspace_edit(&snap, change.info)?;
673 Ok(Some(workspace_edit))
676 pub(crate) fn handle_references(
677 snap: GlobalStateSnapshot,
678 params: lsp_types::ReferenceParams,
679 ) -> Result<Option<Vec<Location>>> {
680 let _p = profile::span("handle_references");
681 let position = from_proto::file_position(&snap, params.text_document_position)?;
683 let refs = match snap.analysis.find_all_refs(position, None)? {
684 None => return Ok(None),
688 let locations = if params.context.include_declaration {
690 .filter_map(|reference| to_proto::location(&snap, reference.file_range).ok())
693 // Only iterate over the references if include_declaration was false
696 .filter_map(|reference| to_proto::location(&snap, reference.file_range).ok())
703 pub(crate) fn handle_formatting(
704 snap: GlobalStateSnapshot,
705 params: DocumentFormattingParams,
706 ) -> Result<Option<Vec<lsp_types::TextEdit>>> {
707 let _p = profile::span("handle_formatting");
708 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
709 let file = snap.analysis.file_text(file_id)?;
710 let crate_ids = snap.analysis.crate_for(file_id)?;
712 let file_line_index = snap.analysis.file_line_index(file_id)?;
713 let end_position = to_proto::position(&file_line_index, TextSize::of(file.as_str()));
715 let mut rustfmt = match &snap.config.rustfmt {
716 RustfmtConfig::Rustfmt { extra_args } => {
717 let mut cmd = process::Command::new(toolchain::rustfmt());
718 cmd.args(extra_args);
719 if let Some(&crate_id) = crate_ids.first() {
720 // Assume all crates are in the same edition
721 let edition = snap.analysis.crate_edition(crate_id)?;
722 cmd.arg("--edition");
723 cmd.arg(edition.to_string());
727 RustfmtConfig::CustomCommand { command, args } => {
728 let mut cmd = process::Command::new(command);
734 let mut rustfmt = rustfmt.stdin(Stdio::piped()).stdout(Stdio::piped()).spawn()?;
736 rustfmt.stdin.as_mut().unwrap().write_all(file.as_bytes())?;
738 let output = rustfmt.wait_with_output()?;
739 let captured_stdout = String::from_utf8(output.stdout)?;
741 if !output.status.success() {
742 match output.status.code() {
744 // While `rustfmt` doesn't have a specific exit code for parse errors this is the
745 // likely cause exiting with 1. Most Language Servers swallow parse errors on
746 // formatting because otherwise an error is surfaced to the user on top of the
747 // syntax error diagnostics they're already receiving. This is especially jarring
748 // if they have format on save enabled.
749 log::info!("rustfmt exited with status 1, assuming parse error and ignoring");
753 // Something else happened - e.g. `rustfmt` is missing or caught a signal
754 return Err(LspError::new(
757 r#"rustfmt exited with:
760 output.status, captured_stdout,
768 if *file == captured_stdout {
769 // The document is already formatted correctly -- no edits needed.
772 Ok(Some(vec![lsp_types::TextEdit {
773 range: Range::new(Position::new(0, 0), end_position),
774 new_text: captured_stdout,
780 snap: &GlobalStateSnapshot,
781 params: &lsp_types::CodeActionParams,
782 res: &mut Vec<lsp_ext::CodeAction>,
784 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
785 let line_index = snap.analysis.file_line_index(file_id)?;
786 let range = from_proto::text_range(&line_index, params.range);
788 match ¶ms.context.only {
790 if !v.iter().any(|it| {
791 it == &lsp_types::CodeActionKind::EMPTY
792 || it == &lsp_types::CodeActionKind::QUICKFIX
800 let diagnostics = snap.analysis.diagnostics(&snap.config.diagnostics, file_id)?;
802 for fix in diagnostics
804 .filter_map(|d| d.fix)
805 .filter(|fix| fix.fix_trigger_range.intersect(range).is_some())
807 let edit = to_proto::snippet_workspace_edit(&snap, fix.source_change)?;
808 let action = lsp_ext::CodeAction {
809 title: fix.label.to_string(),
811 kind: Some(CodeActionKind::QUICKFIX),
813 is_preferred: Some(false),
819 for fix in snap.check_fixes.get(&file_id).into_iter().flatten() {
820 let fix_range = from_proto::text_range(&line_index, fix.range);
821 if fix_range.intersect(range).is_none() {
824 res.push(fix.action.clone());
829 pub(crate) fn handle_code_action(
830 mut snap: GlobalStateSnapshot,
831 params: lsp_types::CodeActionParams,
832 ) -> Result<Option<Vec<lsp_ext::CodeAction>>> {
833 let _p = profile::span("handle_code_action");
834 // We intentionally don't support command-based actions, as those either
835 // requires custom client-code anyway, or requires server-initiated edits.
836 // Server initiated edits break causality, so we avoid those as well.
837 if !snap.config.client_caps.code_action_literals {
841 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
842 let line_index = snap.analysis.file_line_index(file_id)?;
843 let range = from_proto::text_range(&line_index, params.range);
844 let frange = FileRange { file_id, range };
846 snap.config.assist.allowed = params
850 .map(|it| it.into_iter().filter_map(from_proto::assist_kind).collect());
852 let mut res: Vec<lsp_ext::CodeAction> = Vec::new();
854 handle_fixes(&snap, ¶ms, &mut res)?;
856 if snap.config.client_caps.code_action_resolve {
857 for (index, assist) in
858 snap.analysis.unresolved_assists(&snap.config.assist, frange)?.into_iter().enumerate()
860 res.push(to_proto::unresolved_code_action(&snap, params.clone(), assist, index)?);
863 for assist in snap.analysis.resolved_assists(&snap.config.assist, frange)?.into_iter() {
864 res.push(to_proto::resolved_code_action(&snap, assist)?);
871 pub(crate) fn handle_code_action_resolve(
872 mut snap: GlobalStateSnapshot,
873 mut code_action: lsp_ext::CodeAction,
874 ) -> Result<lsp_ext::CodeAction> {
875 let _p = profile::span("handle_code_action_resolve");
876 let params = match code_action.data.take() {
878 None => Err("can't resolve code action without data")?,
881 let file_id = from_proto::file_id(&snap, ¶ms.code_action_params.text_document.uri)?;
882 let line_index = snap.analysis.file_line_index(file_id)?;
883 let range = from_proto::text_range(&line_index, params.code_action_params.range);
884 let frange = FileRange { file_id, range };
886 snap.config.assist.allowed = params
890 .map(|it| it.into_iter().filter_map(from_proto::assist_kind).collect());
892 let assists = snap.analysis.resolved_assists(&snap.config.assist, frange)?;
893 let (id, index) = split_once(¶ms.id, ':').unwrap();
894 let index = index.parse::<usize>().unwrap();
895 let assist = &assists[index];
896 assert!(assist.assist.id.0 == id);
897 let edit = to_proto::resolved_code_action(&snap, assist.clone())?.edit;
898 code_action.edit = edit;
902 pub(crate) fn handle_code_lens(
903 snap: GlobalStateSnapshot,
904 params: lsp_types::CodeLensParams,
905 ) -> Result<Option<Vec<CodeLens>>> {
906 let _p = profile::span("handle_code_lens");
907 let mut lenses: Vec<CodeLens> = Default::default();
909 if snap.config.lens.none() {
910 // early return before any db query!
911 return Ok(Some(lenses));
914 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
915 let line_index = snap.analysis.file_line_index(file_id)?;
916 let cargo_spec = CargoTargetSpec::for_file(&snap, file_id)?;
918 if snap.config.lens.runnable() {
920 for runnable in snap.analysis.runnables(file_id)? {
921 if should_skip_target(&runnable, cargo_spec.as_ref()) {
925 let action = runnable.action();
926 let range = to_proto::range(&line_index, runnable.nav.full_range);
927 let r = to_proto::runnable(&snap, file_id, runnable)?;
928 if snap.config.lens.run {
929 let lens = CodeLens {
931 command: Some(run_single_command(&r, action.run_title)),
937 if action.debugee && snap.config.lens.debug {
939 CodeLens { range, command: Some(debug_single_command(&r)), data: None };
940 lenses.push(debug_lens);
945 if snap.config.lens.implementations {
949 .file_structure(file_id)?
961 let range = to_proto::range(&line_index, it.node_range);
962 let pos = range.start;
963 let lens_params = lsp_types::request::GotoImplementationParams {
964 text_document_position_params: lsp_types::TextDocumentPositionParams::new(
965 params.text_document.clone(),
968 work_done_progress_params: Default::default(),
969 partial_result_params: Default::default(),
974 data: Some(to_value(CodeLensResolveData::Impls(lens_params)).unwrap()),
980 if snap.config.lens.references() {
981 lenses.extend(snap.analysis.find_all_methods(file_id)?.into_iter().map(|it| {
982 let range = to_proto::range(&line_index, it.range);
983 let position = to_proto::position(&line_index, it.range.start());
985 lsp_types::TextDocumentPositionParams::new(params.text_document.clone(), position);
990 data: Some(to_value(CodeLensResolveData::References(lens_params)).unwrap()),
998 #[derive(Debug, Serialize, Deserialize)]
999 #[serde(rename_all = "camelCase")]
1000 enum CodeLensResolveData {
1001 Impls(lsp_types::request::GotoImplementationParams),
1002 References(lsp_types::TextDocumentPositionParams),
1005 pub(crate) fn handle_code_lens_resolve(
1006 snap: GlobalStateSnapshot,
1007 code_lens: CodeLens,
1008 ) -> Result<CodeLens> {
1009 let _p = profile::span("handle_code_lens_resolve");
1010 let data = code_lens.data.unwrap();
1011 let resolve = from_json::<Option<CodeLensResolveData>>("CodeLensResolveData", data)?;
1013 Some(CodeLensResolveData::Impls(lens_params)) => {
1014 let locations: Vec<Location> =
1015 match handle_goto_implementation(snap, lens_params.clone())? {
1016 Some(lsp_types::GotoDefinitionResponse::Scalar(loc)) => vec![loc],
1017 Some(lsp_types::GotoDefinitionResponse::Array(locs)) => locs,
1018 Some(lsp_types::GotoDefinitionResponse::Link(links)) => links
1020 .map(|link| Location::new(link.target_uri, link.target_selection_range))
1025 let title = implementation_title(locations.len());
1026 let cmd = show_references_command(
1028 &lens_params.text_document_position_params.text_document.uri,
1029 code_lens.range.start,
1032 Ok(CodeLens { range: code_lens.range, command: Some(cmd), data: None })
1034 Some(CodeLensResolveData::References(doc_position)) => {
1035 let position = from_proto::file_position(&snap, doc_position.clone())?;
1036 let locations = snap
1038 .find_all_refs(position, None)
1043 .filter_map(|it| to_proto::location(&snap, it.file_range).ok())
1046 .unwrap_or_default();
1048 let title = reference_title(locations.len());
1049 let cmd = if locations.is_empty() {
1050 Command { title, command: "".into(), arguments: None }
1052 show_references_command(
1054 &doc_position.text_document.uri,
1055 code_lens.range.start,
1060 Ok(CodeLens { range: code_lens.range, command: Some(cmd), data: None })
1062 None => Ok(CodeLens {
1063 range: code_lens.range,
1064 command: Some(Command { title: "Error".into(), ..Default::default() }),
1070 pub(crate) fn handle_document_highlight(
1071 snap: GlobalStateSnapshot,
1072 params: lsp_types::DocumentHighlightParams,
1073 ) -> Result<Option<Vec<DocumentHighlight>>> {
1074 let _p = profile::span("handle_document_highlight");
1075 let position = from_proto::file_position(&snap, params.text_document_position_params)?;
1076 let line_index = snap.analysis.file_line_index(position.file_id)?;
1078 let refs = match snap
1080 .find_all_refs(position, Some(SearchScope::single_file(position.file_id)))?
1082 None => return Ok(None),
1088 .filter(|reference| reference.file_range.file_id == position.file_id)
1089 .map(|reference| DocumentHighlight {
1090 range: to_proto::range(&line_index, reference.file_range.range),
1091 kind: reference.access.map(to_proto::document_highlight_kind),
1097 pub(crate) fn handle_ssr(
1098 snap: GlobalStateSnapshot,
1099 params: lsp_ext::SsrParams,
1100 ) -> Result<lsp_types::WorkspaceEdit> {
1101 let _p = profile::span("handle_ssr");
1102 let selections = params
1105 .map(|range| from_proto::file_range(&snap, params.position.text_document.clone(), *range))
1106 .collect::<Result<Vec<_>, _>>()?;
1107 let position = from_proto::file_position(&snap, params.position)?;
1108 let source_change = snap.analysis.structural_search_replace(
1114 to_proto::workspace_edit(&snap, source_change)
1117 pub(crate) fn publish_diagnostics(
1118 snap: &GlobalStateSnapshot,
1120 ) -> Result<Vec<Diagnostic>> {
1121 let _p = profile::span("publish_diagnostics");
1122 let line_index = snap.analysis.file_line_index(file_id)?;
1124 let diagnostics: Vec<Diagnostic> = snap
1126 .diagnostics(&snap.config.diagnostics, file_id)?
1128 .map(|d| Diagnostic {
1129 range: to_proto::range(&line_index, d.range),
1130 severity: Some(to_proto::diagnostic_severity(d.severity)),
1131 code: d.code.map(|d| d.as_str().to_owned()).map(NumberOrString::String),
1132 code_description: d.code.and_then(|code| {
1133 lsp_types::Url::parse(&format!(
1134 "https://rust-analyzer.github.io/manual.html#{}",
1138 .map(|href| lsp_types::CodeDescription { href })
1140 source: Some("rust-analyzer".to_string()),
1142 related_information: None,
1143 tags: if d.unused { Some(vec![DiagnosticTag::Unnecessary]) } else { None },
1150 pub(crate) fn handle_inlay_hints(
1151 snap: GlobalStateSnapshot,
1152 params: InlayHintsParams,
1153 ) -> Result<Vec<InlayHint>> {
1154 let _p = profile::span("handle_inlay_hints");
1155 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
1156 let line_index = snap.analysis.file_line_index(file_id)?;
1159 .inlay_hints(file_id, &snap.config.inlay_hints)?
1161 .map(|it| to_proto::inlay_hint(&line_index, it))
1165 pub(crate) fn handle_call_hierarchy_prepare(
1166 snap: GlobalStateSnapshot,
1167 params: CallHierarchyPrepareParams,
1168 ) -> Result<Option<Vec<CallHierarchyItem>>> {
1169 let _p = profile::span("handle_call_hierarchy_prepare");
1170 let position = from_proto::file_position(&snap, params.text_document_position_params)?;
1172 let nav_info = match snap.analysis.call_hierarchy(position)? {
1173 None => return Ok(None),
1177 let RangeInfo { range: _, info: navs } = nav_info;
1180 .filter(|it| it.kind == SyntaxKind::FN)
1181 .map(|it| to_proto::call_hierarchy_item(&snap, it))
1182 .collect::<Result<Vec<_>>>()?;
1187 pub(crate) fn handle_call_hierarchy_incoming(
1188 snap: GlobalStateSnapshot,
1189 params: CallHierarchyIncomingCallsParams,
1190 ) -> Result<Option<Vec<CallHierarchyIncomingCall>>> {
1191 let _p = profile::span("handle_call_hierarchy_incoming");
1192 let item = params.item;
1194 let doc = TextDocumentIdentifier::new(item.uri);
1195 let frange = from_proto::file_range(&snap, doc, item.selection_range)?;
1196 let fpos = FilePosition { file_id: frange.file_id, offset: frange.range.start() };
1198 let call_items = match snap.analysis.incoming_calls(fpos)? {
1199 None => return Ok(None),
1203 let mut res = vec![];
1205 for call_item in call_items.into_iter() {
1206 let file_id = call_item.target.file_id;
1207 let line_index = snap.analysis.file_line_index(file_id)?;
1208 let item = to_proto::call_hierarchy_item(&snap, call_item.target)?;
1209 res.push(CallHierarchyIncomingCall {
1211 from_ranges: call_item
1214 .map(|it| to_proto::range(&line_index, it))
1222 pub(crate) fn handle_call_hierarchy_outgoing(
1223 snap: GlobalStateSnapshot,
1224 params: CallHierarchyOutgoingCallsParams,
1225 ) -> Result<Option<Vec<CallHierarchyOutgoingCall>>> {
1226 let _p = profile::span("handle_call_hierarchy_outgoing");
1227 let item = params.item;
1229 let doc = TextDocumentIdentifier::new(item.uri);
1230 let frange = from_proto::file_range(&snap, doc, item.selection_range)?;
1231 let fpos = FilePosition { file_id: frange.file_id, offset: frange.range.start() };
1233 let call_items = match snap.analysis.outgoing_calls(fpos)? {
1234 None => return Ok(None),
1238 let mut res = vec![];
1240 for call_item in call_items.into_iter() {
1241 let file_id = call_item.target.file_id;
1242 let line_index = snap.analysis.file_line_index(file_id)?;
1243 let item = to_proto::call_hierarchy_item(&snap, call_item.target)?;
1244 res.push(CallHierarchyOutgoingCall {
1246 from_ranges: call_item
1249 .map(|it| to_proto::range(&line_index, it))
1257 pub(crate) fn handle_semantic_tokens_full(
1258 snap: GlobalStateSnapshot,
1259 params: SemanticTokensParams,
1260 ) -> Result<Option<SemanticTokensResult>> {
1261 let _p = profile::span("handle_semantic_tokens_full");
1263 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
1264 let text = snap.analysis.file_text(file_id)?;
1265 let line_index = snap.analysis.file_line_index(file_id)?;
1267 let highlights = snap.analysis.highlight(file_id)?;
1268 let semantic_tokens = to_proto::semantic_tokens(&text, &line_index, highlights);
1270 // Unconditionally cache the tokens
1271 snap.semantic_tokens_cache.lock().insert(params.text_document.uri, semantic_tokens.clone());
1273 Ok(Some(semantic_tokens.into()))
1276 pub(crate) fn handle_semantic_tokens_full_delta(
1277 snap: GlobalStateSnapshot,
1278 params: SemanticTokensDeltaParams,
1279 ) -> Result<Option<SemanticTokensFullDeltaResult>> {
1280 let _p = profile::span("handle_semantic_tokens_full_delta");
1282 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
1283 let text = snap.analysis.file_text(file_id)?;
1284 let line_index = snap.analysis.file_line_index(file_id)?;
1286 let highlights = snap.analysis.highlight(file_id)?;
1288 let semantic_tokens = to_proto::semantic_tokens(&text, &line_index, highlights);
1290 let mut cache = snap.semantic_tokens_cache.lock();
1291 let cached_tokens = cache.entry(params.text_document.uri).or_default();
1293 if let Some(prev_id) = &cached_tokens.result_id {
1294 if *prev_id == params.previous_result_id {
1295 let delta = to_proto::semantic_token_delta(&cached_tokens, &semantic_tokens);
1296 *cached_tokens = semantic_tokens;
1297 return Ok(Some(delta.into()));
1301 *cached_tokens = semantic_tokens.clone();
1303 Ok(Some(semantic_tokens.into()))
1306 pub(crate) fn handle_semantic_tokens_range(
1307 snap: GlobalStateSnapshot,
1308 params: SemanticTokensRangeParams,
1309 ) -> Result<Option<SemanticTokensRangeResult>> {
1310 let _p = profile::span("handle_semantic_tokens_range");
1312 let frange = from_proto::file_range(&snap, params.text_document, params.range)?;
1313 let text = snap.analysis.file_text(frange.file_id)?;
1314 let line_index = snap.analysis.file_line_index(frange.file_id)?;
1316 let highlights = snap.analysis.highlight_range(frange)?;
1317 let semantic_tokens = to_proto::semantic_tokens(&text, &line_index, highlights);
1318 Ok(Some(semantic_tokens.into()))
1321 pub(crate) fn handle_open_docs(
1322 snap: GlobalStateSnapshot,
1323 params: lsp_types::TextDocumentPositionParams,
1324 ) -> Result<Option<lsp_types::Url>> {
1325 let _p = profile::span("handle_open_docs");
1326 let position = from_proto::file_position(&snap, params)?;
1328 let remote = snap.analysis.external_docs(position)?;
1330 Ok(remote.and_then(|remote| Url::parse(&remote).ok()))
1333 pub(crate) fn handle_open_cargo_toml(
1334 snap: GlobalStateSnapshot,
1335 params: lsp_ext::OpenCargoTomlParams,
1336 ) -> Result<Option<lsp_types::GotoDefinitionResponse>> {
1337 let _p = profile::span("handle_open_cargo_toml");
1338 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
1339 let maybe_cargo_spec = CargoTargetSpec::for_file(&snap, file_id)?;
1340 if maybe_cargo_spec.is_none() {
1344 let cargo_spec = maybe_cargo_spec.unwrap();
1345 let cargo_toml_path = cargo_spec.workspace_root.join("Cargo.toml");
1346 if !cargo_toml_path.exists() {
1349 let cargo_toml_url = to_proto::url_from_abs_path(&cargo_toml_path);
1350 let cargo_toml_location = Location::new(cargo_toml_url, Range::default());
1351 let res = lsp_types::GotoDefinitionResponse::from(cargo_toml_location);
1355 fn implementation_title(count: usize) -> String {
1357 "1 implementation".into()
1359 format!("{} implementations", count)
1363 fn reference_title(count: usize) -> String {
1365 "1 reference".into()
1367 format!("{} references", count)
1371 fn show_references_command(
1373 uri: &lsp_types::Url,
1374 position: lsp_types::Position,
1375 locations: Vec<lsp_types::Location>,
1377 // We cannot use the 'editor.action.showReferences' command directly
1378 // because that command requires vscode types which we convert in the handler
1379 // on the client side.
1383 command: "rust-analyzer.showReferences".into(),
1384 arguments: Some(vec![
1385 to_value(uri).unwrap(),
1386 to_value(position).unwrap(),
1387 to_value(locations).unwrap(),
1392 fn run_single_command(runnable: &lsp_ext::Runnable, title: &str) -> Command {
1394 title: title.to_string(),
1395 command: "rust-analyzer.runSingle".into(),
1396 arguments: Some(vec![to_value(runnable).unwrap()]),
1400 fn debug_single_command(runnable: &lsp_ext::Runnable) -> Command {
1402 title: "Debug".into(),
1403 command: "rust-analyzer.debugSingle".into(),
1404 arguments: Some(vec![to_value(runnable).unwrap()]),
1408 fn goto_location_command(snap: &GlobalStateSnapshot, nav: &NavigationTarget) -> Option<Command> {
1409 let value = if snap.config.client_caps.location_link {
1410 let link = to_proto::location_link(snap, None, nav.clone()).ok()?;
1411 to_value(link).ok()?
1413 let range = FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() };
1414 let location = to_proto::location(snap, range).ok()?;
1415 to_value(location).ok()?
1419 title: nav.name.to_string(),
1420 command: "rust-analyzer.gotoLocation".into(),
1421 arguments: Some(vec![value]),
1425 fn to_command_link(command: Command, tooltip: String) -> lsp_ext::CommandLink {
1426 lsp_ext::CommandLink { tooltip: Some(tooltip), command }
1429 fn show_impl_command_link(
1430 snap: &GlobalStateSnapshot,
1431 position: &FilePosition,
1432 ) -> Option<lsp_ext::CommandLinkGroup> {
1433 if snap.config.hover.implementations {
1434 if let Some(nav_data) = snap.analysis.goto_implementation(*position).unwrap_or(None) {
1435 let uri = to_proto::url(snap, position.file_id);
1436 let line_index = snap.analysis.file_line_index(position.file_id).ok()?;
1437 let position = to_proto::position(&line_index, position.offset);
1438 let locations: Vec<_> = nav_data
1441 .filter_map(|nav| to_proto::location_from_nav(snap, nav).ok())
1443 let title = implementation_title(locations.len());
1444 let command = show_references_command(title, &uri, position, locations);
1446 return Some(lsp_ext::CommandLinkGroup {
1447 commands: vec![to_command_link(command, "Go to implementations".into())],
1448 ..Default::default()
1455 fn runnable_action_links(
1456 snap: &GlobalStateSnapshot,
1459 ) -> Option<lsp_ext::CommandLinkGroup> {
1460 let cargo_spec = CargoTargetSpec::for_file(&snap, file_id).ok()?;
1461 if !snap.config.hover.runnable() || should_skip_target(&runnable, cargo_spec.as_ref()) {
1465 let action: &'static _ = runnable.action();
1466 to_proto::runnable(snap, file_id, runnable).ok().map(|r| {
1467 let mut group = lsp_ext::CommandLinkGroup::default();
1469 if snap.config.hover.run {
1470 let run_command = run_single_command(&r, action.run_title);
1471 group.commands.push(to_command_link(run_command, r.label.clone()));
1474 if snap.config.hover.debug {
1475 let dbg_command = debug_single_command(&r);
1476 group.commands.push(to_command_link(dbg_command, r.label));
1483 fn goto_type_action_links(
1484 snap: &GlobalStateSnapshot,
1485 nav_targets: &[HoverGotoTypeData],
1486 ) -> Option<lsp_ext::CommandLinkGroup> {
1487 if !snap.config.hover.goto_type_def || nav_targets.is_empty() {
1491 Some(lsp_ext::CommandLinkGroup {
1492 title: Some("Go to ".into()),
1493 commands: nav_targets
1496 goto_location_command(snap, &it.nav)
1497 .map(|cmd| to_command_link(cmd, it.mod_path.clone()))
1503 fn prepare_hover_actions(
1504 snap: &GlobalStateSnapshot,
1506 actions: &[HoverAction],
1507 ) -> Vec<lsp_ext::CommandLinkGroup> {
1508 if snap.config.hover.none() || !snap.config.client_caps.hover_actions {
1514 .filter_map(|it| match it {
1515 HoverAction::Implementaion(position) => show_impl_command_link(snap, position),
1516 HoverAction::Runnable(r) => runnable_action_links(snap, file_id, r.clone()),
1517 HoverAction::GoToType(targets) => goto_type_action_links(snap, targets),
1522 fn should_skip_target(runnable: &Runnable, cargo_spec: Option<&CargoTargetSpec>) -> bool {
1523 match runnable.kind {
1524 RunnableKind::Bin => {
1525 // Do not suggest binary run on other target than binary
1527 Some(spec) => !matches!(
1529 TargetKind::Bin | TargetKind::Example | TargetKind::Test