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(),
810 kind: Some(CodeActionKind::QUICKFIX),
812 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.code_action_resolve {
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, params.clone(), 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_code_action_resolve(
871 mut snap: GlobalStateSnapshot,
872 mut code_action: lsp_ext::CodeAction,
873 ) -> Result<lsp_ext::CodeAction> {
874 let _p = profile::span("handle_code_action_resolve");
875 let params = match code_action.data.take() {
877 None => Err("can't resolve code action without data")?,
880 let file_id = from_proto::file_id(&snap, ¶ms.code_action_params.text_document.uri)?;
881 let line_index = snap.analysis.file_line_index(file_id)?;
882 let range = from_proto::text_range(&line_index, params.code_action_params.range);
883 let frange = FileRange { file_id, range };
885 snap.config.assist.allowed = params
889 .map(|it| it.into_iter().filter_map(from_proto::assist_kind).collect());
891 let assists = snap.analysis.resolved_assists(&snap.config.assist, frange)?;
892 let (id, index) = split_once(¶ms.id, ':').unwrap();
893 let index = index.parse::<usize>().unwrap();
894 let assist = &assists[index];
895 assert!(assist.assist.id.0 == id);
896 let edit = to_proto::resolved_code_action(&snap, assist.clone())?.edit;
897 code_action.edit = edit;
901 pub(crate) fn handle_code_lens(
902 snap: GlobalStateSnapshot,
903 params: lsp_types::CodeLensParams,
904 ) -> Result<Option<Vec<CodeLens>>> {
905 let _p = profile::span("handle_code_lens");
906 let mut lenses: Vec<CodeLens> = Default::default();
908 if snap.config.lens.none() {
909 // early return before any db query!
910 return Ok(Some(lenses));
913 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
914 let line_index = snap.analysis.file_line_index(file_id)?;
915 let cargo_spec = CargoTargetSpec::for_file(&snap, file_id)?;
917 if snap.config.lens.runnable() {
919 for runnable in snap.analysis.runnables(file_id)? {
920 if should_skip_target(&runnable, cargo_spec.as_ref()) {
924 let action = runnable.action();
925 let range = to_proto::range(&line_index, runnable.nav.full_range);
926 let r = to_proto::runnable(&snap, file_id, runnable)?;
927 if snap.config.lens.run {
928 let lens = CodeLens {
930 command: Some(run_single_command(&r, action.run_title)),
936 if action.debugee && snap.config.lens.debug {
938 CodeLens { range, command: Some(debug_single_command(&r)), data: None };
939 lenses.push(debug_lens);
944 if snap.config.lens.implementations {
948 .file_structure(file_id)?
960 let range = to_proto::range(&line_index, it.node_range);
961 let pos = range.start;
962 let lens_params = lsp_types::request::GotoImplementationParams {
963 text_document_position_params: lsp_types::TextDocumentPositionParams::new(
964 params.text_document.clone(),
967 work_done_progress_params: Default::default(),
968 partial_result_params: Default::default(),
973 data: Some(to_value(CodeLensResolveData::Impls(lens_params)).unwrap()),
979 if snap.config.lens.references() {
980 lenses.extend(snap.analysis.find_all_methods(file_id)?.into_iter().map(|it| {
981 let range = to_proto::range(&line_index, it.range);
982 let position = to_proto::position(&line_index, it.range.start());
984 lsp_types::TextDocumentPositionParams::new(params.text_document.clone(), position);
989 data: Some(to_value(CodeLensResolveData::References(lens_params)).unwrap()),
997 #[derive(Debug, Serialize, Deserialize)]
998 #[serde(rename_all = "camelCase")]
999 enum CodeLensResolveData {
1000 Impls(lsp_types::request::GotoImplementationParams),
1001 References(lsp_types::TextDocumentPositionParams),
1004 pub(crate) fn handle_code_lens_resolve(
1005 snap: GlobalStateSnapshot,
1006 code_lens: CodeLens,
1007 ) -> Result<CodeLens> {
1008 let _p = profile::span("handle_code_lens_resolve");
1009 let data = code_lens.data.unwrap();
1010 let resolve = from_json::<Option<CodeLensResolveData>>("CodeLensResolveData", data)?;
1012 Some(CodeLensResolveData::Impls(lens_params)) => {
1013 let locations: Vec<Location> =
1014 match handle_goto_implementation(snap, lens_params.clone())? {
1015 Some(lsp_types::GotoDefinitionResponse::Scalar(loc)) => vec![loc],
1016 Some(lsp_types::GotoDefinitionResponse::Array(locs)) => locs,
1017 Some(lsp_types::GotoDefinitionResponse::Link(links)) => links
1019 .map(|link| Location::new(link.target_uri, link.target_selection_range))
1024 let title = implementation_title(locations.len());
1025 let cmd = show_references_command(
1027 &lens_params.text_document_position_params.text_document.uri,
1028 code_lens.range.start,
1031 Ok(CodeLens { range: code_lens.range, command: Some(cmd), data: None })
1033 Some(CodeLensResolveData::References(doc_position)) => {
1034 let position = from_proto::file_position(&snap, doc_position.clone())?;
1035 let locations = snap
1037 .find_all_refs(position, None)
1042 .filter_map(|it| to_proto::location(&snap, it.file_range).ok())
1045 .unwrap_or_default();
1047 let title = reference_title(locations.len());
1048 let cmd = if locations.is_empty() {
1049 Command { title, command: "".into(), arguments: None }
1051 show_references_command(
1053 &doc_position.text_document.uri,
1054 code_lens.range.start,
1059 Ok(CodeLens { range: code_lens.range, command: Some(cmd), data: None })
1061 None => Ok(CodeLens {
1062 range: code_lens.range,
1063 command: Some(Command { title: "Error".into(), ..Default::default() }),
1069 pub(crate) fn handle_document_highlight(
1070 snap: GlobalStateSnapshot,
1071 params: lsp_types::DocumentHighlightParams,
1072 ) -> Result<Option<Vec<DocumentHighlight>>> {
1073 let _p = profile::span("handle_document_highlight");
1074 let position = from_proto::file_position(&snap, params.text_document_position_params)?;
1075 let line_index = snap.analysis.file_line_index(position.file_id)?;
1077 let refs = match snap
1079 .find_all_refs(position, Some(SearchScope::single_file(position.file_id)))?
1081 None => return Ok(None),
1087 .filter(|reference| reference.file_range.file_id == position.file_id)
1088 .map(|reference| DocumentHighlight {
1089 range: to_proto::range(&line_index, reference.file_range.range),
1090 kind: reference.access.map(to_proto::document_highlight_kind),
1096 pub(crate) fn handle_ssr(
1097 snap: GlobalStateSnapshot,
1098 params: lsp_ext::SsrParams,
1099 ) -> Result<lsp_types::WorkspaceEdit> {
1100 let _p = profile::span("handle_ssr");
1101 let selections = params
1104 .map(|range| from_proto::file_range(&snap, params.position.text_document.clone(), *range))
1105 .collect::<Result<Vec<_>, _>>()?;
1106 let position = from_proto::file_position(&snap, params.position)?;
1107 let source_change = snap.analysis.structural_search_replace(
1113 to_proto::workspace_edit(&snap, source_change)
1116 pub(crate) fn publish_diagnostics(
1117 snap: &GlobalStateSnapshot,
1119 ) -> Result<Vec<Diagnostic>> {
1120 let _p = profile::span("publish_diagnostics");
1121 let line_index = snap.analysis.file_line_index(file_id)?;
1123 let diagnostics: Vec<Diagnostic> = snap
1125 .diagnostics(&snap.config.diagnostics, file_id)?
1127 .map(|d| Diagnostic {
1128 range: to_proto::range(&line_index, d.range),
1129 severity: Some(to_proto::diagnostic_severity(d.severity)),
1131 code_description: None,
1132 source: Some("rust-analyzer".to_string()),
1134 related_information: None,
1135 tags: if d.unused { Some(vec![DiagnosticTag::Unnecessary]) } else { None },
1142 pub(crate) fn handle_inlay_hints(
1143 snap: GlobalStateSnapshot,
1144 params: InlayHintsParams,
1145 ) -> Result<Vec<InlayHint>> {
1146 let _p = profile::span("handle_inlay_hints");
1147 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
1148 let line_index = snap.analysis.file_line_index(file_id)?;
1151 .inlay_hints(file_id, &snap.config.inlay_hints)?
1153 .map(|it| to_proto::inlay_hint(&line_index, it))
1157 pub(crate) fn handle_call_hierarchy_prepare(
1158 snap: GlobalStateSnapshot,
1159 params: CallHierarchyPrepareParams,
1160 ) -> Result<Option<Vec<CallHierarchyItem>>> {
1161 let _p = profile::span("handle_call_hierarchy_prepare");
1162 let position = from_proto::file_position(&snap, params.text_document_position_params)?;
1164 let nav_info = match snap.analysis.call_hierarchy(position)? {
1165 None => return Ok(None),
1169 let RangeInfo { range: _, info: navs } = nav_info;
1172 .filter(|it| it.kind == SyntaxKind::FN)
1173 .map(|it| to_proto::call_hierarchy_item(&snap, it))
1174 .collect::<Result<Vec<_>>>()?;
1179 pub(crate) fn handle_call_hierarchy_incoming(
1180 snap: GlobalStateSnapshot,
1181 params: CallHierarchyIncomingCallsParams,
1182 ) -> Result<Option<Vec<CallHierarchyIncomingCall>>> {
1183 let _p = profile::span("handle_call_hierarchy_incoming");
1184 let item = params.item;
1186 let doc = TextDocumentIdentifier::new(item.uri);
1187 let frange = from_proto::file_range(&snap, doc, item.selection_range)?;
1188 let fpos = FilePosition { file_id: frange.file_id, offset: frange.range.start() };
1190 let call_items = match snap.analysis.incoming_calls(fpos)? {
1191 None => return Ok(None),
1195 let mut res = vec![];
1197 for call_item in call_items.into_iter() {
1198 let file_id = call_item.target.file_id;
1199 let line_index = snap.analysis.file_line_index(file_id)?;
1200 let item = to_proto::call_hierarchy_item(&snap, call_item.target)?;
1201 res.push(CallHierarchyIncomingCall {
1203 from_ranges: call_item
1206 .map(|it| to_proto::range(&line_index, it))
1214 pub(crate) fn handle_call_hierarchy_outgoing(
1215 snap: GlobalStateSnapshot,
1216 params: CallHierarchyOutgoingCallsParams,
1217 ) -> Result<Option<Vec<CallHierarchyOutgoingCall>>> {
1218 let _p = profile::span("handle_call_hierarchy_outgoing");
1219 let item = params.item;
1221 let doc = TextDocumentIdentifier::new(item.uri);
1222 let frange = from_proto::file_range(&snap, doc, item.selection_range)?;
1223 let fpos = FilePosition { file_id: frange.file_id, offset: frange.range.start() };
1225 let call_items = match snap.analysis.outgoing_calls(fpos)? {
1226 None => return Ok(None),
1230 let mut res = vec![];
1232 for call_item in call_items.into_iter() {
1233 let file_id = call_item.target.file_id;
1234 let line_index = snap.analysis.file_line_index(file_id)?;
1235 let item = to_proto::call_hierarchy_item(&snap, call_item.target)?;
1236 res.push(CallHierarchyOutgoingCall {
1238 from_ranges: call_item
1241 .map(|it| to_proto::range(&line_index, it))
1249 pub(crate) fn handle_semantic_tokens_full(
1250 snap: GlobalStateSnapshot,
1251 params: SemanticTokensParams,
1252 ) -> Result<Option<SemanticTokensResult>> {
1253 let _p = profile::span("handle_semantic_tokens_full");
1255 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
1256 let text = snap.analysis.file_text(file_id)?;
1257 let line_index = snap.analysis.file_line_index(file_id)?;
1259 let highlights = snap.analysis.highlight(file_id)?;
1260 let semantic_tokens = to_proto::semantic_tokens(&text, &line_index, highlights);
1262 // Unconditionally cache the tokens
1263 snap.semantic_tokens_cache.lock().insert(params.text_document.uri, semantic_tokens.clone());
1265 Ok(Some(semantic_tokens.into()))
1268 pub(crate) fn handle_semantic_tokens_full_delta(
1269 snap: GlobalStateSnapshot,
1270 params: SemanticTokensDeltaParams,
1271 ) -> Result<Option<SemanticTokensFullDeltaResult>> {
1272 let _p = profile::span("handle_semantic_tokens_full_delta");
1274 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
1275 let text = snap.analysis.file_text(file_id)?;
1276 let line_index = snap.analysis.file_line_index(file_id)?;
1278 let highlights = snap.analysis.highlight(file_id)?;
1280 let semantic_tokens = to_proto::semantic_tokens(&text, &line_index, highlights);
1282 let mut cache = snap.semantic_tokens_cache.lock();
1283 let cached_tokens = cache.entry(params.text_document.uri).or_default();
1285 if let Some(prev_id) = &cached_tokens.result_id {
1286 if *prev_id == params.previous_result_id {
1287 let delta = to_proto::semantic_token_delta(&cached_tokens, &semantic_tokens);
1288 *cached_tokens = semantic_tokens;
1289 return Ok(Some(delta.into()));
1293 *cached_tokens = semantic_tokens.clone();
1295 Ok(Some(semantic_tokens.into()))
1298 pub(crate) fn handle_semantic_tokens_range(
1299 snap: GlobalStateSnapshot,
1300 params: SemanticTokensRangeParams,
1301 ) -> Result<Option<SemanticTokensRangeResult>> {
1302 let _p = profile::span("handle_semantic_tokens_range");
1304 let frange = from_proto::file_range(&snap, params.text_document, params.range)?;
1305 let text = snap.analysis.file_text(frange.file_id)?;
1306 let line_index = snap.analysis.file_line_index(frange.file_id)?;
1308 let highlights = snap.analysis.highlight_range(frange)?;
1309 let semantic_tokens = to_proto::semantic_tokens(&text, &line_index, highlights);
1310 Ok(Some(semantic_tokens.into()))
1313 pub(crate) fn handle_open_docs(
1314 snap: GlobalStateSnapshot,
1315 params: lsp_types::TextDocumentPositionParams,
1316 ) -> Result<Option<lsp_types::Url>> {
1317 let _p = profile::span("handle_open_docs");
1318 let position = from_proto::file_position(&snap, params)?;
1320 let remote = snap.analysis.external_docs(position)?;
1322 Ok(remote.and_then(|remote| Url::parse(&remote).ok()))
1325 fn implementation_title(count: usize) -> String {
1327 "1 implementation".into()
1329 format!("{} implementations", count)
1333 fn reference_title(count: usize) -> String {
1335 "1 reference".into()
1337 format!("{} references", count)
1341 fn show_references_command(
1343 uri: &lsp_types::Url,
1344 position: lsp_types::Position,
1345 locations: Vec<lsp_types::Location>,
1347 // We cannot use the 'editor.action.showReferences' command directly
1348 // because that command requires vscode types which we convert in the handler
1349 // on the client side.
1353 command: "rust-analyzer.showReferences".into(),
1354 arguments: Some(vec![
1355 to_value(uri).unwrap(),
1356 to_value(position).unwrap(),
1357 to_value(locations).unwrap(),
1362 fn run_single_command(runnable: &lsp_ext::Runnable, title: &str) -> Command {
1364 title: title.to_string(),
1365 command: "rust-analyzer.runSingle".into(),
1366 arguments: Some(vec![to_value(runnable).unwrap()]),
1370 fn debug_single_command(runnable: &lsp_ext::Runnable) -> Command {
1372 title: "Debug".into(),
1373 command: "rust-analyzer.debugSingle".into(),
1374 arguments: Some(vec![to_value(runnable).unwrap()]),
1378 fn goto_location_command(snap: &GlobalStateSnapshot, nav: &NavigationTarget) -> Option<Command> {
1379 let value = if snap.config.client_caps.location_link {
1380 let link = to_proto::location_link(snap, None, nav.clone()).ok()?;
1381 to_value(link).ok()?
1383 let range = FileRange { file_id: nav.file_id, range: nav.focus_or_full_range() };
1384 let location = to_proto::location(snap, range).ok()?;
1385 to_value(location).ok()?
1389 title: nav.name.to_string(),
1390 command: "rust-analyzer.gotoLocation".into(),
1391 arguments: Some(vec![value]),
1395 fn to_command_link(command: Command, tooltip: String) -> lsp_ext::CommandLink {
1396 lsp_ext::CommandLink { tooltip: Some(tooltip), command }
1399 fn show_impl_command_link(
1400 snap: &GlobalStateSnapshot,
1401 position: &FilePosition,
1402 ) -> Option<lsp_ext::CommandLinkGroup> {
1403 if snap.config.hover.implementations {
1404 if let Some(nav_data) = snap.analysis.goto_implementation(*position).unwrap_or(None) {
1405 let uri = to_proto::url(snap, position.file_id);
1406 let line_index = snap.analysis.file_line_index(position.file_id).ok()?;
1407 let position = to_proto::position(&line_index, position.offset);
1408 let locations: Vec<_> = nav_data
1411 .filter_map(|nav| to_proto::location_from_nav(snap, nav).ok())
1413 let title = implementation_title(locations.len());
1414 let command = show_references_command(title, &uri, position, locations);
1416 return Some(lsp_ext::CommandLinkGroup {
1417 commands: vec![to_command_link(command, "Go to implementations".into())],
1418 ..Default::default()
1425 fn runnable_action_links(
1426 snap: &GlobalStateSnapshot,
1429 ) -> Option<lsp_ext::CommandLinkGroup> {
1430 let cargo_spec = CargoTargetSpec::for_file(&snap, file_id).ok()?;
1431 if !snap.config.hover.runnable() || should_skip_target(&runnable, cargo_spec.as_ref()) {
1435 let action: &'static _ = runnable.action();
1436 to_proto::runnable(snap, file_id, runnable).ok().map(|r| {
1437 let mut group = lsp_ext::CommandLinkGroup::default();
1439 if snap.config.hover.run {
1440 let run_command = run_single_command(&r, action.run_title);
1441 group.commands.push(to_command_link(run_command, r.label.clone()));
1444 if snap.config.hover.debug {
1445 let dbg_command = debug_single_command(&r);
1446 group.commands.push(to_command_link(dbg_command, r.label));
1453 fn goto_type_action_links(
1454 snap: &GlobalStateSnapshot,
1455 nav_targets: &[HoverGotoTypeData],
1456 ) -> Option<lsp_ext::CommandLinkGroup> {
1457 if !snap.config.hover.goto_type_def || nav_targets.is_empty() {
1461 Some(lsp_ext::CommandLinkGroup {
1462 title: Some("Go to ".into()),
1463 commands: nav_targets
1466 goto_location_command(snap, &it.nav)
1467 .map(|cmd| to_command_link(cmd, it.mod_path.clone()))
1473 fn prepare_hover_actions(
1474 snap: &GlobalStateSnapshot,
1476 actions: &[HoverAction],
1477 ) -> Vec<lsp_ext::CommandLinkGroup> {
1478 if snap.config.hover.none() || !snap.config.client_caps.hover_actions {
1484 .filter_map(|it| match it {
1485 HoverAction::Implementaion(position) => show_impl_command_link(snap, position),
1486 HoverAction::Runnable(r) => runnable_action_links(snap, file_id, r.clone()),
1487 HoverAction::GoToType(targets) => goto_type_action_links(snap, targets),
1492 fn should_skip_target(runnable: &Runnable, cargo_spec: Option<&CargoTargetSpec>) -> bool {
1493 match runnable.kind {
1494 RunnableKind::Bin => {
1495 // Do not suggest binary run on other target than binary
1497 Some(spec) => !matches!(
1499 TargetKind::Bin | TargetKind::Example | TargetKind::Test