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},
12 AnnotationConfig, AssistKind, AssistResolveStrategy, FileId, FilePosition, FileRange,
13 HoverAction, HoverGotoTypeData, Query, RangeInfo, Runnable, RunnableKind, SingleResolve,
14 SourceChange, TextEdit,
16 use ide_db::SymbolKind;
17 use lsp_server::ErrorCode;
19 CallHierarchyIncomingCall, CallHierarchyIncomingCallsParams, CallHierarchyItem,
20 CallHierarchyOutgoingCall, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams,
21 CodeLens, CompletionItem, Diagnostic, DiagnosticTag, DocumentFormattingParams, FoldingRange,
22 FoldingRangeParams, HoverContents, InlayHint, InlayHintParams, Location, LocationLink,
23 NumberOrString, Position, PrepareRenameResponse, Range, RenameParams,
24 SemanticTokensDeltaParams, SemanticTokensFullDeltaResult, SemanticTokensParams,
25 SemanticTokensRangeParams, SemanticTokensRangeResult, SemanticTokensResult, SymbolInformation,
26 SymbolTag, TextDocumentIdentifier, Url, WorkspaceEdit,
28 use project_model::{ManifestPath, ProjectWorkspace, TargetKind};
30 use stdx::{format_to, never};
31 use syntax::{algo, ast, AstNode, TextRange, TextSize, T};
35 cargo_target_spec::CargoTargetSpec,
36 config::{RustfmtConfig, WorkspaceSymbolConfig},
39 global_state::{GlobalState, GlobalStateSnapshot},
40 line_index::LineEndings,
41 lsp_ext::{self, PositionOrRange, ViewCrateGraphParams, WorkspaceSymbolParams},
42 lsp_utils::{all_edits_are_disjoint, invalid_params_error},
43 to_proto, LspError, Result,
46 pub(crate) fn handle_workspace_reload(state: &mut GlobalState, _: ()) -> Result<()> {
47 state.proc_macro_clients.clear();
48 state.proc_macro_changed = false;
49 state.fetch_workspaces_queue.request_op("reload workspace request".to_string());
50 state.fetch_build_data_queue.request_op("reload workspace request".to_string());
54 pub(crate) fn handle_analyzer_status(
55 snap: GlobalStateSnapshot,
56 params: lsp_ext::AnalyzerStatusParams,
58 let _p = profile::span("handle_analyzer_status");
60 let mut buf = String::new();
62 let mut file_id = None;
63 if let Some(tdi) = params.text_document {
64 match from_proto::file_id(&snap, &tdi.uri) {
65 Ok(it) => file_id = Some(it),
66 Err(_) => format_to!(buf, "file {} not found in vfs", tdi.uri),
70 if snap.workspaces.is_empty() {
71 buf.push_str("No workspaces\n")
73 buf.push_str("Workspaces:\n");
76 "Loaded {:?} packages across {} workspace{}.\n",
77 snap.workspaces.iter().map(|w| w.n_packages()).sum::<usize>(),
78 snap.workspaces.len(),
79 if snap.workspaces.len() == 1 { "" } else { "s" }
82 buf.push_str("\nAnalysis:\n");
87 .unwrap_or_else(|_| "Analysis retrieval was cancelled".to_owned()),
92 pub(crate) fn handle_memory_usage(state: &mut GlobalState, _: ()) -> Result<String> {
93 let _p = profile::span("handle_memory_usage");
94 let mut mem = state.analysis_host.per_query_memory_usage();
95 mem.push(("Remaining".into(), profile::memory_usage().allocated));
97 let mut out = String::new();
98 for (name, bytes) in mem {
99 format_to!(out, "{:>8} {}\n", bytes, name);
104 pub(crate) fn handle_shuffle_crate_graph(state: &mut GlobalState, _: ()) -> Result<()> {
105 state.analysis_host.shuffle_crate_graph();
109 pub(crate) fn handle_syntax_tree(
110 snap: GlobalStateSnapshot,
111 params: lsp_ext::SyntaxTreeParams,
112 ) -> Result<String> {
113 let _p = profile::span("handle_syntax_tree");
114 let id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
115 let line_index = snap.file_line_index(id)?;
116 let text_range = params.range.and_then(|r| from_proto::text_range(&line_index, r).ok());
117 let res = snap.analysis.syntax_tree(id, text_range)?;
121 pub(crate) fn handle_view_hir(
122 snap: GlobalStateSnapshot,
123 params: lsp_types::TextDocumentPositionParams,
124 ) -> Result<String> {
125 let _p = profile::span("handle_view_hir");
126 let position = from_proto::file_position(&snap, params)?;
127 let res = snap.analysis.view_hir(position)?;
131 pub(crate) fn handle_view_file_text(
132 snap: GlobalStateSnapshot,
133 params: lsp_types::TextDocumentIdentifier,
134 ) -> Result<String> {
135 let file_id = from_proto::file_id(&snap, ¶ms.uri)?;
136 Ok(snap.analysis.file_text(file_id)?.to_string())
139 pub(crate) fn handle_view_item_tree(
140 snap: GlobalStateSnapshot,
141 params: lsp_ext::ViewItemTreeParams,
142 ) -> Result<String> {
143 let _p = profile::span("handle_view_item_tree");
144 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
145 let res = snap.analysis.view_item_tree(file_id)?;
149 pub(crate) fn handle_view_crate_graph(
150 snap: GlobalStateSnapshot,
151 params: ViewCrateGraphParams,
152 ) -> Result<String> {
153 let _p = profile::span("handle_view_crate_graph");
154 let dot = snap.analysis.view_crate_graph(params.full)??;
158 pub(crate) fn handle_expand_macro(
159 snap: GlobalStateSnapshot,
160 params: lsp_ext::ExpandMacroParams,
161 ) -> Result<Option<lsp_ext::ExpandedMacro>> {
162 let _p = profile::span("handle_expand_macro");
163 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
164 let line_index = snap.file_line_index(file_id)?;
165 let offset = from_proto::offset(&line_index, params.position)?;
167 let res = snap.analysis.expand_macro(FilePosition { file_id, offset })?;
168 Ok(res.map(|it| lsp_ext::ExpandedMacro { name: it.name, expansion: it.expansion }))
171 pub(crate) fn handle_selection_range(
172 snap: GlobalStateSnapshot,
173 params: lsp_types::SelectionRangeParams,
174 ) -> Result<Option<Vec<lsp_types::SelectionRange>>> {
175 let _p = profile::span("handle_selection_range");
176 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
177 let line_index = snap.file_line_index(file_id)?;
178 let res: Result<Vec<lsp_types::SelectionRange>> = params
182 let offset = from_proto::offset(&line_index, position)?;
183 let mut ranges = Vec::new();
185 let mut range = TextRange::new(offset, offset);
188 let frange = FileRange { file_id, range };
189 let next = snap.analysis.extend_selection(frange)?;
197 let mut range = lsp_types::SelectionRange {
198 range: to_proto::range(&line_index, *ranges.last().unwrap()),
201 for &r in ranges.iter().rev().skip(1) {
202 range = lsp_types::SelectionRange {
203 range: to_proto::range(&line_index, r),
204 parent: Some(Box::new(range)),
214 pub(crate) fn handle_matching_brace(
215 snap: GlobalStateSnapshot,
216 params: lsp_ext::MatchingBraceParams,
217 ) -> Result<Vec<Position>> {
218 let _p = profile::span("handle_matching_brace");
219 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
220 let line_index = snap.file_line_index(file_id)?;
225 let offset = from_proto::offset(&line_index, position);
226 offset.map(|offset| {
227 let offset = match snap.analysis.matching_brace(FilePosition { file_id, offset }) {
228 Ok(Some(matching_brace_offset)) => matching_brace_offset,
229 Err(_) | Ok(None) => offset,
231 to_proto::position(&line_index, offset)
237 pub(crate) fn handle_join_lines(
238 snap: GlobalStateSnapshot,
239 params: lsp_ext::JoinLinesParams,
240 ) -> Result<Vec<lsp_types::TextEdit>> {
241 let _p = profile::span("handle_join_lines");
243 let config = snap.config.join_lines();
244 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
245 let line_index = snap.file_line_index(file_id)?;
247 let mut res = TextEdit::default();
248 for range in params.ranges {
249 let range = from_proto::text_range(&line_index, range)?;
250 let edit = snap.analysis.join_lines(&config, FileRange { file_id, range })?;
251 match res.union(edit) {
254 // just ignore overlapping edits
259 Ok(to_proto::text_edit_vec(&line_index, res))
262 pub(crate) fn handle_on_enter(
263 snap: GlobalStateSnapshot,
264 params: lsp_types::TextDocumentPositionParams,
265 ) -> Result<Option<Vec<lsp_ext::SnippetTextEdit>>> {
266 let _p = profile::span("handle_on_enter");
267 let position = from_proto::file_position(&snap, params)?;
268 let edit = match snap.analysis.on_enter(position)? {
269 None => return Ok(None),
272 let line_index = snap.file_line_index(position.file_id)?;
273 let edit = to_proto::snippet_text_edit_vec(&line_index, true, edit);
277 pub(crate) fn handle_on_type_formatting(
278 snap: GlobalStateSnapshot,
279 params: lsp_types::DocumentOnTypeFormattingParams,
280 ) -> Result<Option<Vec<lsp_ext::SnippetTextEdit>>> {
281 let _p = profile::span("handle_on_type_formatting");
282 let mut position = from_proto::file_position(&snap, params.text_document_position)?;
283 let line_index = snap.file_line_index(position.file_id)?;
285 // in `ide`, the `on_type` invariant is that
286 // `text.char_at(position) == typed_char`.
287 position.offset -= TextSize::of('.');
288 let char_typed = params.ch.chars().next().unwrap_or('\0');
290 let text = snap.analysis.file_text(position.file_id)?;
291 if stdx::never!(!text[usize::from(position.offset)..].starts_with(char_typed)) {
295 // We have an assist that inserts ` ` after typing `->` in `fn foo() ->{`,
296 // but it requires precise cursor positioning to work, and one can't
297 // position the cursor with on_type formatting. So, let's just toggle this
298 // feature off here, hoping that we'll enable it one day, 😿.
299 if char_typed == '>' {
304 snap.analysis.on_char_typed(position, char_typed, snap.config.typing_autoclose_angle())?;
305 let edit = match edit {
307 None => return Ok(None),
310 // This should be a single-file edit
311 let (_, text_edit) = edit.source_file_edits.into_iter().next().unwrap();
313 let change = to_proto::snippet_text_edit_vec(&line_index, edit.is_snippet, text_edit);
317 pub(crate) fn handle_document_symbol(
318 snap: GlobalStateSnapshot,
319 params: lsp_types::DocumentSymbolParams,
320 ) -> Result<Option<lsp_types::DocumentSymbolResponse>> {
321 let _p = profile::span("handle_document_symbol");
322 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
323 let line_index = snap.file_line_index(file_id)?;
325 let mut parents: Vec<(lsp_types::DocumentSymbol, Option<usize>)> = Vec::new();
327 for symbol in snap.analysis.file_structure(file_id)? {
328 let mut tags = Vec::new();
329 if symbol.deprecated {
330 tags.push(SymbolTag::DEPRECATED)
334 let doc_symbol = lsp_types::DocumentSymbol {
336 detail: symbol.detail,
337 kind: to_proto::structure_node_kind(symbol.kind),
339 deprecated: Some(symbol.deprecated),
340 range: to_proto::range(&line_index, symbol.node_range),
341 selection_range: to_proto::range(&line_index, symbol.navigation_range),
344 parents.push((doc_symbol, symbol.parent));
347 // Builds hierarchy from a flat list, in reverse order (so that indices
349 let document_symbols = {
350 let mut acc = Vec::new();
351 while let Some((mut node, parent_idx)) = parents.pop() {
352 if let Some(children) = &mut node.children {
355 let parent = match parent_idx {
357 Some(i) => parents[i].0.children.get_or_insert_with(Vec::new),
365 let res = if snap.config.hierarchical_symbols() {
366 document_symbols.into()
368 let url = to_proto::url(&snap, file_id);
369 let mut symbol_information = Vec::<SymbolInformation>::new();
370 for symbol in document_symbols {
371 flatten_document_symbol(&symbol, None, &url, &mut symbol_information);
373 symbol_information.into()
375 return Ok(Some(res));
377 fn flatten_document_symbol(
378 symbol: &lsp_types::DocumentSymbol,
379 container_name: Option<String>,
381 res: &mut Vec<SymbolInformation>,
383 let mut tags = Vec::new();
386 if let Some(true) = symbol.deprecated {
387 tags.push(SymbolTag::DEPRECATED)
391 res.push(SymbolInformation {
392 name: symbol.name.clone(),
395 deprecated: symbol.deprecated,
396 location: Location::new(url.clone(), symbol.range),
400 for child in symbol.children.iter().flatten() {
401 flatten_document_symbol(child, Some(symbol.name.clone()), url, res);
406 pub(crate) fn handle_workspace_symbol(
407 snap: GlobalStateSnapshot,
408 params: WorkspaceSymbolParams,
409 ) -> Result<Option<Vec<SymbolInformation>>> {
410 let _p = profile::span("handle_workspace_symbol");
412 let config = snap.config.workspace_symbol();
413 let (all_symbols, libs) = decide_search_scope_and_kind(¶ms, &config);
414 let limit = config.search_limit;
417 let query: String = params.query.chars().filter(|&c| c != '#' && c != '*').collect();
418 let mut q = Query::new(query);
428 let mut res = exec_query(&snap, query)?;
429 if res.is_empty() && !all_symbols {
430 let mut query = Query::new(params.query);
432 res = exec_query(&snap, query)?;
435 return Ok(Some(res));
437 fn decide_search_scope_and_kind(
438 params: &WorkspaceSymbolParams,
439 config: &WorkspaceSymbolConfig,
441 // Support old-style parsing of markers in the query.
442 let mut all_symbols = params.query.contains('#');
443 let mut libs = params.query.contains('*');
445 // If no explicit marker was set, check request params. If that's also empty
446 // use global config.
448 let search_kind = match params.search_kind {
449 Some(ref search_kind) => search_kind,
450 None => &config.search_kind,
452 all_symbols = match search_kind {
453 lsp_ext::WorkspaceSymbolSearchKind::OnlyTypes => false,
454 lsp_ext::WorkspaceSymbolSearchKind::AllSymbols => true,
459 let search_scope = match params.search_scope {
460 Some(ref search_scope) => search_scope,
461 None => &config.search_scope,
463 libs = match search_scope {
464 lsp_ext::WorkspaceSymbolSearchScope::Workspace => false,
465 lsp_ext::WorkspaceSymbolSearchScope::WorkspaceAndDependencies => true,
472 fn exec_query(snap: &GlobalStateSnapshot, query: Query) -> Result<Vec<SymbolInformation>> {
473 let mut res = Vec::new();
474 for nav in snap.analysis.symbol_search(query)? {
475 let container_name = nav.container_name.as_ref().map(|v| v.to_string());
478 let info = SymbolInformation {
479 name: nav.name.to_string(),
482 .map(to_proto::symbol_kind)
483 .unwrap_or(lsp_types::SymbolKind::VARIABLE),
485 location: to_proto::location_from_nav(snap, nav)?,
495 pub(crate) fn handle_will_rename_files(
496 snap: GlobalStateSnapshot,
497 params: lsp_types::RenameFilesParams,
498 ) -> Result<Option<lsp_types::WorkspaceEdit>> {
499 let _p = profile::span("handle_will_rename_files");
501 let source_changes: Vec<SourceChange> = params
504 .filter_map(|file_rename| {
505 let from = Url::parse(&file_rename.old_uri).ok()?;
506 let to = Url::parse(&file_rename.new_uri).ok()?;
508 let from_path = from.to_file_path().ok()?;
509 let to_path = to.to_file_path().ok()?;
511 // Limit to single-level moves for now.
512 match (from_path.parent(), to_path.parent()) {
513 (Some(p1), Some(p2)) if p1 == p2 => {
514 if from_path.is_dir() {
515 // add '/' to end of url -- from `file://path/to/folder` to `file://path/to/folder/`
516 let mut old_folder_name = from_path.file_stem()?.to_str()?.to_string();
517 old_folder_name.push('/');
518 let from_with_trailing_slash = from.join(&old_folder_name).ok()?;
520 let imitate_from_url = from_with_trailing_slash.join("mod.rs").ok()?;
521 let new_file_name = to_path.file_name()?.to_str()?;
523 snap.url_to_file_id(&imitate_from_url).ok()?,
524 new_file_name.to_string(),
527 let old_name = from_path.file_stem()?.to_str()?;
528 let new_name = to_path.file_stem()?.to_str()?;
529 match (old_name, new_name) {
532 _ => Some((snap.url_to_file_id(&from).ok()?, new_name.to_string())),
539 .filter_map(|(file_id, new_name)| {
540 snap.analysis.will_rename_file(file_id, &new_name).ok()?
544 // Drop file system edits since we're just renaming things on the same level
545 let mut source_changes = source_changes.into_iter();
546 let mut source_change = source_changes.next().unwrap_or_default();
547 source_change.file_system_edits.clear();
548 // no collect here because we want to merge text edits on same file ids
549 source_change.extend(source_changes.flat_map(|it| it.source_file_edits));
550 if source_change.source_file_edits.is_empty() {
553 to_proto::workspace_edit(&snap, source_change).map(Some)
557 pub(crate) fn handle_goto_definition(
558 snap: GlobalStateSnapshot,
559 params: lsp_types::GotoDefinitionParams,
560 ) -> Result<Option<lsp_types::GotoDefinitionResponse>> {
561 let _p = profile::span("handle_goto_definition");
562 let position = from_proto::file_position(&snap, params.text_document_position_params)?;
563 let nav_info = match snap.analysis.goto_definition(position)? {
564 None => return Ok(None),
567 let src = FileRange { file_id: position.file_id, range: nav_info.range };
568 let res = to_proto::goto_definition_response(&snap, Some(src), nav_info.info)?;
572 pub(crate) fn handle_goto_declaration(
573 snap: GlobalStateSnapshot,
574 params: lsp_types::request::GotoDeclarationParams,
575 ) -> Result<Option<lsp_types::request::GotoDeclarationResponse>> {
576 let _p = profile::span("handle_goto_declaration");
577 let position = from_proto::file_position(&snap, params.text_document_position_params.clone())?;
578 let nav_info = match snap.analysis.goto_declaration(position)? {
579 None => return handle_goto_definition(snap, params),
582 let src = FileRange { file_id: position.file_id, range: nav_info.range };
583 let res = to_proto::goto_definition_response(&snap, Some(src), nav_info.info)?;
587 pub(crate) fn handle_goto_implementation(
588 snap: GlobalStateSnapshot,
589 params: lsp_types::request::GotoImplementationParams,
590 ) -> Result<Option<lsp_types::request::GotoImplementationResponse>> {
591 let _p = profile::span("handle_goto_implementation");
592 let position = from_proto::file_position(&snap, params.text_document_position_params)?;
593 let nav_info = match snap.analysis.goto_implementation(position)? {
594 None => return Ok(None),
597 let src = FileRange { file_id: position.file_id, range: nav_info.range };
598 let res = to_proto::goto_definition_response(&snap, Some(src), nav_info.info)?;
602 pub(crate) fn handle_goto_type_definition(
603 snap: GlobalStateSnapshot,
604 params: lsp_types::request::GotoTypeDefinitionParams,
605 ) -> Result<Option<lsp_types::request::GotoTypeDefinitionResponse>> {
606 let _p = profile::span("handle_goto_type_definition");
607 let position = from_proto::file_position(&snap, params.text_document_position_params)?;
608 let nav_info = match snap.analysis.goto_type_definition(position)? {
609 None => return Ok(None),
612 let src = FileRange { file_id: position.file_id, range: nav_info.range };
613 let res = to_proto::goto_definition_response(&snap, Some(src), nav_info.info)?;
617 pub(crate) fn handle_parent_module(
618 snap: GlobalStateSnapshot,
619 params: lsp_types::TextDocumentPositionParams,
620 ) -> Result<Option<lsp_types::GotoDefinitionResponse>> {
621 let _p = profile::span("handle_parent_module");
622 if let Ok(file_path) = ¶ms.text_document.uri.to_file_path() {
623 if file_path.file_name().unwrap_or_default() == "Cargo.toml" {
624 // search workspaces for parent packages or fallback to workspace root
625 let abs_path_buf = match AbsPathBuf::try_from(file_path.to_path_buf()).ok() {
626 Some(abs_path_buf) => abs_path_buf,
627 None => return Ok(None),
630 let manifest_path = match ManifestPath::try_from(abs_path_buf).ok() {
631 Some(manifest_path) => manifest_path,
632 None => return Ok(None),
635 let links: Vec<LocationLink> = snap
638 .filter_map(|ws| match ws {
639 ProjectWorkspace::Cargo { cargo, .. } => cargo.parent_manifests(&manifest_path),
643 .map(|parent_manifest_path| LocationLink {
644 origin_selection_range: None,
645 target_uri: to_proto::url_from_abs_path(&parent_manifest_path),
646 target_range: Range::default(),
647 target_selection_range: Range::default(),
650 return Ok(Some(links.into()));
653 // check if invoked at the crate root
654 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
655 let crate_id = match snap.analysis.crate_for(file_id)?.first() {
656 Some(&crate_id) => crate_id,
657 None => return Ok(None),
659 let cargo_spec = match CargoTargetSpec::for_file(&snap, file_id)? {
661 None => return Ok(None),
664 if snap.analysis.crate_root(crate_id)? == file_id {
665 let cargo_toml_url = to_proto::url_from_abs_path(&cargo_spec.cargo_toml);
666 let res = vec![LocationLink {
667 origin_selection_range: None,
668 target_uri: cargo_toml_url,
669 target_range: Range::default(),
670 target_selection_range: Range::default(),
673 return Ok(Some(res));
677 // locate parent module by semantics
678 let position = from_proto::file_position(&snap, params)?;
679 let navs = snap.analysis.parent_module(position)?;
680 let res = to_proto::goto_definition_response(&snap, None, navs)?;
684 pub(crate) fn handle_runnables(
685 snap: GlobalStateSnapshot,
686 params: lsp_ext::RunnablesParams,
687 ) -> Result<Vec<lsp_ext::Runnable>> {
688 let _p = profile::span("handle_runnables");
689 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
690 let line_index = snap.file_line_index(file_id)?;
691 let offset = params.position.and_then(|it| from_proto::offset(&line_index, it).ok());
692 let cargo_spec = CargoTargetSpec::for_file(&snap, file_id)?;
694 let expect_test = match offset {
696 let source_file = snap.analysis.parse(file_id)?;
697 algo::find_node_at_offset::<ast::MacroCall>(source_file.syntax(), offset)
698 .and_then(|it| it.path()?.segment()?.name_ref())
699 .map_or(false, |it| it.text() == "expect" || it.text() == "expect_file")
704 let mut res = Vec::new();
705 for runnable in snap.analysis.runnables(file_id)? {
706 if let Some(offset) = offset {
707 if !runnable.nav.full_range.contains_inclusive(offset) {
711 if should_skip_target(&runnable, cargo_spec.as_ref()) {
714 let mut runnable = to_proto::runnable(&snap, runnable)?;
716 runnable.label = format!("{} + expect", runnable.label);
717 runnable.args.expect_test = Some(true);
722 // Add `cargo check` and `cargo test` for all targets of the whole package
723 let config = snap.config.runnables();
726 for cmd in ["check", "test"] {
727 res.push(lsp_ext::Runnable {
728 label: format!("cargo {} -p {} --all-targets", cmd, spec.package),
730 kind: lsp_ext::RunnableKind::Cargo,
731 args: lsp_ext::CargoRunnable {
732 workspace_root: Some(spec.workspace_root.clone().into()),
733 override_cargo: config.override_cargo.clone(),
736 "--package".to_string(),
737 spec.package.clone(),
738 "--all-targets".to_string(),
740 cargo_extra_args: config.cargo_extra_args.clone(),
741 executable_args: Vec::new(),
748 if !snap.config.linked_projects().is_empty()
753 .map(|projects| projects.is_empty())
756 res.push(lsp_ext::Runnable {
757 label: "cargo check --workspace".to_string(),
759 kind: lsp_ext::RunnableKind::Cargo,
760 args: lsp_ext::CargoRunnable {
761 workspace_root: None,
762 override_cargo: config.override_cargo,
763 cargo_args: vec!["check".to_string(), "--workspace".to_string()],
764 cargo_extra_args: config.cargo_extra_args,
765 executable_args: Vec::new(),
775 pub(crate) fn handle_related_tests(
776 snap: GlobalStateSnapshot,
777 params: lsp_types::TextDocumentPositionParams,
778 ) -> Result<Vec<lsp_ext::TestInfo>> {
779 let _p = profile::span("handle_related_tests");
780 let position = from_proto::file_position(&snap, params)?;
782 let tests = snap.analysis.related_tests(position, None)?;
783 let mut res = Vec::new();
785 if let Ok(runnable) = to_proto::runnable(&snap, it) {
786 res.push(lsp_ext::TestInfo { runnable })
793 pub(crate) fn handle_completion(
794 snap: GlobalStateSnapshot,
795 params: lsp_types::CompletionParams,
796 ) -> Result<Option<lsp_types::CompletionResponse>> {
797 let _p = profile::span("handle_completion");
798 let text_document_position = params.text_document_position.clone();
799 let position = from_proto::file_position(&snap, params.text_document_position)?;
800 let completion_trigger_character =
801 params.context.and_then(|ctx| ctx.trigger_character).and_then(|s| s.chars().next());
803 if Some(':') == completion_trigger_character {
804 let source_file = snap.analysis.parse(position.file_id)?;
805 let left_token = source_file.syntax().token_at_offset(position.offset).left_biased();
806 let completion_triggered_after_single_colon = match left_token {
807 Some(left_token) => left_token.kind() == T![:],
810 if completion_triggered_after_single_colon {
815 let completion_config = &snap.config.completion();
816 let items = match snap.analysis.completions(
819 completion_trigger_character,
821 None => return Ok(None),
822 Some(items) => items,
824 let line_index = snap.file_line_index(position.file_id)?;
827 to_proto::completion_items(&snap.config, &line_index, text_document_position, items);
829 let completion_list = lsp_types::CompletionList { is_incomplete: true, items };
830 Ok(Some(completion_list.into()))
833 pub(crate) fn handle_completion_resolve(
834 snap: GlobalStateSnapshot,
835 mut original_completion: CompletionItem,
836 ) -> Result<CompletionItem> {
837 let _p = profile::span("handle_completion_resolve");
839 if !all_edits_are_disjoint(&original_completion, &[]) {
840 return Err(invalid_params_error(
841 "Received a completion with overlapping edits, this is not LSP-compliant".to_string(),
846 let data = match original_completion.data.take() {
848 None => return Ok(original_completion),
851 let resolve_data: lsp_ext::CompletionResolveData = serde_json::from_value(data)?;
853 let file_id = from_proto::file_id(&snap, &resolve_data.position.text_document.uri)?;
854 let line_index = snap.file_line_index(file_id)?;
855 let offset = from_proto::offset(&line_index, resolve_data.position.position)?;
857 let additional_edits = snap
859 .resolve_completion_edits(
860 &snap.config.completion(),
861 FilePosition { file_id, offset },
865 .map(|import| (import.full_import_path, import.imported_name)),
868 .flat_map(|edit| edit.into_iter().map(|indel| to_proto::text_edit(&line_index, indel)))
869 .collect::<Vec<_>>();
871 if !all_edits_are_disjoint(&original_completion, &additional_edits) {
872 return Err(LspError::new(
873 ErrorCode::InternalError as i32,
874 "Import edit overlaps with the original completion edits, this is not LSP-compliant"
880 if let Some(original_additional_edits) = original_completion.additional_text_edits.as_mut() {
881 original_additional_edits.extend(additional_edits.into_iter())
883 original_completion.additional_text_edits = Some(additional_edits);
886 Ok(original_completion)
889 pub(crate) fn handle_folding_range(
890 snap: GlobalStateSnapshot,
891 params: FoldingRangeParams,
892 ) -> Result<Option<Vec<FoldingRange>>> {
893 let _p = profile::span("handle_folding_range");
894 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
895 let folds = snap.analysis.folding_ranges(file_id)?;
896 let text = snap.analysis.file_text(file_id)?;
897 let line_index = snap.file_line_index(file_id)?;
898 let line_folding_only = snap.config.line_folding_only();
901 .map(|it| to_proto::folding_range(&*text, &line_index, line_folding_only, it))
906 pub(crate) fn handle_signature_help(
907 snap: GlobalStateSnapshot,
908 params: lsp_types::SignatureHelpParams,
909 ) -> Result<Option<lsp_types::SignatureHelp>> {
910 let _p = profile::span("handle_signature_help");
911 let position = from_proto::file_position(&snap, params.text_document_position_params)?;
912 let help = match snap.analysis.signature_help(position)? {
914 None => return Ok(None),
916 let config = snap.config.call_info();
917 let res = to_proto::signature_help(help, config, snap.config.signature_help_label_offsets());
921 pub(crate) fn handle_hover(
922 snap: GlobalStateSnapshot,
923 params: lsp_ext::HoverParams,
924 ) -> Result<Option<lsp_ext::Hover>> {
925 let _p = profile::span("handle_hover");
926 let range = match params.position {
927 PositionOrRange::Position(position) => Range::new(position, position),
928 PositionOrRange::Range(range) => range,
931 let file_range = from_proto::file_range(&snap, params.text_document, range)?;
932 let info = match snap.analysis.hover(&snap.config.hover(), file_range)? {
933 None => return Ok(None),
937 let line_index = snap.file_line_index(file_range.file_id)?;
938 let range = to_proto::range(&line_index, info.range);
940 snap.config.hover().documentation.map_or(ide::HoverDocFormat::Markdown, |kind| kind);
941 let hover = lsp_ext::Hover {
942 hover: lsp_types::Hover {
943 contents: HoverContents::Markup(to_proto::markup_content(
949 actions: if snap.config.hover_actions().none() {
952 prepare_hover_actions(&snap, &info.info.actions)
959 pub(crate) fn handle_prepare_rename(
960 snap: GlobalStateSnapshot,
961 params: lsp_types::TextDocumentPositionParams,
962 ) -> Result<Option<PrepareRenameResponse>> {
963 let _p = profile::span("handle_prepare_rename");
964 let position = from_proto::file_position(&snap, params)?;
966 let change = snap.analysis.prepare_rename(position)?.map_err(to_proto::rename_error)?;
968 let line_index = snap.file_line_index(position.file_id)?;
969 let range = to_proto::range(&line_index, change.range);
970 Ok(Some(PrepareRenameResponse::Range(range)))
973 pub(crate) fn handle_rename(
974 snap: GlobalStateSnapshot,
975 params: RenameParams,
976 ) -> Result<Option<WorkspaceEdit>> {
977 let _p = profile::span("handle_rename");
978 let position = from_proto::file_position(&snap, params.text_document_position)?;
981 snap.analysis.rename(position, &*params.new_name)?.map_err(to_proto::rename_error)?;
983 // this is kind of a hack to prevent double edits from happening when moving files
984 // When a module gets renamed by renaming the mod declaration this causes the file to move
985 // which in turn will trigger a WillRenameFiles request to the server for which we reply with a
986 // a second identical set of renames, the client will then apply both edits causing incorrect edits
987 // with this we only emit source_file_edits in the WillRenameFiles response which will do the rename instead
988 // See https://github.com/microsoft/vscode-languageserver-node/issues/752 for more info
989 if !change.file_system_edits.is_empty() && snap.config.will_rename() {
990 change.source_file_edits.clear();
992 let workspace_edit = to_proto::workspace_edit(&snap, change)?;
993 Ok(Some(workspace_edit))
996 pub(crate) fn handle_references(
997 snap: GlobalStateSnapshot,
998 params: lsp_types::ReferenceParams,
999 ) -> Result<Option<Vec<Location>>> {
1000 let _p = profile::span("handle_references");
1001 let position = from_proto::file_position(&snap, params.text_document_position)?;
1003 let refs = match snap.analysis.find_all_refs(position, None)? {
1004 None => return Ok(None),
1008 let include_declaration = params.context.include_declaration;
1009 let locations = refs
1012 let decl = if include_declaration {
1013 refs.declaration.map(|decl| FileRange {
1014 file_id: decl.nav.file_id,
1015 range: decl.nav.focus_or_full_range(),
1022 .flat_map(|(file_id, refs)| {
1023 refs.into_iter().map(move |(range, _)| FileRange { file_id, range })
1027 .filter_map(|frange| to_proto::location(&snap, frange).ok())
1033 pub(crate) fn handle_formatting(
1034 snap: GlobalStateSnapshot,
1035 params: DocumentFormattingParams,
1036 ) -> Result<Option<Vec<lsp_types::TextEdit>>> {
1037 let _p = profile::span("handle_formatting");
1039 run_rustfmt(&snap, params.text_document, None)
1042 pub(crate) fn handle_range_formatting(
1043 snap: GlobalStateSnapshot,
1044 params: lsp_types::DocumentRangeFormattingParams,
1045 ) -> Result<Option<Vec<lsp_types::TextEdit>>> {
1046 let _p = profile::span("handle_range_formatting");
1048 run_rustfmt(&snap, params.text_document, Some(params.range))
1051 pub(crate) fn handle_code_action(
1052 snap: GlobalStateSnapshot,
1053 params: lsp_types::CodeActionParams,
1054 ) -> Result<Option<Vec<lsp_ext::CodeAction>>> {
1055 let _p = profile::span("handle_code_action");
1057 if !snap.config.code_action_literals() {
1058 // We intentionally don't support command-based actions, as those either
1059 // require either custom client-code or server-initiated edits. Server
1060 // initiated edits break causality, so we avoid those.
1065 snap.file_line_index(from_proto::file_id(&snap, ¶ms.text_document.uri)?)?;
1066 let frange = from_proto::file_range(&snap, params.text_document.clone(), params.range)?;
1068 let mut assists_config = snap.config.assist();
1069 assists_config.allowed = params
1073 .map(|it| it.into_iter().filter_map(from_proto::assist_kind).collect());
1075 let mut res: Vec<lsp_ext::CodeAction> = Vec::new();
1077 let code_action_resolve_cap = snap.config.code_action_resolve();
1078 let resolve = if code_action_resolve_cap {
1079 AssistResolveStrategy::None
1081 AssistResolveStrategy::All
1083 let assists = snap.analysis.assists_with_fixes(
1085 &snap.config.diagnostics(),
1089 for (index, assist) in assists.into_iter().enumerate() {
1091 if code_action_resolve_cap { Some((index, params.clone())) } else { None };
1092 let code_action = to_proto::code_action(&snap, assist, resolve_data)?;
1093 res.push(code_action)
1096 // Fixes from `cargo check`.
1097 for fix in snap.check_fixes.get(&frange.file_id).into_iter().flatten() {
1098 // FIXME: this mapping is awkward and shouldn't exist. Refactor
1099 // `snap.check_fixes` to not convert to LSP prematurely.
1100 let intersect_fix_range = fix
1104 .filter_map(|range| from_proto::text_range(&line_index, range).ok())
1105 .any(|fix_range| fix_range.intersect(frange.range).is_some());
1106 if intersect_fix_range {
1107 res.push(fix.action.clone());
1114 pub(crate) fn handle_code_action_resolve(
1115 snap: GlobalStateSnapshot,
1116 mut code_action: lsp_ext::CodeAction,
1117 ) -> Result<lsp_ext::CodeAction> {
1118 let _p = profile::span("handle_code_action_resolve");
1119 let params = match code_action.data.take() {
1121 None => return Err(invalid_params_error("code action without data".to_string()).into()),
1124 let file_id = from_proto::file_id(&snap, ¶ms.code_action_params.text_document.uri)?;
1125 let line_index = snap.file_line_index(file_id)?;
1126 let range = from_proto::text_range(&line_index, params.code_action_params.range)?;
1127 let frange = FileRange { file_id, range };
1129 let mut assists_config = snap.config.assist();
1130 assists_config.allowed = params
1134 .map(|it| it.into_iter().filter_map(from_proto::assist_kind).collect());
1136 let (assist_index, assist_resolve) = match parse_action_id(¶ms.id) {
1137 Ok(parsed_data) => parsed_data,
1139 return Err(invalid_params_error(format!(
1140 "Failed to parse action id string '{}': {}",
1147 let expected_assist_id = assist_resolve.assist_id.clone();
1148 let expected_kind = assist_resolve.assist_kind;
1150 let assists = snap.analysis.assists_with_fixes(
1152 &snap.config.diagnostics(),
1153 AssistResolveStrategy::Single(assist_resolve),
1157 let assist = match assists.get(assist_index) {
1158 Some(assist) => assist,
1159 None => return Err(invalid_params_error(format!(
1160 "Failed to find the assist for index {} provided by the resolve request. Resolve request assist id: {}",
1161 assist_index, params.id,
1165 if assist.id.0 != expected_assist_id || assist.id.1 != expected_kind {
1166 return Err(invalid_params_error(format!(
1167 "Mismatching assist at index {} for the resolve parameters given. Resolve request assist id: {}, actual id: {:?}.",
1168 assist_index, params.id, assist.id
1172 let ca = to_proto::code_action(&snap, assist.clone(), None)?;
1173 code_action.edit = ca.edit;
1174 code_action.command = ca.command;
1178 fn parse_action_id(action_id: &str) -> Result<(usize, SingleResolve), String> {
1179 let id_parts = action_id.split(':').collect::<Vec<_>>();
1180 match id_parts.as_slice() {
1181 [assist_id_string, assist_kind_string, index_string] => {
1182 let assist_kind: AssistKind = assist_kind_string.parse()?;
1183 let index: usize = match index_string.parse() {
1185 Err(e) => return Err(format!("Incorrect index string: {}", e)),
1187 Ok((index, SingleResolve { assist_id: assist_id_string.to_string(), assist_kind }))
1189 _ => Err("Action id contains incorrect number of segments".to_string()),
1193 pub(crate) fn handle_code_lens(
1194 snap: GlobalStateSnapshot,
1195 params: lsp_types::CodeLensParams,
1196 ) -> Result<Option<Vec<CodeLens>>> {
1197 let _p = profile::span("handle_code_lens");
1199 let lens_config = snap.config.lens();
1200 if lens_config.none() {
1201 // early return before any db query!
1202 return Ok(Some(Vec::default()));
1205 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
1206 let cargo_target_spec = CargoTargetSpec::for_file(&snap, file_id)?;
1208 let annotations = snap.analysis.annotations(
1210 binary_target: cargo_target_spec
1214 TargetKind::Bin | TargetKind::Example | TargetKind::Test
1218 annotate_runnables: lens_config.runnable(),
1219 annotate_impls: lens_config.implementations,
1220 annotate_references: lens_config.refs_adt,
1221 annotate_method_references: lens_config.method_refs,
1222 annotate_enum_variant_references: lens_config.enum_variant_refs,
1227 let mut res = Vec::new();
1228 for a in annotations {
1229 to_proto::code_lens(&mut res, &snap, a)?;
1235 pub(crate) fn handle_code_lens_resolve(
1236 snap: GlobalStateSnapshot,
1237 code_lens: CodeLens,
1238 ) -> Result<CodeLens> {
1239 let annotation = from_proto::annotation(&snap, code_lens.clone())?;
1240 let annotation = snap.analysis.resolve_annotation(annotation)?;
1242 let mut acc = Vec::new();
1243 to_proto::code_lens(&mut acc, &snap, annotation)?;
1245 let res = match acc.pop() {
1246 Some(it) if acc.is_empty() => it,
1256 pub(crate) fn handle_document_highlight(
1257 snap: GlobalStateSnapshot,
1258 params: lsp_types::DocumentHighlightParams,
1259 ) -> Result<Option<Vec<lsp_types::DocumentHighlight>>> {
1260 let _p = profile::span("handle_document_highlight");
1261 let position = from_proto::file_position(&snap, params.text_document_position_params)?;
1262 let line_index = snap.file_line_index(position.file_id)?;
1264 let refs = match snap.analysis.highlight_related(snap.config.highlight_related(), position)? {
1265 None => return Ok(None),
1270 .map(|ide::HighlightedRange { range, category }| lsp_types::DocumentHighlight {
1271 range: to_proto::range(&line_index, range),
1272 kind: category.map(to_proto::document_highlight_kind),
1278 pub(crate) fn handle_ssr(
1279 snap: GlobalStateSnapshot,
1280 params: lsp_ext::SsrParams,
1281 ) -> Result<lsp_types::WorkspaceEdit> {
1282 let _p = profile::span("handle_ssr");
1283 let selections = params
1286 .map(|range| from_proto::file_range(&snap, params.position.text_document.clone(), *range))
1287 .collect::<Result<Vec<_>, _>>()?;
1288 let position = from_proto::file_position(&snap, params.position)?;
1289 let source_change = snap.analysis.structural_search_replace(
1295 to_proto::workspace_edit(&snap, source_change)
1298 pub(crate) fn publish_diagnostics(
1299 snap: &GlobalStateSnapshot,
1301 ) -> Result<Vec<Diagnostic>> {
1302 let _p = profile::span("publish_diagnostics");
1303 let line_index = snap.file_line_index(file_id)?;
1305 let diagnostics: Vec<Diagnostic> = snap
1307 .diagnostics(&snap.config.diagnostics(), AssistResolveStrategy::None, file_id)?
1309 .map(|d| Diagnostic {
1310 range: to_proto::range(&line_index, d.range),
1311 severity: Some(to_proto::diagnostic_severity(d.severity)),
1312 code: Some(NumberOrString::String(d.code.as_str().to_string())),
1313 code_description: Some(lsp_types::CodeDescription {
1314 href: lsp_types::Url::parse(&format!(
1315 "https://rust-analyzer.github.io/manual.html#{}",
1320 source: Some("rust-analyzer".to_string()),
1321 // https://github.com/rust-lang/rust-analyzer/issues/11404
1322 message: if !d.message.is_empty() { d.message } else { " ".to_string() },
1323 related_information: None,
1324 tags: if d.unused { Some(vec![DiagnosticTag::UNNECESSARY]) } else { None },
1331 pub(crate) fn handle_inlay_hints(
1332 snap: GlobalStateSnapshot,
1333 params: InlayHintParams,
1334 ) -> Result<Option<Vec<InlayHint>>> {
1335 let _p = profile::span("handle_inlay_hints");
1336 let document_uri = ¶ms.text_document.uri;
1337 let file_id = from_proto::file_id(&snap, document_uri)?;
1338 let line_index = snap.file_line_index(file_id)?;
1339 let range = from_proto::file_range(
1341 TextDocumentIdentifier::new(document_uri.to_owned()),
1344 let inlay_hints_config = snap.config.inlay_hints();
1347 .inlay_hints(&inlay_hints_config, file_id, Some(range))?
1350 to_proto::inlay_hint(&snap, &line_index, inlay_hints_config.render_colons, it)
1356 pub(crate) fn handle_inlay_hints_resolve(
1357 snap: GlobalStateSnapshot,
1358 mut hint: InlayHint,
1359 ) -> Result<InlayHint> {
1360 let _p = profile::span("handle_inlay_hints_resolve");
1361 let data = match hint.data.take() {
1363 None => return Ok(hint),
1366 let resolve_data: lsp_ext::InlayHintResolveData = serde_json::from_value(data)?;
1368 let file_range = from_proto::file_range(
1370 resolve_data.text_document,
1371 match resolve_data.position {
1372 PositionOrRange::Position(pos) => Range::new(pos, pos),
1373 PositionOrRange::Range(range) => range,
1376 let info = match snap.analysis.hover(&snap.config.hover(), file_range)? {
1377 None => return Ok(hint),
1382 snap.config.hover().documentation.map_or(ide::HoverDocFormat::Markdown, |kind| kind);
1384 // FIXME: hover actions?
1385 hint.tooltip = Some(lsp_types::InlayHintTooltip::MarkupContent(to_proto::markup_content(
1392 pub(crate) fn handle_call_hierarchy_prepare(
1393 snap: GlobalStateSnapshot,
1394 params: CallHierarchyPrepareParams,
1395 ) -> Result<Option<Vec<CallHierarchyItem>>> {
1396 let _p = profile::span("handle_call_hierarchy_prepare");
1397 let position = from_proto::file_position(&snap, params.text_document_position_params)?;
1399 let nav_info = match snap.analysis.call_hierarchy(position)? {
1400 None => return Ok(None),
1404 let RangeInfo { range: _, info: navs } = nav_info;
1407 .filter(|it| it.kind == Some(SymbolKind::Function))
1408 .map(|it| to_proto::call_hierarchy_item(&snap, it))
1409 .collect::<Result<Vec<_>>>()?;
1414 pub(crate) fn handle_call_hierarchy_incoming(
1415 snap: GlobalStateSnapshot,
1416 params: CallHierarchyIncomingCallsParams,
1417 ) -> Result<Option<Vec<CallHierarchyIncomingCall>>> {
1418 let _p = profile::span("handle_call_hierarchy_incoming");
1419 let item = params.item;
1421 let doc = TextDocumentIdentifier::new(item.uri);
1422 let frange = from_proto::file_range(&snap, doc, item.selection_range)?;
1423 let fpos = FilePosition { file_id: frange.file_id, offset: frange.range.start() };
1425 let call_items = match snap.analysis.incoming_calls(fpos)? {
1426 None => return Ok(None),
1430 let mut res = vec![];
1432 for call_item in call_items.into_iter() {
1433 let file_id = call_item.target.file_id;
1434 let line_index = snap.file_line_index(file_id)?;
1435 let item = to_proto::call_hierarchy_item(&snap, call_item.target)?;
1436 res.push(CallHierarchyIncomingCall {
1438 from_ranges: call_item
1441 .map(|it| to_proto::range(&line_index, it))
1449 pub(crate) fn handle_call_hierarchy_outgoing(
1450 snap: GlobalStateSnapshot,
1451 params: CallHierarchyOutgoingCallsParams,
1452 ) -> Result<Option<Vec<CallHierarchyOutgoingCall>>> {
1453 let _p = profile::span("handle_call_hierarchy_outgoing");
1454 let item = params.item;
1456 let doc = TextDocumentIdentifier::new(item.uri);
1457 let frange = from_proto::file_range(&snap, doc, item.selection_range)?;
1458 let fpos = FilePosition { file_id: frange.file_id, offset: frange.range.start() };
1460 let call_items = match snap.analysis.outgoing_calls(fpos)? {
1461 None => return Ok(None),
1465 let mut res = vec![];
1467 for call_item in call_items.into_iter() {
1468 let file_id = call_item.target.file_id;
1469 let line_index = snap.file_line_index(file_id)?;
1470 let item = to_proto::call_hierarchy_item(&snap, call_item.target)?;
1471 res.push(CallHierarchyOutgoingCall {
1473 from_ranges: call_item
1476 .map(|it| to_proto::range(&line_index, it))
1484 pub(crate) fn handle_semantic_tokens_full(
1485 snap: GlobalStateSnapshot,
1486 params: SemanticTokensParams,
1487 ) -> Result<Option<SemanticTokensResult>> {
1488 let _p = profile::span("handle_semantic_tokens_full");
1490 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
1491 let text = snap.analysis.file_text(file_id)?;
1492 let line_index = snap.file_line_index(file_id)?;
1494 let highlights = snap.analysis.highlight(file_id)?;
1495 let highlight_strings = snap.config.highlighting_strings();
1496 let semantic_tokens =
1497 to_proto::semantic_tokens(&text, &line_index, highlights, highlight_strings);
1499 // Unconditionally cache the tokens
1500 snap.semantic_tokens_cache.lock().insert(params.text_document.uri, semantic_tokens.clone());
1502 Ok(Some(semantic_tokens.into()))
1505 pub(crate) fn handle_semantic_tokens_full_delta(
1506 snap: GlobalStateSnapshot,
1507 params: SemanticTokensDeltaParams,
1508 ) -> Result<Option<SemanticTokensFullDeltaResult>> {
1509 let _p = profile::span("handle_semantic_tokens_full_delta");
1511 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
1512 let text = snap.analysis.file_text(file_id)?;
1513 let line_index = snap.file_line_index(file_id)?;
1515 let highlights = snap.analysis.highlight(file_id)?;
1516 let highlight_strings = snap.config.highlighting_strings();
1517 let semantic_tokens =
1518 to_proto::semantic_tokens(&text, &line_index, highlights, highlight_strings);
1520 let mut cache = snap.semantic_tokens_cache.lock();
1521 let cached_tokens = cache.entry(params.text_document.uri).or_default();
1523 if let Some(prev_id) = &cached_tokens.result_id {
1524 if *prev_id == params.previous_result_id {
1525 let delta = to_proto::semantic_token_delta(cached_tokens, &semantic_tokens);
1526 *cached_tokens = semantic_tokens;
1527 return Ok(Some(delta.into()));
1531 *cached_tokens = semantic_tokens.clone();
1533 Ok(Some(semantic_tokens.into()))
1536 pub(crate) fn handle_semantic_tokens_range(
1537 snap: GlobalStateSnapshot,
1538 params: SemanticTokensRangeParams,
1539 ) -> Result<Option<SemanticTokensRangeResult>> {
1540 let _p = profile::span("handle_semantic_tokens_range");
1542 let frange = from_proto::file_range(&snap, params.text_document, params.range)?;
1543 let text = snap.analysis.file_text(frange.file_id)?;
1544 let line_index = snap.file_line_index(frange.file_id)?;
1546 let highlights = snap.analysis.highlight_range(frange)?;
1547 let highlight_strings = snap.config.highlighting_strings();
1548 let semantic_tokens =
1549 to_proto::semantic_tokens(&text, &line_index, highlights, highlight_strings);
1550 Ok(Some(semantic_tokens.into()))
1553 pub(crate) fn handle_open_docs(
1554 snap: GlobalStateSnapshot,
1555 params: lsp_types::TextDocumentPositionParams,
1556 ) -> Result<Option<lsp_types::Url>> {
1557 let _p = profile::span("handle_open_docs");
1558 let position = from_proto::file_position(&snap, params)?;
1560 let remote = snap.analysis.external_docs(position)?;
1562 Ok(remote.and_then(|remote| Url::parse(&remote).ok()))
1565 pub(crate) fn handle_open_cargo_toml(
1566 snap: GlobalStateSnapshot,
1567 params: lsp_ext::OpenCargoTomlParams,
1568 ) -> Result<Option<lsp_types::GotoDefinitionResponse>> {
1569 let _p = profile::span("handle_open_cargo_toml");
1570 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
1572 let cargo_spec = match CargoTargetSpec::for_file(&snap, file_id)? {
1574 None => return Ok(None),
1577 let cargo_toml_url = to_proto::url_from_abs_path(&cargo_spec.cargo_toml);
1578 let res: lsp_types::GotoDefinitionResponse =
1579 Location::new(cargo_toml_url, Range::default()).into();
1583 pub(crate) fn handle_move_item(
1584 snap: GlobalStateSnapshot,
1585 params: lsp_ext::MoveItemParams,
1586 ) -> Result<Vec<lsp_ext::SnippetTextEdit>> {
1587 let _p = profile::span("handle_move_item");
1588 let file_id = from_proto::file_id(&snap, ¶ms.text_document.uri)?;
1589 let range = from_proto::file_range(&snap, params.text_document, params.range)?;
1591 let direction = match params.direction {
1592 lsp_ext::MoveItemDirection::Up => ide::Direction::Up,
1593 lsp_ext::MoveItemDirection::Down => ide::Direction::Down,
1596 match snap.analysis.move_item(range, direction)? {
1597 Some(text_edit) => {
1598 let line_index = snap.file_line_index(file_id)?;
1599 Ok(to_proto::snippet_text_edit_vec(&line_index, true, text_edit))
1605 fn to_command_link(command: lsp_types::Command, tooltip: String) -> lsp_ext::CommandLink {
1606 lsp_ext::CommandLink { tooltip: Some(tooltip), command }
1609 fn show_impl_command_link(
1610 snap: &GlobalStateSnapshot,
1611 position: &FilePosition,
1612 ) -> Option<lsp_ext::CommandLinkGroup> {
1613 if snap.config.hover_actions().implementations && snap.config.client_commands().show_reference {
1614 if let Some(nav_data) = snap.analysis.goto_implementation(*position).unwrap_or(None) {
1615 let uri = to_proto::url(snap, position.file_id);
1616 let line_index = snap.file_line_index(position.file_id).ok()?;
1617 let position = to_proto::position(&line_index, position.offset);
1618 let locations: Vec<_> = nav_data
1621 .filter_map(|nav| to_proto::location_from_nav(snap, nav).ok())
1623 let title = to_proto::implementation_title(locations.len());
1624 let command = to_proto::command::show_references(title, &uri, position, locations);
1626 return Some(lsp_ext::CommandLinkGroup {
1627 commands: vec![to_command_link(command, "Go to implementations".into())],
1628 ..Default::default()
1635 fn show_ref_command_link(
1636 snap: &GlobalStateSnapshot,
1637 position: &FilePosition,
1638 ) -> Option<lsp_ext::CommandLinkGroup> {
1639 if snap.config.hover_actions().references && snap.config.client_commands().show_reference {
1640 if let Some(ref_search_res) = snap.analysis.find_all_refs(*position, None).unwrap_or(None) {
1641 let uri = to_proto::url(snap, position.file_id);
1642 let line_index = snap.file_line_index(position.file_id).ok()?;
1643 let position = to_proto::position(&line_index, position.offset);
1644 let locations: Vec<_> = ref_search_res
1646 .flat_map(|res| res.references)
1647 .flat_map(|(file_id, ranges)| {
1648 ranges.into_iter().filter_map(move |(range, _)| {
1649 to_proto::location(snap, FileRange { file_id, range }).ok()
1653 let title = to_proto::reference_title(locations.len());
1654 let command = to_proto::command::show_references(title, &uri, position, locations);
1656 return Some(lsp_ext::CommandLinkGroup {
1657 commands: vec![to_command_link(command, "Go to references".into())],
1658 ..Default::default()
1665 fn runnable_action_links(
1666 snap: &GlobalStateSnapshot,
1668 ) -> Option<lsp_ext::CommandLinkGroup> {
1669 let hover_actions_config = snap.config.hover_actions();
1670 if !hover_actions_config.runnable() {
1674 let cargo_spec = CargoTargetSpec::for_file(snap, runnable.nav.file_id).ok()?;
1675 if should_skip_target(&runnable, cargo_spec.as_ref()) {
1679 let client_commands_config = snap.config.client_commands();
1680 if !(client_commands_config.run_single || client_commands_config.debug_single) {
1684 let title = runnable.title();
1685 let r = to_proto::runnable(snap, runnable).ok()?;
1687 let mut group = lsp_ext::CommandLinkGroup::default();
1689 if hover_actions_config.run && client_commands_config.run_single {
1690 let run_command = to_proto::command::run_single(&r, &title);
1691 group.commands.push(to_command_link(run_command, r.label.clone()));
1694 if hover_actions_config.debug && client_commands_config.debug_single {
1695 let dbg_command = to_proto::command::debug_single(&r);
1696 group.commands.push(to_command_link(dbg_command, r.label));
1702 fn goto_type_action_links(
1703 snap: &GlobalStateSnapshot,
1704 nav_targets: &[HoverGotoTypeData],
1705 ) -> Option<lsp_ext::CommandLinkGroup> {
1706 if !snap.config.hover_actions().goto_type_def
1707 || nav_targets.is_empty()
1708 || !snap.config.client_commands().goto_location
1713 Some(lsp_ext::CommandLinkGroup {
1714 title: Some("Go to ".into()),
1715 commands: nav_targets
1718 to_proto::command::goto_location(snap, &it.nav)
1719 .map(|cmd| to_command_link(cmd, it.mod_path.clone()))
1725 fn prepare_hover_actions(
1726 snap: &GlobalStateSnapshot,
1727 actions: &[HoverAction],
1728 ) -> Vec<lsp_ext::CommandLinkGroup> {
1731 .filter_map(|it| match it {
1732 HoverAction::Implementation(position) => show_impl_command_link(snap, position),
1733 HoverAction::Reference(position) => show_ref_command_link(snap, position),
1734 HoverAction::Runnable(r) => runnable_action_links(snap, r.clone()),
1735 HoverAction::GoToType(targets) => goto_type_action_links(snap, targets),
1740 fn should_skip_target(runnable: &Runnable, cargo_spec: Option<&CargoTargetSpec>) -> bool {
1741 match runnable.kind {
1742 RunnableKind::Bin => {
1743 // Do not suggest binary run on other target than binary
1745 Some(spec) => !matches!(
1747 TargetKind::Bin | TargetKind::Example | TargetKind::Test
1757 snap: &GlobalStateSnapshot,
1758 text_document: TextDocumentIdentifier,
1759 range: Option<lsp_types::Range>,
1760 ) -> Result<Option<Vec<lsp_types::TextEdit>>> {
1761 let file_id = from_proto::file_id(snap, &text_document.uri)?;
1762 let file = snap.analysis.file_text(file_id)?;
1763 let crate_ids = snap.analysis.crate_for(file_id)?;
1765 let line_index = snap.file_line_index(file_id)?;
1767 let mut rustfmt = match snap.config.rustfmt() {
1768 RustfmtConfig::Rustfmt { extra_args, enable_range_formatting } => {
1769 let mut cmd = process::Command::new(toolchain::rustfmt());
1770 cmd.args(extra_args);
1771 // try to chdir to the file so we can respect `rustfmt.toml`
1772 // FIXME: use `rustfmt --config-path` once
1773 // https://github.com/rust-lang/rustfmt/issues/4660 gets fixed
1774 match text_document.uri.to_file_path() {
1776 // pop off file name
1777 if path.pop() && path.is_dir() {
1778 cmd.current_dir(path);
1783 "Unable to get file path for {}, rustfmt.toml might be ignored",
1788 if let Some(&crate_id) = crate_ids.first() {
1789 // Assume all crates are in the same edition
1790 let edition = snap.analysis.crate_edition(crate_id)?;
1791 cmd.arg("--edition");
1792 cmd.arg(edition.to_string());
1795 if let Some(range) = range {
1796 if !enable_range_formatting {
1797 return Err(LspError::new(
1798 ErrorCode::InvalidRequest as i32,
1800 "rustfmt range formatting is unstable. \
1801 Opt-in by using a nightly build of rustfmt and setting \
1802 `rustfmt.rangeFormatting.enable` to true in your LSP configuration",
1808 let frange = from_proto::file_range(snap, text_document, range)?;
1809 let start_line = line_index.index.line_col(frange.range.start()).line;
1810 let end_line = line_index.index.line_col(frange.range.end()).line;
1812 cmd.arg("--unstable-features");
1813 cmd.arg("--file-lines");
1817 "range": [start_line, end_line]
1825 RustfmtConfig::CustomCommand { command, args } => {
1826 let mut cmd = process::Command::new(command);
1832 let mut rustfmt = rustfmt
1833 .stdin(Stdio::piped())
1834 .stdout(Stdio::piped())
1835 .stderr(Stdio::piped())
1837 .context(format!("Failed to spawn {:?}", rustfmt))?;
1839 rustfmt.stdin.as_mut().unwrap().write_all(file.as_bytes())?;
1841 let output = rustfmt.wait_with_output()?;
1842 let captured_stdout = String::from_utf8(output.stdout)?;
1843 let captured_stderr = String::from_utf8(output.stderr).unwrap_or_default();
1845 if !output.status.success() {
1846 let rustfmt_not_installed =
1847 captured_stderr.contains("not installed") || captured_stderr.contains("not available");
1849 return match output.status.code() {
1850 Some(1) if !rustfmt_not_installed => {
1851 // While `rustfmt` doesn't have a specific exit code for parse errors this is the
1852 // likely cause exiting with 1. Most Language Servers swallow parse errors on
1853 // formatting because otherwise an error is surfaced to the user on top of the
1854 // syntax error diagnostics they're already receiving. This is especially jarring
1855 // if they have format on save enabled.
1856 tracing::info!("rustfmt exited with status 1, assuming parse error and ignoring");
1860 // Something else happened - e.g. `rustfmt` is missing or caught a signal
1864 r#"rustfmt exited with:
1868 output.status, captured_stdout, captured_stderr,
1876 let (new_text, new_line_endings) = LineEndings::normalize(captured_stdout);
1878 if line_index.endings != new_line_endings {
1879 // If line endings are different, send the entire file.
1880 // Diffing would not work here, as the line endings might be the only
1882 Ok(Some(to_proto::text_edit_vec(
1884 TextEdit::replace(TextRange::up_to(TextSize::of(&*file)), new_text),
1886 } else if *file == new_text {
1887 // The document is already formatted correctly -- no edits needed.
1890 Ok(Some(to_proto::text_edit_vec(&line_index, diff(&file, &new_text))))