1use std::{fs, io::Write as _, ops::Not, process::Stdio};
5
6use anyhow::Context;
7
8use base64::{Engine, prelude::BASE64_STANDARD};
9use ide::{
10 AssistKind, AssistResolveStrategy, Cancellable, CompletionFieldsToResolve,
11 CompletionItemImport, FilePosition, FileRange, FileStructureConfig, FindAllRefsConfig,
12 HoverAction, HoverGotoTypeData, InlayFieldsToResolve, Query, RangeInfo, Runnable, RunnableKind,
13 SingleResolve, SourceChange, TextEdit,
14};
15use ide_db::{FxHashMap, SymbolKind, base_db::TargetKind};
16use itertools::Itertools;
17use lsp_server::ErrorCode;
18use lsp_types::{
19 CallHierarchyIncomingCall, CallHierarchyIncomingCallsParams, CallHierarchyItem,
20 CallHierarchyOutgoingCall, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams,
21 CodeLens, CompletionItem, Contents, DocumentChange, FoldingRange, FoldingRangeParams,
22 InlayHint, InlayHintParams, Location, LocationLink, Position, PrepareRenameResult, Range,
23 RenameParams, ResourceOperationKind, SemanticTokens, SemanticTokensDeltaParams,
24 SemanticTokensDeltaResponse, SemanticTokensParams, SemanticTokensRangeParams,
25 SymbolInformation, SymbolTag, TextDocumentIdentifier, Uri, WorkspaceEdit,
26};
27use paths::Utf8PathBuf;
28use project_model::{CargoWorkspace, ManifestPath, ProjectWorkspaceKind};
29use serde_json::json;
30use stdx::{format_to, never};
31use syntax::{TextRange, TextSize};
32use triomphe::Arc;
33use vfs::{AbsPath, AbsPathBuf, FileId, LineEndings, VfsPath};
34
35use crate::{
36 config::{
37 ClientCommandsConfig, Config, HoverActionsConfig, RustfmtConfig, WorkspaceSymbolConfig,
38 },
39 diagnostics::convert_diagnostic,
40 global_state::{FetchWorkspaceRequest, GlobalState, GlobalStateSnapshot},
41 lsp::{
42 LspError, completion_item_hash,
43 ext::{
44 GetFailedObligationsParams, InternalTestingFetchConfigOption,
45 InternalTestingFetchConfigParams, InternalTestingFetchConfigResponse,
46 },
47 from_proto, to_proto,
48 utils::{all_edits_are_disjoint, invalid_params_error},
49 },
50 lsp_ext::{
51 self, CrateInfoResult, ExternalDocsPair, ExternalDocsResponse, FetchDependencyListParams,
52 FetchDependencyListResult, PositionOrRange, ViewCrateGraphParams, WorkspaceSymbolParams,
53 },
54 target_spec::{CargoTargetSpec, TargetSpec},
55 test_runner::{CargoTestHandle, TestTarget},
56 try_default,
57};
58
59pub(crate) fn handle_workspace_reload(state: &mut GlobalState, _: ()) -> anyhow::Result<()> {
60 state.proc_macro_clients = Arc::from_iter([]);
61 state.build_deps_changed = false;
62
63 let req = FetchWorkspaceRequest { path: None, force_crate_graph_reload: false };
64 state.fetch_workspaces_queue.request_op("reload workspace request".to_owned(), req);
65 Ok(())
66}
67
68pub(crate) fn handle_proc_macros_rebuild(state: &mut GlobalState, _: ()) -> anyhow::Result<()> {
69 state.proc_macro_clients = Arc::from_iter([]);
70 state.build_deps_changed = false;
71
72 state.fetch_build_data_queue.request_op("rebuild proc macros request".to_owned(), ());
73 Ok(())
74}
75
76pub(crate) fn handle_analyzer_status(
77 snap: GlobalStateSnapshot,
78 params: lsp_ext::AnalyzerStatusParams,
79) -> anyhow::Result<String> {
80 let _p = tracing::info_span!("handle_analyzer_status").entered();
81
82 let mut buf = String::new();
83
84 let mut file_id = None;
85 if let Some(tdi) = params.text_document {
86 match from_proto::file_id(&snap, &tdi.uri) {
87 Ok(Some(it)) => file_id = Some(it),
88 Ok(None) => {}
89 Err(_) => format_to!(buf, "file {} not found in vfs", tdi.uri),
90 }
91 }
92
93 if snap.workspaces.is_empty() {
94 buf.push_str("No workspaces\n")
95 } else {
96 buf.push_str("Workspaces:\n");
97 format_to!(
98 buf,
99 "Loaded {:?} packages across {} workspace{}.\n",
100 snap.workspaces.iter().map(|w| w.n_packages()).sum::<usize>(),
101 snap.workspaces.len(),
102 if snap.workspaces.len() == 1 { "" } else { "s" }
103 );
104
105 format_to!(
106 buf,
107 "Workspace root folders: {:?}",
108 snap.workspaces.iter().map(|ws| ws.manifest_or_root()).collect::<Vec<&AbsPath>>()
109 );
110 }
111 buf.push_str("\nAnalysis:\n");
112 buf.push_str(
113 &snap
114 .analysis
115 .status(file_id)
116 .unwrap_or_else(|_| "Analysis retrieval was cancelled".to_owned()),
117 );
118
119 buf.push_str("\nVersion: \n");
120 format_to!(buf, "{}", crate::version());
121
122 buf.push_str("\nConfiguration: \n");
123 format_to!(buf, "{:#?}", snap.config);
124
125 Ok(buf)
126}
127
128pub(crate) fn handle_memory_usage(_state: &mut GlobalState, _: ()) -> anyhow::Result<String> {
129 let _p = tracing::info_span!("handle_memory_usage").entered();
130
131 #[cfg(not(feature = "dhat"))]
132 {
133 Err(anyhow::anyhow!(
134 "Memory profiling is not enabled for this build of rust-analyzer.\n\n\
135 To build rust-analyzer with profiling support, pass `--features dhat --profile dev-rel` to `cargo build`
136 when building from source, or pass `--enable-profiling` to `cargo xtask`."
137 ))
138 }
139 #[cfg(feature = "dhat")]
140 {
141 if let Some(dhat_output_file) = _state.config.dhat_output_file() {
142 let mut profiler = crate::DHAT_PROFILER.lock().unwrap();
143 let old_profiler = profiler.take();
144 drop(old_profiler);
146 *profiler = Some(dhat::Profiler::builder().file_name(&dhat_output_file).build());
147 Ok(format!(
148 "Memory profile was saved successfully to {dhat_output_file}.\n\n\
149 See https://docs.rs/dhat/latest/dhat/#viewing for how to inspect the profile."
150 ))
151 } else {
152 Err(anyhow::anyhow!(
153 "Please set `rust-analyzer.profiling.memoryProfile` to the path where you want to save the profile."
154 ))
155 }
156 }
157}
158
159pub(crate) fn handle_view_syntax_tree(
160 snap: GlobalStateSnapshot,
161 params: lsp_ext::ViewSyntaxTreeParams,
162) -> anyhow::Result<String> {
163 let _p = tracing::info_span!("handle_view_syntax_tree").entered();
164 let id = try_default!(from_proto::file_id(&snap, ¶ms.text_document.uri)?);
165 let res = snap.analysis.view_syntax_tree(id)?;
166 Ok(res)
167}
168
169pub(crate) fn handle_view_hir(
170 snap: GlobalStateSnapshot,
171 params: lsp_types::TextDocumentPositionParams,
172) -> anyhow::Result<String> {
173 let _p = tracing::info_span!("handle_view_hir").entered();
174 let position = try_default!(from_proto::file_position(&snap, ¶ms)?);
175 let res = snap.analysis.view_hir(position)?;
176 Ok(res)
177}
178
179pub(crate) fn handle_view_mir(
180 snap: GlobalStateSnapshot,
181 params: lsp_types::TextDocumentPositionParams,
182) -> anyhow::Result<String> {
183 let _p = tracing::info_span!("handle_view_mir").entered();
184 let position = try_default!(from_proto::file_position(&snap, ¶ms)?);
185 let res = snap.analysis.view_mir(position)?;
186 Ok(res)
187}
188
189pub(crate) fn handle_interpret_function(
190 snap: GlobalStateSnapshot,
191 params: lsp_types::TextDocumentPositionParams,
192) -> anyhow::Result<String> {
193 let _p = tracing::info_span!("handle_interpret_function").entered();
194 let position = try_default!(from_proto::file_position(&snap, ¶ms)?);
195 let res = snap.analysis.interpret_function(position)?;
196 Ok(res)
197}
198
199pub(crate) fn handle_view_file_text(
200 snap: GlobalStateSnapshot,
201 params: lsp_types::TextDocumentIdentifier,
202) -> anyhow::Result<String> {
203 let file_id = try_default!(from_proto::file_id(&snap, ¶ms.uri)?);
204 Ok(snap.analysis.file_text(file_id)?.to_string())
205}
206
207pub(crate) fn handle_view_item_tree(
208 snap: GlobalStateSnapshot,
209 params: lsp_ext::ViewItemTreeParams,
210) -> anyhow::Result<String> {
211 let _p = tracing::info_span!("handle_view_item_tree").entered();
212 let file_id = try_default!(from_proto::file_id(&snap, ¶ms.text_document.uri)?);
213 let res = snap.analysis.view_item_tree(file_id)?;
214 Ok(res)
215}
216
217fn all_test_targets(cargo: &CargoWorkspace) -> impl Iterator<Item = TestTarget> {
228 cargo.packages().filter(|p| cargo[*p].is_member).flat_map(|p| {
229 let package = &cargo[p];
230 package.targets.iter().filter_map(|t| {
231 let target = &cargo[*t];
232 if target.kind == TargetKind::BuildScript {
233 None
234 } else {
235 Some(TestTarget {
236 package: package.name.clone(),
237 target: target.name.clone(),
238 kind: target.kind,
239 })
240 }
241 })
242 })
243}
244
245fn find_test_target(namespace_root: &str, cargo: &CargoWorkspace) -> Option<TestTarget> {
246 all_test_targets(cargo).find(|t| namespace_root == t.target.replace('-', "_"))
247}
248
249pub(crate) fn handle_run_test(
250 state: &mut GlobalState,
251 params: lsp_ext::RunTestParams,
252) -> anyhow::Result<()> {
253 if let Some(_session) = state.test_run_session.take() {
254 state.send_notification::<lsp_ext::EndRunTestNotification>(());
255 }
256
257 let mut handles = vec![];
258 for ws in &*state.workspaces {
259 if let ProjectWorkspaceKind::Cargo { cargo, .. } = &ws.kind {
260 let tests = match params.include {
262 Some(ref include) => include
263 .iter()
264 .unique()
265 .filter_map(|test| {
266 let (root, remainder) = match test.split_once("::") {
267 Some((root, remainder)) => (root.to_owned(), Some(remainder)),
268 None => (test.clone(), None),
269 };
270 if let Some(target) = find_test_target(&root, cargo) {
271 Some((target, remainder))
272 } else {
273 tracing::error!("Test target not found for: {test}");
274 None
275 }
276 })
277 .collect_vec(),
278 None => all_test_targets(cargo).map(|target| (target, None)).collect(),
279 };
280
281 for (target, path) in tests {
282 let handle = CargoTestHandle::new(
283 path,
284 state.config.cargo_test_options(None),
285 cargo.workspace_root(),
286 Some(cargo.target_directory().as_ref()),
287 target,
288 state.test_run_sender.clone(),
289 ws.toolchain.as_ref(),
290 )?;
291 handles.push(handle);
292 }
293 }
294 }
295 state.test_run_remaining_jobs = 2 * handles.len();
297 state.test_run_session = Some(handles);
298 Ok(())
299}
300
301pub(crate) fn handle_discover_test(
302 snap: GlobalStateSnapshot,
303 params: lsp_ext::DiscoverTestParams,
304) -> anyhow::Result<lsp_ext::DiscoverTestResults> {
305 let _p = tracing::info_span!("handle_discover_test").entered();
306 let (tests, scope) = match params.test_id {
307 Some(id) => {
308 let crate_id = id.split_once("::").map(|it| it.0).unwrap_or(&id);
309 (
310 snap.analysis.discover_tests_in_crate_by_test_id(crate_id)?,
311 Some(vec![crate_id.to_owned()]),
312 )
313 }
314 None => (snap.analysis.discover_test_roots()?, None),
315 };
316
317 Ok(lsp_ext::DiscoverTestResults {
318 tests: tests
319 .into_iter()
320 .filter_map(|t| {
321 let line_index = t.file.and_then(|f| snap.file_line_index(f).ok());
322 to_proto::test_item(&snap, t, line_index.as_ref())
323 })
324 .collect(),
325 scope,
326 scope_file: None,
327 })
328}
329
330pub(crate) fn handle_view_crate_graph(
331 snap: GlobalStateSnapshot,
332 params: ViewCrateGraphParams,
333) -> anyhow::Result<String> {
334 let _p = tracing::info_span!("handle_view_crate_graph").entered();
335 let dot = snap.analysis.view_crate_graph(params.full)?;
336 Ok(dot)
337}
338
339pub(crate) fn handle_expand_macro(
340 snap: GlobalStateSnapshot,
341 params: lsp_ext::ExpandMacroParams,
342) -> anyhow::Result<Option<lsp_ext::ExpandedMacro>> {
343 let _p = tracing::info_span!("handle_expand_macro").entered();
344 let file_id = try_default!(from_proto::file_id(&snap, ¶ms.text_document.uri)?);
345 let line_index = snap.file_line_index(file_id)?;
346 let offset = from_proto::offset(&line_index, params.position)?;
347
348 let res = snap.analysis.expand_macro(FilePosition { file_id, offset })?;
349 Ok(res.map(|it| lsp_ext::ExpandedMacro { name: it.name, expansion: it.expansion }))
350}
351
352pub(crate) fn handle_selection_range(
353 snap: GlobalStateSnapshot,
354 params: lsp_types::SelectionRangeParams,
355) -> anyhow::Result<Option<Vec<lsp_types::SelectionRange>>> {
356 let _p = tracing::info_span!("handle_selection_range").entered();
357 let file_id = try_default!(from_proto::file_id(&snap, ¶ms.text_document.uri)?);
358 let line_index = snap.file_line_index(file_id)?;
359 let res: anyhow::Result<Vec<lsp_types::SelectionRange>> = params
360 .positions
361 .iter()
362 .map(|position| {
363 let offset = from_proto::offset(&line_index, *position)?;
364 let mut ranges = Vec::new();
365 {
366 let mut range = TextRange::new(offset, offset);
367 loop {
368 ranges.push(range);
369 let frange = FileRange { file_id, range };
370 let next = snap.analysis.extend_selection(frange)?;
371 if next == range {
372 break;
373 } else {
374 range = next
375 }
376 }
377 }
378 let mut range = lsp_types::SelectionRange {
379 range: to_proto::range(&line_index, *ranges.last().unwrap()),
380 parent: None,
381 };
382 for &r in ranges.iter().rev().skip(1) {
383 range = lsp_types::SelectionRange {
384 range: to_proto::range(&line_index, r),
385 parent: Some(Box::new(range)),
386 }
387 }
388 Ok(range)
389 })
390 .collect();
391
392 Ok(Some(res?))
393}
394
395pub(crate) fn handle_matching_brace(
396 snap: GlobalStateSnapshot,
397 params: lsp_ext::MatchingBraceParams,
398) -> anyhow::Result<Vec<Position>> {
399 let _p = tracing::info_span!("handle_matching_brace").entered();
400 let file_id = try_default!(from_proto::file_id(&snap, ¶ms.text_document.uri)?);
401 let line_index = snap.file_line_index(file_id)?;
402 params
403 .positions
404 .iter()
405 .map(|position| {
406 let offset = from_proto::offset(&line_index, *position);
407 offset.map(|offset| {
408 let offset = match snap.analysis.matching_brace(FilePosition { file_id, offset }) {
409 Ok(Some(matching_brace_offset)) => matching_brace_offset,
410 Err(_) | Ok(None) => offset,
411 };
412 to_proto::position(&line_index, offset)
413 })
414 })
415 .collect()
416}
417
418pub(crate) fn handle_join_lines(
419 snap: GlobalStateSnapshot,
420 params: lsp_ext::JoinLinesParams,
421) -> anyhow::Result<Vec<lsp_types::TextEdit>> {
422 let _p = tracing::info_span!("handle_join_lines").entered();
423
424 let file_id = try_default!(from_proto::file_id(&snap, ¶ms.text_document.uri)?);
425 let config = snap.config.join_lines();
426 let line_index = snap.file_line_index(file_id)?;
427
428 let mut res = TextEdit::default();
429 for range in params.ranges {
430 let range = from_proto::text_range(&line_index, range)?;
431 let edit = snap.analysis.join_lines(&config, FileRange { file_id, range })?;
432 match res.union(edit) {
433 Ok(()) => (),
434 Err(_edit) => {
435 }
437 }
438 }
439
440 Ok(to_proto::text_edit_vec(&line_index, res))
441}
442
443pub(crate) fn handle_on_enter(
444 snap: GlobalStateSnapshot,
445 params: lsp_types::TextDocumentPositionParams,
446) -> anyhow::Result<Option<Vec<lsp_ext::SnippetTextEdit>>> {
447 let _p = tracing::info_span!("handle_on_enter").entered();
448 let position = try_default!(from_proto::file_position(&snap, ¶ms)?);
449 let edit = match snap.analysis.on_enter(position)? {
450 None => return Ok(None),
451 Some(it) => it,
452 };
453 let line_index = snap.file_line_index(position.file_id)?;
454 let edit = to_proto::snippet_text_edit_vec(
455 &line_index,
456 true,
457 edit,
458 snap.config.change_annotation_support(),
459 );
460 Ok(Some(edit))
461}
462
463pub(crate) fn handle_on_type_formatting(
464 snap: GlobalStateSnapshot,
465 params: lsp_types::DocumentOnTypeFormattingParams,
466) -> anyhow::Result<Option<Vec<lsp_ext::SnippetTextEdit>>> {
467 let _p = tracing::info_span!("handle_on_type_formatting").entered();
468 let char_typed = params.ch.chars().next().unwrap_or('\0');
469 if !snap.config.typing_trigger_chars().contains(char_typed) {
470 return Ok(None);
471 }
472 let tdpp = lsp_types::TextDocumentPositionParams {
473 text_document: params.text_document,
474 position: params.position,
475 };
476 let mut position = try_default!(from_proto::file_position(&snap, &tdpp)?);
477 let line_index = snap.file_line_index(position.file_id)?;
478
479 position.offset -= TextSize::of('.');
482
483 let text = snap.analysis.file_text(position.file_id)?;
484 if stdx::never!(!text[usize::from(position.offset)..].starts_with(char_typed)) {
485 return Ok(None);
486 }
487
488 let edit = snap.analysis.on_char_typed(position, char_typed)?;
489 let edit = match edit {
490 Some(it) => it,
491 None => return Ok(None),
492 };
493
494 let (_, (text_edit, snippet_edit)) = edit.source_file_edits.into_iter().next().unwrap();
496 stdx::always!(snippet_edit.is_none(), "on type formatting shouldn't use structured snippets");
497
498 let change = to_proto::snippet_text_edit_vec(
499 &line_index,
500 edit.is_snippet,
501 text_edit,
502 snap.config.change_annotation_support(),
503 );
504 Ok(Some(change))
505}
506
507pub(crate) fn empty_diagnostic_report() -> lsp_types::DocumentDiagnosticReport {
508 lsp_types::DocumentDiagnosticReport::RelatedFullDocumentDiagnosticReport(
509 lsp_types::RelatedFullDocumentDiagnosticReport {
510 related_documents: None,
511 full_document_diagnostic_report: lsp_types::FullDocumentDiagnosticReport {
512 result_id: Some("rust-analyzer".to_owned()),
513 items: vec![],
514 },
515 },
516 )
517}
518
519pub(crate) fn handle_document_diagnostics(
520 snap: GlobalStateSnapshot,
521 params: lsp_types::DocumentDiagnosticParams,
522) -> anyhow::Result<lsp_types::DocumentDiagnosticReport> {
523 let file_id = match from_proto::file_id(&snap, ¶ms.text_document.uri)? {
524 Some(it) => it,
525 None => return Ok(empty_diagnostic_report()),
526 };
527 let source_root = snap.analysis.source_root_id(file_id)?;
528 if !snap.analysis.is_local_source_root(source_root)? {
529 return Ok(empty_diagnostic_report());
530 }
531 let source_root = snap.analysis.source_root_id(file_id)?;
532 let config = snap.config.diagnostics(Some(source_root));
533 if !config.enabled {
534 return Ok(empty_diagnostic_report());
535 }
536 let line_index = snap.file_line_index(file_id)?;
537 let supports_related = snap.config.text_document_diagnostic_related_document_support();
538
539 let mut related_documents = FxHashMap::default();
540 let diagnostics = snap
541 .analysis
542 .full_diagnostics(&config, AssistResolveStrategy::None, file_id)?
543 .into_iter()
544 .filter_map(|d| {
545 let file = d.range.file_id;
546 if file == file_id {
547 let diagnostic = convert_diagnostic(&line_index, d);
548 return Some(diagnostic);
549 }
550 if supports_related {
551 let (diagnostics, line_index) = related_documents
552 .entry(file)
553 .or_insert_with(|| (Vec::new(), snap.file_line_index(file).ok()));
554 let diagnostic = convert_diagnostic(line_index.as_mut()?, d);
555 diagnostics.push(diagnostic);
556 }
557 None
558 });
559 Ok(lsp_types::DocumentDiagnosticReport::RelatedFullDocumentDiagnosticReport(
560 lsp_types::RelatedFullDocumentDiagnosticReport {
561 full_document_diagnostic_report: lsp_types::FullDocumentDiagnosticReport {
562 result_id: Some("rust-analyzer".to_owned()),
563 items: diagnostics.collect(),
564 },
565 related_documents: related_documents.is_empty().not().then(|| {
566 related_documents
567 .into_iter()
568 .map(|(id, (items, _))| {
569 (
570 to_proto::url(&snap, id),
571 lsp_types::RelatedDocument::FullDocumentDiagnosticReport(
572 lsp_types::FullDocumentDiagnosticReport {
573 result_id: Some("rust-analyzer".to_owned()),
574 items,
575 },
576 ),
577 )
578 })
579 .collect()
580 }),
581 },
582 ))
583}
584
585pub(crate) fn handle_document_symbol(
586 snap: GlobalStateSnapshot,
587 params: lsp_types::DocumentSymbolParams,
588) -> anyhow::Result<Option<lsp_types::DocumentSymbolResponse>> {
589 let _p = tracing::info_span!("handle_document_symbol").entered();
590 let file_id = try_default!(from_proto::file_id(&snap, ¶ms.text_document.uri)?);
591 let line_index = snap.file_line_index(file_id)?;
592
593 let mut symbols: Vec<(lsp_types::DocumentSymbol, Option<usize>)> = Vec::new();
594
595 let config = snap.config.document_symbol(None);
596
597 let structure_nodes = snap.analysis.file_structure(
598 &FileStructureConfig { exclude_locals: config.search_exclude_locals },
599 file_id,
600 )?;
601
602 for node in structure_nodes {
603 let mut tags = Vec::new();
604 if node.deprecated {
605 tags.push(SymbolTag::Deprecated)
606 };
607
608 #[allow(deprecated)]
609 let symbol = lsp_types::DocumentSymbol {
610 name: node.label,
611 detail: node.detail,
612 kind: to_proto::structure_node_kind(node.kind),
613 tags: Some(tags),
614 deprecated: Some(node.deprecated),
615 range: to_proto::range(&line_index, node.node_range),
616 selection_range: to_proto::range(&line_index, node.navigation_range),
617 children: None,
618 };
619 symbols.push((symbol, node.parent));
620 }
621
622 let document_symbols = {
624 let mut acc = Vec::new();
625 while let Some((mut symbol, parent_idx)) = symbols.pop() {
626 if let Some(children) = &mut symbol.children {
627 children.reverse();
628 }
629 let parent = match parent_idx {
630 None => &mut acc,
631 Some(i) => symbols[i].0.children.get_or_insert_with(Vec::new),
632 };
633 parent.push(symbol);
634 }
635 acc.reverse();
636 acc
637 };
638
639 let res = if snap.config.hierarchical_symbols() {
640 document_symbols.into()
641 } else {
642 let url = to_proto::url(&snap, file_id);
643 let mut symbol_information = Vec::new();
644 for symbol in document_symbols {
645 flatten_document_symbol(&symbol, None, &url, &mut symbol_information);
646 }
647 symbol_information.into()
648 };
649 return Ok(Some(res));
650
651 fn flatten_document_symbol(
652 symbol: &lsp_types::DocumentSymbol,
653 container_name: Option<String>,
654 url: &Uri,
655 res: &mut Vec<SymbolInformation>,
656 ) {
657 #[allow(deprecated)]
658 res.push(SymbolInformation {
659 deprecated: symbol.deprecated,
660 location: Location::new(url.clone(), symbol.range),
661 base_symbol_information: lsp_types::BaseSymbolInformation {
662 name: symbol.name.clone(),
663 kind: symbol.kind,
664 tags: symbol.tags.clone(),
665 container_name,
666 },
667 });
668
669 for child in symbol.children.iter().flatten() {
670 flatten_document_symbol(child, Some(symbol.name.clone()), url, res);
671 }
672 }
673}
674
675pub(crate) fn handle_workspace_symbol(
676 snap: GlobalStateSnapshot,
677 params: WorkspaceSymbolParams,
678) -> anyhow::Result<Option<lsp_types::WorkspaceSymbolResponse>> {
679 let _p = tracing::info_span!("handle_workspace_symbol").entered();
680
681 let config = snap.config.workspace_symbol(None);
682 let (all_symbols, libs) = decide_search_kind_and_scope(¶ms, &config);
683
684 let query = {
685 let query: String = params.query.chars().filter(|&c| c != '#' && c != '*').collect();
686 let mut q = Query::new(query);
687 if !all_symbols {
688 q.only_types();
689 }
690 if libs {
691 q.libs();
692 }
693 if config.search_exclude_imports {
694 q.exclude_imports();
695 }
696 q
697 };
698 let mut res = exec_query(&snap, query, config.search_limit)?;
699 if res.is_empty() && !all_symbols {
700 res = exec_query(&snap, Query::new(params.query), config.search_limit)?;
701 }
702
703 return Ok(Some(lsp_types::WorkspaceSymbolResponse::WorkspaceSymbolList(res)));
704
705 fn decide_search_kind_and_scope(
706 params: &WorkspaceSymbolParams,
707 config: &WorkspaceSymbolConfig,
708 ) -> (bool, bool) {
709 let mut all_symbols = params.query.contains('#');
711 let mut libs = params.query.contains('*');
712
713 if !all_symbols {
716 let search_kind = match params.search_kind {
717 Some(ref search_kind) => search_kind,
718 None => &config.search_kind,
719 };
720 all_symbols = match search_kind {
721 lsp_ext::WorkspaceSymbolSearchKind::OnlyTypes => false,
722 lsp_ext::WorkspaceSymbolSearchKind::AllSymbols => true,
723 }
724 }
725
726 if !libs {
727 let search_scope = match params.search_scope {
728 Some(ref search_scope) => search_scope,
729 None => &config.search_scope,
730 };
731 libs = match search_scope {
732 lsp_ext::WorkspaceSymbolSearchScope::Workspace => false,
733 lsp_ext::WorkspaceSymbolSearchScope::WorkspaceAndDependencies => true,
734 }
735 }
736
737 (all_symbols, libs)
738 }
739
740 fn exec_query(
741 snap: &GlobalStateSnapshot,
742 query: Query,
743 limit: usize,
744 ) -> anyhow::Result<Vec<lsp_types::WorkspaceSymbol>> {
745 let mut res = Vec::new();
746 for nav in snap.analysis.symbol_search(query, limit)? {
747 let container_name = nav.container_name.as_ref().map(|v| v.to_string());
748
749 let info = lsp_types::WorkspaceSymbol {
750 location: lsp_types::WorkspaceSymbolLocation::Location(
751 to_proto::location_from_nav(snap, &nav)?,
752 ),
753 data: None,
754 base_symbol_information: lsp_types::BaseSymbolInformation {
755 name: match &nav.alias {
756 Some(alias) => format!("{} (alias for {})", alias, nav.name),
757 None => nav.name.to_string(),
758 },
759 kind: nav
760 .kind
761 .map(to_proto::symbol_kind)
762 .unwrap_or(lsp_types::SymbolKind::Variable),
763 tags: None,
765 container_name,
766 },
767 };
768 res.push(info);
769 }
770 Ok(res)
771 }
772}
773
774pub(crate) fn handle_will_rename_files(
775 snap: GlobalStateSnapshot,
776 params: lsp_types::RenameFilesParams,
777) -> anyhow::Result<Option<lsp_types::WorkspaceEdit>> {
778 let _p = tracing::info_span!("handle_will_rename_files").entered();
779
780 let source_changes: Vec<SourceChange> = params
781 .files
782 .into_iter()
783 .filter_map(|lsp_types::FileRename { new_uri: to, old_uri: from }| {
784 let from_path = from.to_file_path().ok()?;
785 let to_path = to.to_file_path().ok()?;
786
787 match (from_path.parent(), to_path.parent()) {
789 (Some(p1), Some(p2)) if p1 == p2 => {
790 if from_path.is_dir() {
791 let mut old_folder_name = from_path.file_stem()?.to_str()?.to_owned();
793 old_folder_name.push('/');
794 let from_with_trailing_slash = from.join(&old_folder_name).ok()?;
795
796 let imitate_from_url = from_with_trailing_slash.join("mod.rs").ok()?;
797 let new_file_name = to_path.file_name()?.to_str()?;
798 Some((
799 snap.url_to_file_id(&imitate_from_url).ok()?,
800 new_file_name.to_owned(),
801 ))
802 } else {
803 let old_name = from_path.file_stem()?.to_str()?;
804 let new_name = to_path.file_stem()?.to_str()?;
805 match (old_name, new_name) {
806 ("mod", _) => None,
807 (_, "mod") => None,
808 _ => Some((snap.url_to_file_id(&from).ok()?, new_name.to_owned())),
809 }
810 }
811 }
812 _ => None,
813 }
814 })
815 .filter_map(|(file_id, new_name)| {
816 let file_id = file_id?;
817 let source_root = snap.analysis.source_root_id(file_id).ok();
818 snap.analysis
819 .will_rename_file(file_id, &new_name, &snap.config.rename(source_root))
820 .ok()?
821 })
822 .collect();
823
824 let mut source_changes = source_changes.into_iter();
826 let mut source_change = source_changes.next().unwrap_or_default();
827 source_change.file_system_edits.clear();
828 source_change.extend(source_changes.flat_map(|it| it.source_file_edits));
830 if source_change.source_file_edits.is_empty() {
831 Ok(None)
832 } else {
833 Ok(Some(to_proto::workspace_edit(&snap, source_change)?))
834 }
835}
836
837pub(crate) fn handle_goto_definition(
838 snap: GlobalStateSnapshot,
839 params: lsp_types::DefinitionParams,
840) -> anyhow::Result<Option<lsp_types::DefinitionResponse>> {
841 let _p = tracing::info_span!("handle_goto_definition").entered();
842 let position =
843 try_default!(from_proto::file_position(&snap, ¶ms.text_document_position_params)?);
844 let config = snap.config.goto_definition(snap.minicore());
845 let nav_info = match snap.analysis.goto_definition(position, &config)? {
846 None => return Ok(None),
847 Some(it) => it,
848 };
849 let src = FileRange { file_id: position.file_id, range: nav_info.range };
850 let res = to_proto::goto_definition_response(&snap, Some(src), nav_info.info)?;
851 Ok(Some(res))
852}
853
854pub(crate) fn handle_goto_declaration(
855 snap: GlobalStateSnapshot,
856 params: lsp_types::DeclarationParams,
857) -> anyhow::Result<Option<lsp_types::DeclarationResponse>> {
858 let _p = tracing::info_span!("handle_goto_declaration").entered();
859 let position =
860 try_default!(from_proto::file_position(&snap, ¶ms.text_document_position_params)?);
861 let config = snap.config.goto_definition(snap.minicore());
862 let nav_info = match snap.analysis.goto_declaration(position, &config)? {
863 None => {
864 let params = lsp_types::DefinitionParams {
866 work_done_progress_params: params.work_done_progress_params,
867 partial_result_params: params.partial_result_params,
868 text_document_position_params: params.text_document_position_params,
869 };
870 return match handle_goto_definition(snap, params) {
871 Ok(Some(x)) => match x {
872 lsp_types::DefinitionResponse::Definition(definition) => {
873 Ok(Some(lsp_types::DeclarationResponse::Declaration(match definition {
874 lsp_types::Definition::Location(location) => {
875 lsp_types::Declaration::Location(location)
876 }
877 lsp_types::Definition::LocationList(locations) => {
878 lsp_types::Declaration::LocationList(locations)
879 }
880 })))
881 }
882 lsp_types::DefinitionResponse::DefinitionLinkList(location_links) => Ok(Some(
883 lsp_types::DeclarationResponse::DeclarationLinkList(location_links),
884 )),
885 },
886 Ok(None) => Ok(None),
887 Err(error) => Err(error),
888 };
889 }
890 Some(it) => it,
891 };
892 let src = FileRange { file_id: position.file_id, range: nav_info.range };
893 let res = to_proto::goto_declaration_response(&snap, Some(src), nav_info.info)?;
894 Ok(Some(res))
895}
896
897pub(crate) fn handle_goto_implementation(
898 snap: GlobalStateSnapshot,
899 params: lsp_types::ImplementationParams,
900) -> anyhow::Result<Option<lsp_types::ImplementationResponse>> {
901 let _p = tracing::info_span!("handle_goto_implementation").entered();
902 let position =
903 try_default!(from_proto::file_position(&snap, ¶ms.text_document_position_params)?);
904 let nav_info =
905 match snap.analysis.goto_implementation(&snap.config.goto_implementation(), position)? {
906 None => return Ok(None),
907 Some(it) => it,
908 };
909 let src = FileRange { file_id: position.file_id, range: nav_info.range };
910 let res = to_proto::goto_implementation_response(&snap, Some(src), nav_info.info)?;
911 Ok(Some(res))
912}
913
914pub(crate) fn handle_goto_type_definition(
915 snap: GlobalStateSnapshot,
916 params: lsp_types::TypeDefinitionParams,
917) -> anyhow::Result<Option<lsp_types::TypeDefinitionResponse>> {
918 let _p = tracing::info_span!("handle_goto_type_definition").entered();
919 let position =
920 try_default!(from_proto::file_position(&snap, ¶ms.text_document_position_params)?);
921 let nav_info = match snap.analysis.goto_type_definition(position)? {
922 None => return Ok(None),
923 Some(it) => it,
924 };
925 let src = FileRange { file_id: position.file_id, range: nav_info.range };
926 let res = to_proto::goto_type_definition_response(&snap, Some(src), nav_info.info)?;
927 Ok(Some(res))
928}
929
930pub(crate) fn handle_parent_module(
931 snap: GlobalStateSnapshot,
932 params: lsp_types::TextDocumentPositionParams,
933) -> anyhow::Result<Option<lsp_types::DefinitionResponse>> {
934 let _p = tracing::info_span!("handle_parent_module").entered();
935 if let Ok(file_path) = ¶ms.text_document.uri.to_file_path() {
936 if file_path.file_name().unwrap_or_default() == "Cargo.toml" {
937 let abs_path_buf = match Utf8PathBuf::from_path_buf(file_path.to_path_buf())
939 .ok()
940 .map(AbsPathBuf::try_from)
941 {
942 Some(Ok(abs_path_buf)) => abs_path_buf,
943 _ => return Ok(None),
944 };
945
946 let manifest_path = match ManifestPath::try_from(abs_path_buf).ok() {
947 Some(manifest_path) => manifest_path,
948 None => return Ok(None),
949 };
950
951 let links: Vec<LocationLink> = snap
952 .workspaces
953 .iter()
954 .filter_map(|ws| match &ws.kind {
955 ProjectWorkspaceKind::Cargo { cargo, .. }
956 | ProjectWorkspaceKind::DetachedFile { cargo: Some((cargo, _, _)), .. } => {
957 cargo.parent_manifests(&manifest_path)
958 }
959 _ => None,
960 })
961 .flatten()
962 .map(|parent_manifest_path| LocationLink {
963 origin_selection_range: None,
964 target_uri: to_proto::url_from_abs_path(&parent_manifest_path),
965 target_range: Range::default(),
966 target_selection_range: Range::default(),
967 })
968 .collect::<_>();
969 return Ok(Some(links.into()));
970 }
971
972 let file_id = try_default!(from_proto::file_id(&snap, ¶ms.text_document.uri)?);
974 let crate_id = match snap.analysis.crates_for(file_id)?.first() {
975 Some(&crate_id) => crate_id,
976 None => return Ok(None),
977 };
978 let cargo_spec = match TargetSpec::for_file(&snap, file_id)? {
979 Some(TargetSpec::Cargo(it)) => it,
980 Some(TargetSpec::ProjectJson(_)) | None => return Ok(None),
981 };
982
983 if snap.analysis.crate_root(crate_id)? == file_id {
984 let cargo_toml_url = to_proto::url_from_abs_path(&cargo_spec.cargo_toml);
985 let res = vec![LocationLink {
986 origin_selection_range: None,
987 target_uri: cargo_toml_url,
988 target_range: Range::default(),
989 target_selection_range: Range::default(),
990 }]
991 .into();
992 return Ok(Some(res));
993 }
994 }
995
996 let position = try_default!(from_proto::file_position(&snap, ¶ms)?);
998 let navs = snap.analysis.parent_module(position)?;
999 let res = to_proto::goto_definition_response(&snap, None, navs)?;
1000 Ok(Some(res))
1001}
1002
1003pub(crate) fn handle_child_modules(
1004 snap: GlobalStateSnapshot,
1005 params: lsp_types::TextDocumentPositionParams,
1006) -> anyhow::Result<Option<lsp_types::DefinitionResponse>> {
1007 let _p = tracing::info_span!("handle_child_modules").entered();
1008 let position = try_default!(from_proto::file_position(&snap, ¶ms)?);
1010 let navs = snap.analysis.child_modules(position)?;
1011 let res = to_proto::goto_definition_response(&snap, None, navs)?;
1012 Ok(Some(res))
1013}
1014
1015pub(crate) fn handle_runnables(
1016 snap: GlobalStateSnapshot,
1017 params: lsp_ext::RunnablesParams,
1018) -> anyhow::Result<Vec<lsp_ext::Runnable>> {
1019 let _p = tracing::info_span!("handle_runnables").entered();
1020 let file_id = try_default!(from_proto::file_id(&snap, ¶ms.text_document.uri)?);
1021 let source_root = snap.analysis.source_root_id(file_id).ok();
1022 let line_index = snap.file_line_index(file_id)?;
1023 let offset = params.position.and_then(|it| from_proto::offset(&line_index, it).ok());
1024 let target_spec = TargetSpec::for_file(&snap, file_id)?;
1025
1026 let mut res = Vec::new();
1027 for runnable in snap.analysis.runnables(file_id)? {
1028 if should_skip_for_offset(&runnable, offset)
1029 || should_skip_target(&runnable, target_spec.as_ref())
1030 {
1031 continue;
1032 }
1033
1034 let update_test = runnable.update_test;
1035 if let Some(mut runnable) = to_proto::runnable(&snap, runnable)? {
1036 if let Some(runnable) = to_proto::make_update_runnable(&runnable, update_test) {
1037 res.push(runnable);
1038 }
1039
1040 if let lsp_ext::RunnableArgs::Cargo(r) = &mut runnable.args
1041 && let Some(TargetSpec::Cargo(CargoTargetSpec {
1042 sysroot_root: Some(sysroot_root),
1043 ..
1044 })) = &target_spec
1045 {
1046 r.environment.insert("RUSTC_TOOLCHAIN".to_owned(), sysroot_root.to_string());
1047 };
1048
1049 res.push(runnable);
1050 }
1051 }
1052
1053 let config = snap.config.runnables(source_root);
1055 match target_spec {
1056 Some(TargetSpec::Cargo(spec)) => {
1057 let is_crate_no_std = snap.analysis.is_crate_no_std(spec.crate_id)?;
1058 for cmd in ["check", "run", "test"] {
1059 if cmd == "run" && spec.target_kind != TargetKind::Bin {
1060 continue;
1061 }
1062 let cwd = if cmd != "test" || spec.target_kind == TargetKind::Bin {
1063 spec.workspace_root.clone()
1064 } else {
1065 spec.cargo_toml.parent().to_path_buf()
1066 };
1067 let mut cargo_args =
1068 vec![cmd.to_owned(), "--package".to_owned(), spec.package.clone()];
1069 let all_targets = cmd != "run" && !is_crate_no_std;
1070 if all_targets {
1071 cargo_args.push("--all-targets".to_owned());
1072 }
1073 cargo_args.extend(config.cargo_extra_args.iter().cloned());
1074 if let Some(config_path) = &config.config_path {
1075 cargo_args.push("--config".to_owned());
1076 cargo_args.push(config_path.to_string());
1077 }
1078 res.push(lsp_ext::Runnable {
1079 label: format!(
1080 "cargo {cmd} -p {}{all_targets}",
1081 spec.package,
1082 all_targets = if all_targets { " --all-targets" } else { "" }
1083 ),
1084 location: None,
1085 args: lsp_ext::RunnableArgs::Cargo(lsp_ext::CargoRunnableArgs {
1086 workspace_root: Some(spec.workspace_root.clone().into()),
1087 cwd: cwd.into(),
1088 override_cargo: config.override_cargo.clone(),
1089 cargo_args,
1090 executable_args: Vec::new(),
1091 environment: spec
1092 .sysroot_root
1093 .as_ref()
1094 .map(|root| ("RUSTC_TOOLCHAIN".to_owned(), root.to_string()))
1095 .into_iter()
1096 .collect(),
1097 }),
1098 })
1099 }
1100 }
1101 Some(TargetSpec::ProjectJson(_)) => {}
1102 None => {
1103 if !snap.config.linked_or_discovered_projects().is_empty()
1104 && let Some(path) = snap.file_id_to_file_path(file_id).parent()
1105 {
1106 let mut cargo_args = vec!["check".to_owned(), "--workspace".to_owned()];
1107 cargo_args.extend(config.cargo_extra_args.iter().cloned());
1108 if let Some(config_path) = &config.config_path {
1109 cargo_args.push("--config".to_owned());
1110 cargo_args.push(config_path.to_string());
1111 }
1112 res.push(lsp_ext::Runnable {
1113 label: "cargo check --workspace".to_owned(),
1114 location: None,
1115 args: lsp_ext::RunnableArgs::Cargo(lsp_ext::CargoRunnableArgs {
1116 workspace_root: None,
1117 cwd: path.as_path().unwrap().to_path_buf().into(),
1118 override_cargo: config.override_cargo,
1119 cargo_args,
1120 executable_args: Vec::new(),
1121 environment: Default::default(),
1122 }),
1123 });
1124 };
1125 }
1126 }
1127 Ok(res)
1128}
1129
1130fn should_skip_for_offset(runnable: &Runnable, offset: Option<TextSize>) -> bool {
1131 match offset {
1132 None => false,
1133 _ if matches!(&runnable.kind, RunnableKind::TestMod { .. }) => false,
1134 Some(offset) => !runnable.nav.full_range.contains_inclusive(offset),
1135 }
1136}
1137
1138pub(crate) fn handle_related_tests(
1139 snap: GlobalStateSnapshot,
1140 params: lsp_types::TextDocumentPositionParams,
1141) -> anyhow::Result<Vec<lsp_ext::TestInfo>> {
1142 let _p = tracing::info_span!("handle_related_tests").entered();
1143 let position = try_default!(from_proto::file_position(&snap, ¶ms)?);
1144
1145 let tests = snap.analysis.related_tests(position, None)?;
1146 let mut res = Vec::new();
1147 for it in tests {
1148 if let Ok(Some(runnable)) = to_proto::runnable(&snap, it) {
1149 res.push(lsp_ext::TestInfo { runnable })
1150 }
1151 }
1152
1153 Ok(res)
1154}
1155
1156pub(crate) fn handle_completion(
1157 snap: GlobalStateSnapshot,
1158 lsp_types::CompletionParams {
1159 text_document_position_params,
1160 context,
1161 ..
1162 }: lsp_types::CompletionParams,
1163) -> anyhow::Result<Option<lsp_types::CompletionResponse>> {
1164 let _p = tracing::info_span!("handle_completion").entered();
1165 let mut position =
1166 try_default!(from_proto::file_position(&snap, &text_document_position_params)?);
1167 let line_index = snap.file_line_index(position.file_id)?;
1168 let completion_trigger_character =
1169 context.and_then(|ctx| ctx.trigger_character).and_then(|s| s.chars().next());
1170
1171 let source_root = snap.analysis.source_root_id(position.file_id)?;
1172 let completion_config = &snap.config.completion(Some(source_root), snap.minicore());
1173 position.offset = position.offset.min(line_index.index.len());
1175 let items = match snap.analysis.completions(
1176 completion_config,
1177 position,
1178 completion_trigger_character,
1179 )? {
1180 None => return Ok(None),
1181 Some(items) => items,
1182 };
1183
1184 let items = to_proto::completion_items(
1185 &snap.config,
1186 &completion_config.fields_to_resolve,
1187 &line_index,
1188 snap.file_version(position.file_id),
1189 &text_document_position_params,
1190 completion_trigger_character,
1191 items,
1192 );
1193
1194 let completion_list = lsp_types::CompletionList {
1195 is_incomplete: true,
1196 items,
1197 item_defaults: None,
1198 apply_kind: None,
1199 };
1200 Ok(Some(completion_list.into()))
1201}
1202
1203pub(crate) fn handle_completion_resolve(
1204 snap: GlobalStateSnapshot,
1205 mut original_completion: CompletionItem,
1206) -> anyhow::Result<CompletionItem> {
1207 let _p = tracing::info_span!("handle_completion_resolve").entered();
1208
1209 if !all_edits_are_disjoint(&original_completion, &[]) {
1210 return Err(invalid_params_error(
1211 "Received a completion with overlapping edits, this is not LSP-compliant".to_owned(),
1212 )
1213 .into());
1214 }
1215
1216 let Some(data) = original_completion.data.take() else {
1217 return Ok(original_completion);
1218 };
1219
1220 let resolve_data: lsp_ext::CompletionResolveData = serde_json::from_value(data)?;
1221
1222 let file_id = from_proto::file_id(&snap, &resolve_data.position.text_document.uri)?
1223 .expect("we never provide completions for excluded files");
1224 let line_index = snap.file_line_index(file_id)?;
1225 let Ok(offset) = from_proto::offset(&line_index, resolve_data.position.position) else {
1227 return Ok(original_completion);
1228 };
1229 let source_root = snap.analysis.source_root_id(file_id)?;
1230
1231 let mut forced_resolve_completions_config =
1232 snap.config.completion(Some(source_root), snap.minicore());
1233 forced_resolve_completions_config.fields_to_resolve = CompletionFieldsToResolve::empty();
1234
1235 let position = FilePosition { file_id, offset };
1236 let Some(completions) = snap.analysis.completions(
1237 &forced_resolve_completions_config,
1238 position,
1239 resolve_data.trigger_character,
1240 )?
1241 else {
1242 return Ok(original_completion);
1243 };
1244 let Ok(resolve_data_hash) = BASE64_STANDARD.decode(resolve_data.hash) else {
1245 return Ok(original_completion);
1246 };
1247
1248 let Some(corresponding_completion) = completions.into_iter().find(|completion_item| {
1249 original_completion.label.starts_with(completion_item.label.primary.as_str())
1252 && resolve_data_hash == completion_item_hash(completion_item, resolve_data.for_ref)
1253 }) else {
1254 return Ok(original_completion);
1255 };
1256
1257 let mut resolved_completions = to_proto::completion_items(
1258 &snap.config,
1259 &forced_resolve_completions_config.fields_to_resolve,
1260 &line_index,
1261 snap.file_version(position.file_id),
1262 &resolve_data.position,
1263 resolve_data.trigger_character,
1264 vec![corresponding_completion],
1265 );
1266 let Some(mut resolved_completion) = resolved_completions.pop() else {
1267 return Ok(original_completion);
1268 };
1269
1270 if !resolve_data.imports.is_empty() {
1271 let additional_edits = snap
1272 .analysis
1273 .resolve_completion_edits(
1274 &forced_resolve_completions_config,
1275 position,
1276 resolve_data.imports.into_iter().map(|import| CompletionItemImport {
1277 path: import.full_import_path,
1278 as_underscore: import.as_underscore,
1279 }),
1280 )?
1281 .into_iter()
1282 .flat_map(|edit| edit.into_iter().map(|indel| to_proto::text_edit(&line_index, indel)))
1283 .collect::<Vec<_>>();
1284
1285 if !all_edits_are_disjoint(&resolved_completion, &additional_edits) {
1286 return Err(LspError::new(
1287 ErrorCode::InternalError as i32,
1288 "Import edit overlaps with the original completion edits, this is not LSP-compliant"
1289 .into(),
1290 )
1291 .into());
1292 }
1293
1294 if let Some(original_additional_edits) = resolved_completion.additional_text_edits.as_mut()
1295 {
1296 original_additional_edits.extend(additional_edits)
1297 } else {
1298 resolved_completion.additional_text_edits = Some(additional_edits);
1299 }
1300 }
1301
1302 Ok(resolved_completion)
1303}
1304
1305pub(crate) fn handle_folding_range(
1306 snap: GlobalStateSnapshot,
1307 params: FoldingRangeParams,
1308) -> anyhow::Result<Option<Vec<FoldingRange>>> {
1309 let _p = tracing::info_span!("handle_folding_range").entered();
1310
1311 let file_id = try_default!(from_proto::file_id(&snap, ¶ms.text_document.uri)?);
1312 let collapsed_text = snap.config.folding_range_collapsed_text();
1313 let folds = snap.analysis.folding_ranges(file_id, collapsed_text)?;
1314
1315 let text = snap.analysis.file_text(file_id)?;
1316 let line_index = snap.file_line_index(file_id)?;
1317 let line_folding_only = snap.config.line_folding_only();
1318
1319 let res = folds
1320 .into_iter()
1321 .map(|it| to_proto::folding_range(&text, &line_index, line_folding_only, it))
1322 .collect();
1323 Ok(Some(res))
1324}
1325
1326pub(crate) fn handle_signature_help(
1327 snap: GlobalStateSnapshot,
1328 params: lsp_types::SignatureHelpParams,
1329) -> anyhow::Result<Option<lsp_types::SignatureHelp>> {
1330 let _p = tracing::info_span!("handle_signature_help").entered();
1331 let position =
1332 try_default!(from_proto::file_position(&snap, ¶ms.text_document_position_params)?);
1333 let help = match snap.analysis.signature_help(position)? {
1334 Some(it) => it,
1335 None => return Ok(None),
1336 };
1337 let config = snap.config.call_info();
1338 let res = to_proto::signature_help(help, config, snap.config.signature_help_label_offsets());
1339 Ok(Some(res))
1340}
1341
1342pub(crate) fn handle_hover(
1343 snap: GlobalStateSnapshot,
1344 params: lsp_ext::HoverParams,
1345) -> anyhow::Result<Option<lsp_ext::Hover>> {
1346 let _p = tracing::info_span!("handle_hover").entered();
1347 let range = match params.position {
1348 PositionOrRange::Position(position) => Range::new(position, position),
1349 PositionOrRange::Range(range) => range,
1350 };
1351 let file_range = try_default!(from_proto::file_range(&snap, ¶ms.text_document, range)?);
1352
1353 let hover = snap.config.hover(snap.minicore());
1354 let info = match snap.analysis.hover(&hover, file_range)? {
1355 None => return Ok(None),
1356 Some(info) => info,
1357 };
1358
1359 let line_index = snap.file_line_index(file_range.file_id)?;
1360 let range = to_proto::range(&line_index, info.range);
1361 let markup_kind = hover.format;
1362 let hover = lsp_ext::Hover {
1363 hover: lsp_types::Hover {
1364 contents: Contents::MarkupContent(to_proto::markup_content(
1365 info.info.markup,
1366 markup_kind,
1367 )),
1368 range: Some(range),
1369 },
1370 actions: if snap.config.hover_actions().none() {
1371 Vec::new()
1372 } else {
1373 prepare_hover_actions(&snap, &info.info.actions)
1374 },
1375 };
1376
1377 Ok(Some(hover))
1378}
1379
1380pub(crate) fn handle_prepare_rename(
1381 snap: GlobalStateSnapshot,
1382 params: lsp_types::PrepareRenameParams,
1383) -> anyhow::Result<Option<PrepareRenameResult>> {
1384 let _p = tracing::info_span!("handle_prepare_rename").entered();
1385 let position =
1386 try_default!(from_proto::file_position(&snap, ¶ms.text_document_position_params)?);
1387
1388 let change = snap.analysis.prepare_rename(position)?.map_err(to_proto::rename_error)?;
1389
1390 let line_index = snap.file_line_index(position.file_id)?;
1391 let range = to_proto::range(&line_index, change.range);
1392 Ok(Some(PrepareRenameResult::Range(range)))
1393}
1394
1395pub(crate) fn handle_rename(
1396 snap: GlobalStateSnapshot,
1397 params: RenameParams,
1398) -> anyhow::Result<Option<WorkspaceEdit>> {
1399 let _p = tracing::info_span!("handle_rename").entered();
1400 let position =
1401 try_default!(from_proto::file_position(&snap, ¶ms.text_document_position_params)?);
1402
1403 let source_root = snap.analysis.source_root_id(position.file_id).ok();
1404 let config = snap.config.rename(source_root);
1405 let mut change = snap
1406 .analysis
1407 .rename(position, ¶ms.new_name, &config)?
1408 .map_err(to_proto::rename_error)?;
1409
1410 if !change.file_system_edits.is_empty() && snap.config.will_rename() {
1417 change.source_file_edits.clear();
1418 }
1419
1420 let workspace_edit = to_proto::workspace_edit(&snap, change)?;
1421
1422 if let Some(changes) = workspace_edit.document_changes.as_ref() {
1423 for change in changes {
1424 resource_ops_supported(&snap.config, change)?;
1425 }
1426 }
1427
1428 Ok(Some(workspace_edit))
1429}
1430
1431pub(crate) fn handle_references(
1432 snap: GlobalStateSnapshot,
1433 params: lsp_types::ReferenceParams,
1434) -> anyhow::Result<Option<Vec<Location>>> {
1435 let _p = tracing::info_span!("handle_references").entered();
1436 let position =
1437 try_default!(from_proto::file_position(&snap, ¶ms.text_document_position_params)?);
1438
1439 let exclude_imports = snap.config.find_all_refs_exclude_imports();
1440 let exclude_tests = snap.config.find_all_refs_exclude_tests();
1441 let Some(refs) = snap.analysis.find_all_refs(
1442 position,
1443 &FindAllRefsConfig {
1444 search_scope: None,
1445 ra_fixture: snap.config.ra_fixture(snap.minicore()),
1446 exclude_imports,
1447 exclude_tests,
1448 },
1449 )?
1450 else {
1451 return Ok(None);
1452 };
1453
1454 let include_declaration = params.context.include_declaration;
1455 let locations = refs
1456 .into_iter()
1457 .flat_map(|refs| {
1458 let decl = if include_declaration {
1459 refs.declaration.map(|decl| FileRange {
1460 file_id: decl.nav.file_id,
1461 range: decl.nav.focus_or_full_range(),
1462 })
1463 } else {
1464 None
1465 };
1466 refs.references
1467 .into_iter()
1468 .flat_map(|(file_id, refs)| {
1469 refs.into_iter().map(move |(range, _)| FileRange { file_id, range })
1470 })
1471 .chain(decl)
1472 })
1473 .unique()
1474 .filter_map(|frange| to_proto::location(&snap, frange).ok())
1475 .collect();
1476
1477 Ok(Some(locations))
1478}
1479
1480pub(crate) fn handle_formatting(
1481 snap: GlobalStateSnapshot,
1482 params: lsp_types::DocumentFormattingParams,
1483) -> anyhow::Result<Option<Vec<lsp_types::TextEdit>>> {
1484 let _p = tracing::info_span!("handle_formatting").entered();
1485
1486 run_rustfmt(&snap, ¶ms.text_document, None)
1487}
1488
1489pub(crate) fn handle_range_formatting(
1490 snap: GlobalStateSnapshot,
1491 params: lsp_types::DocumentRangeFormattingParams,
1492) -> anyhow::Result<Option<Vec<lsp_types::TextEdit>>> {
1493 let _p = tracing::info_span!("handle_range_formatting").entered();
1494
1495 run_rustfmt(&snap, ¶ms.text_document, Some(params.range))
1496}
1497
1498pub(crate) fn handle_code_action(
1499 snap: GlobalStateSnapshot,
1500 params: lsp_types::CodeActionParams,
1501) -> anyhow::Result<Option<Vec<lsp_ext::CodeAction>>> {
1502 let _p = tracing::info_span!("handle_code_action").entered();
1503
1504 if !snap.config.code_action_literals() {
1505 return Ok(None);
1509 }
1510
1511 let file_id = try_default!(from_proto::file_id(&snap, ¶ms.text_document.uri)?);
1512 let line_index = snap.file_line_index(file_id)?;
1513 let frange = try_default!(from_proto::file_range(&snap, ¶ms.text_document, params.range)?);
1514 let source_root = snap.analysis.source_root_id(file_id)?;
1515
1516 let mut assists_config = snap.config.assist(Some(source_root));
1517 assists_config.allowed = params
1518 .context
1519 .only
1520 .clone()
1521 .map(|it| it.into_iter().filter_map(from_proto::assist_kind).collect());
1522
1523 let mut res: Vec<lsp_ext::CodeAction> = Vec::new();
1524
1525 let code_action_resolve_cap = snap.config.code_action_resolve();
1526 let resolve = if code_action_resolve_cap {
1527 AssistResolveStrategy::None
1528 } else {
1529 AssistResolveStrategy::All
1530 };
1531 let assists = snap.analysis.assists_with_fixes(
1532 &assists_config,
1533 &snap.config.diagnostic_fixes(Some(source_root)),
1534 resolve,
1535 frange,
1536 )?;
1537 let client_commands = snap.config.client_commands();
1538 for (index, assist) in assists.into_iter().enumerate() {
1539 let resolve_data = if code_action_resolve_cap {
1540 Some((index, params.clone(), snap.file_version(file_id)))
1541 } else {
1542 None
1543 };
1544 let code_action = to_proto::code_action(&snap, &client_commands, assist, resolve_data)?;
1545
1546 let changes = code_action.edit.as_ref().and_then(|it| it.document_changes.as_ref());
1548 if let Some(changes) = changes {
1549 for change in changes {
1550 if let lsp_ext::SnippetDocumentChangeOperation::Change(change) = change {
1551 resource_ops_supported(&snap.config, change)?
1552 }
1553 }
1554 }
1555
1556 res.push(code_action)
1557 }
1558
1559 for fix in snap
1561 .check_fixes
1562 .iter()
1563 .flat_map(|it| it.values())
1564 .filter_map(|it| it.get(&frange.file_id))
1565 .flatten()
1566 {
1567 let intersect_fix_range = fix
1570 .ranges
1571 .iter()
1572 .copied()
1573 .filter_map(|range| from_proto::text_range(&line_index, range).ok())
1574 .any(|fix_range| fix_range.intersect(frange.range).is_some());
1575
1576 if intersect_fix_range {
1577 res.push(fix.action.clone());
1578 }
1579 }
1580
1581 Ok(Some(res))
1582}
1583
1584pub(crate) fn handle_code_action_resolve(
1585 snap: GlobalStateSnapshot,
1586 mut code_action: lsp_ext::CodeAction,
1587) -> anyhow::Result<lsp_ext::CodeAction> {
1588 let _p = tracing::info_span!("handle_code_action_resolve").entered();
1589 let Some(params) = code_action.data.take() else {
1590 return Ok(code_action);
1591 };
1592
1593 let file_id = from_proto::file_id(&snap, ¶ms.code_action_params.text_document.uri)?
1594 .expect("we never provide code actions for excluded files");
1595 if snap.file_version(file_id) != params.version {
1596 return Err(invalid_params_error("stale code action".to_owned()).into());
1597 }
1598 let line_index = snap.file_line_index(file_id)?;
1599 let range = from_proto::text_range(&line_index, params.code_action_params.range)?;
1600 let frange = FileRange { file_id, range };
1601 let source_root = snap.analysis.source_root_id(file_id)?;
1602
1603 let mut assists_config = snap.config.assist(Some(source_root));
1604 assists_config.allowed = params
1605 .code_action_params
1606 .context
1607 .only
1608 .map(|it| it.into_iter().filter_map(from_proto::assist_kind).collect());
1609
1610 let (assist_index, assist_resolve) = match parse_action_id(¶ms.id) {
1611 Ok(parsed_data) => parsed_data,
1612 Err(e) => {
1613 return Err(invalid_params_error(format!(
1614 "Failed to parse action id string '{}': {e}",
1615 params.id
1616 ))
1617 .into());
1618 }
1619 };
1620
1621 let expected_assist_id = assist_resolve.assist_id.clone();
1622 let expected_kind = assist_resolve.assist_kind;
1623
1624 let assists = snap.analysis.assists_with_fixes(
1625 &assists_config,
1626 &snap.config.diagnostic_fixes(Some(source_root)),
1627 AssistResolveStrategy::Single(assist_resolve),
1628 frange,
1629 )?;
1630
1631 let assist = match assists.get(assist_index) {
1632 Some(assist) => assist,
1633 None => return Err(invalid_params_error(format!(
1634 "Failed to find the assist for index {} provided by the resolve request. Resolve request assist id: {}",
1635 assist_index, params.id,
1636 ))
1637 .into())
1638 };
1639 if assist.id.0 != expected_assist_id || assist.id.1 != expected_kind {
1640 return Err(invalid_params_error(format!(
1641 "Mismatching assist at index {} for the resolve parameters given. Resolve request assist id: {}, actual id: {:?}.",
1642 assist_index, params.id, assist.id
1643 ))
1644 .into());
1645 }
1646 let ca = to_proto::code_action(&snap, &snap.config.client_commands(), assist.clone(), None)?;
1647 code_action.edit = ca.edit;
1648 code_action.command = ca.command;
1649
1650 if let Some(edit) = code_action.edit.as_ref()
1651 && let Some(changes) = edit.document_changes.as_ref()
1652 {
1653 for change in changes {
1654 if let lsp_ext::SnippetDocumentChangeOperation::Change(change) = change {
1655 resource_ops_supported(&snap.config, change)?
1656 }
1657 }
1658 }
1659
1660 Ok(code_action)
1661}
1662
1663fn parse_action_id(action_id: &str) -> anyhow::Result<(usize, SingleResolve), String> {
1664 let id_parts = action_id.split(':').collect::<Vec<_>>();
1665 match id_parts.as_slice() {
1666 [assist_id_string, assist_kind_string, index_string, subtype_str] => {
1667 let assist_kind: AssistKind = assist_kind_string.parse()?;
1668 let index: usize = match index_string.parse() {
1669 Ok(index) => index,
1670 Err(e) => return Err(format!("Incorrect index string: {e}")),
1671 };
1672 let assist_subtype = subtype_str.parse::<usize>().ok();
1673 Ok((
1674 index,
1675 SingleResolve {
1676 assist_id: assist_id_string.to_string(),
1677 assist_kind,
1678 assist_subtype,
1679 },
1680 ))
1681 }
1682 _ => Err("Action id contains incorrect number of segments".to_owned()),
1683 }
1684}
1685
1686pub(crate) fn handle_code_lens(
1687 snap: GlobalStateSnapshot,
1688 params: lsp_types::CodeLensParams,
1689) -> anyhow::Result<Option<Vec<CodeLens>>> {
1690 let _p = tracing::info_span!("handle_code_lens").entered();
1691
1692 let lens_config = snap.config.lens();
1693 if lens_config.none() {
1694 return Ok(Some(Vec::default()));
1696 }
1697
1698 let file_id = try_default!(from_proto::file_id(&snap, ¶ms.text_document.uri)?);
1699 let target_spec = TargetSpec::for_file(&snap, file_id)?;
1700
1701 let annotations = snap.analysis.annotations(
1702 &lens_config.into_annotation_config(
1703 target_spec
1704 .map(|spec| {
1705 matches!(
1706 spec.target_kind(),
1707 TargetKind::Bin
1708 | TargetKind::Example
1709 | TargetKind::Test
1710 | TargetKind::Bench
1711 )
1712 })
1713 .unwrap_or(false),
1714 snap.minicore(),
1715 ),
1716 file_id,
1717 )?;
1718
1719 let mut res = Vec::new();
1720 for a in annotations {
1721 to_proto::code_lens(&mut res, &snap, a)?;
1722 }
1723
1724 Ok(Some(res))
1725}
1726
1727pub(crate) fn handle_code_lens_resolve(
1728 snap: GlobalStateSnapshot,
1729 mut code_lens: CodeLens,
1730) -> anyhow::Result<CodeLens> {
1731 let Some(data) = code_lens.data.take() else {
1732 return Ok(code_lens);
1733 };
1734 let resolve = serde_json::from_value::<lsp_ext::CodeLensResolveData>(data)?;
1735 let Some(annotation) = from_proto::annotation(&snap, code_lens.range, resolve)? else {
1736 return Ok(code_lens);
1737 };
1738 let config = snap.config.lens().into_annotation_config(false, snap.minicore());
1739 let annotation = snap.analysis.resolve_annotation(&config, annotation)?;
1740
1741 let mut acc = Vec::new();
1742 to_proto::code_lens(&mut acc, &snap, annotation)?;
1743
1744 let mut res = match acc.pop() {
1745 Some(it) if acc.is_empty() => it,
1746 _ => {
1747 never!();
1748 code_lens
1749 }
1750 };
1751 res.data = None;
1752
1753 Ok(res)
1754}
1755
1756pub(crate) fn handle_document_highlight(
1757 snap: GlobalStateSnapshot,
1758 params: lsp_types::DocumentHighlightParams,
1759) -> anyhow::Result<Option<Vec<lsp_types::DocumentHighlight>>> {
1760 let _p = tracing::info_span!("handle_document_highlight").entered();
1761 let position =
1762 try_default!(from_proto::file_position(&snap, ¶ms.text_document_position_params)?);
1763 let line_index = snap.file_line_index(position.file_id)?;
1764 let source_root = snap.analysis.source_root_id(position.file_id)?;
1765
1766 let refs = match snap
1767 .analysis
1768 .highlight_related(snap.config.highlight_related(Some(source_root)), position)?
1769 {
1770 None => return Ok(None),
1771 Some(refs) => refs,
1772 };
1773 let res = refs
1774 .into_iter()
1775 .map(|ide::HighlightedRange { range, category }| lsp_types::DocumentHighlight {
1776 range: to_proto::range(&line_index, range),
1777 kind: to_proto::document_highlight_kind(category),
1778 })
1779 .collect();
1780 Ok(Some(res))
1781}
1782
1783pub(crate) fn handle_ssr(
1784 snap: GlobalStateSnapshot,
1785 params: lsp_ext::SsrParams,
1786) -> anyhow::Result<lsp_types::WorkspaceEdit> {
1787 let _p = tracing::info_span!("handle_ssr").entered();
1788 let selections = try_default!(
1789 params
1790 .selections
1791 .iter()
1792 .map(|range| from_proto::file_range(&snap, ¶ms.position.text_document, *range))
1793 .collect::<Result<Option<Vec<_>>, _>>()?
1794 );
1795 let position = try_default!(from_proto::file_position(&snap, ¶ms.position)?);
1796 let source_change = snap.analysis.structural_search_replace(
1797 ¶ms.query,
1798 params.parse_only,
1799 position,
1800 selections,
1801 )??;
1802 to_proto::workspace_edit(&snap, source_change).map_err(Into::into)
1803}
1804
1805pub(crate) fn handle_inlay_hints(
1806 snap: GlobalStateSnapshot,
1807 params: InlayHintParams,
1808) -> anyhow::Result<Option<Vec<InlayHint>>> {
1809 let _p = tracing::info_span!("handle_inlay_hints").entered();
1810 let document_uri = ¶ms.text_document.uri;
1811 let FileRange { file_id, range } = try_default!(from_proto::file_range(
1812 &snap,
1813 &TextDocumentIdentifier::new(document_uri.to_owned()),
1814 params.range,
1815 )?);
1816 let line_index = snap.file_line_index(file_id)?;
1817 let range = TextRange::new(
1818 range.start().min(line_index.index.len()),
1819 range.end().min(line_index.index.len()),
1820 );
1821
1822 let inlay_hints_config = snap.config.inlay_hints(snap.minicore());
1823 Ok(Some(
1824 snap.analysis
1825 .inlay_hints(&inlay_hints_config, file_id, Some(range))?
1826 .into_iter()
1827 .map(|it| {
1828 to_proto::inlay_hint(
1829 &snap,
1830 &inlay_hints_config.fields_to_resolve,
1831 &line_index,
1832 file_id,
1833 it,
1834 )
1835 })
1836 .collect::<Cancellable<Vec<_>>>()?,
1837 ))
1838}
1839
1840pub(crate) fn handle_inlay_hints_resolve(
1841 snap: GlobalStateSnapshot,
1842 mut original_hint: InlayHint,
1843) -> anyhow::Result<InlayHint> {
1844 let _p = tracing::info_span!("handle_inlay_hints_resolve").entered();
1845
1846 let Some(data) = original_hint.data.take() else {
1847 return Ok(original_hint);
1848 };
1849 let resolve_data: lsp_ext::InlayHintResolveData = serde_json::from_value(data)?;
1850 let file_id = FileId::from_raw(resolve_data.file_id);
1851 if resolve_data.version != snap.file_version(file_id) {
1852 tracing::warn!("Inlay hint resolve data is outdated");
1853 return Ok(original_hint);
1854 }
1855 let Some(hash) = resolve_data.hash.parse().ok() else {
1856 return Ok(original_hint);
1857 };
1858 anyhow::ensure!(snap.file_exists(file_id), "Invalid LSP resolve data");
1859
1860 let line_index = snap.file_line_index(file_id)?;
1861 let range = from_proto::text_range(&line_index, resolve_data.resolve_range)?;
1862
1863 let mut forced_resolve_inlay_hints_config = snap.config.inlay_hints(snap.minicore());
1864 forced_resolve_inlay_hints_config.fields_to_resolve = InlayFieldsToResolve::empty();
1865 let resolve_hints = snap.analysis.inlay_hints_resolve(
1866 &forced_resolve_inlay_hints_config,
1867 file_id,
1868 range,
1869 hash,
1870 |hint| {
1871 std::hash::BuildHasher::hash_one(
1872 &std::hash::BuildHasherDefault::<ide_db::FxHasher>::default(),
1873 hint,
1874 )
1875 },
1876 )?;
1877
1878 Ok(resolve_hints
1879 .and_then(|it| {
1880 to_proto::inlay_hint(
1881 &snap,
1882 &forced_resolve_inlay_hints_config.fields_to_resolve,
1883 &line_index,
1884 file_id,
1885 it,
1886 )
1887 .ok()
1888 })
1889 .filter(|hint| hint.position == original_hint.position)
1890 .filter(|hint| hint.kind == original_hint.kind)
1891 .unwrap_or(original_hint))
1892}
1893
1894pub(crate) fn handle_call_hierarchy_prepare(
1895 snap: GlobalStateSnapshot,
1896 params: CallHierarchyPrepareParams,
1897) -> anyhow::Result<Option<Vec<CallHierarchyItem>>> {
1898 let _p = tracing::info_span!("handle_call_hierarchy_prepare").entered();
1899 let position =
1900 try_default!(from_proto::file_position(&snap, ¶ms.text_document_position_params)?);
1901
1902 let config = snap.config.call_hierarchy(snap.minicore());
1903 let nav_info = match snap.analysis.call_hierarchy(position, &config)? {
1904 None => return Ok(None),
1905 Some(it) => it,
1906 };
1907
1908 let RangeInfo { range: _, info: navs } = nav_info;
1909 let res = navs
1910 .into_iter()
1911 .filter(|it| matches!(it.kind, Some(SymbolKind::Function | SymbolKind::Method)))
1912 .map(|it| to_proto::call_hierarchy_item(&snap, it))
1913 .collect::<Cancellable<Vec<_>>>()?;
1914
1915 Ok(Some(res))
1916}
1917
1918pub(crate) fn handle_call_hierarchy_incoming(
1919 snap: GlobalStateSnapshot,
1920 params: CallHierarchyIncomingCallsParams,
1921) -> anyhow::Result<Option<Vec<CallHierarchyIncomingCall>>> {
1922 let _p = tracing::info_span!("handle_call_hierarchy_incoming").entered();
1923 let item = params.item;
1924
1925 let doc = TextDocumentIdentifier::new(item.uri);
1926 let frange = try_default!(from_proto::file_range(&snap, &doc, item.selection_range)?);
1927 let fpos = FilePosition { file_id: frange.file_id, offset: frange.range.start() };
1928
1929 let config = snap.config.call_hierarchy(snap.minicore());
1930 let call_items = match snap.analysis.incoming_calls(&config, fpos)? {
1931 None => return Ok(None),
1932 Some(it) => it,
1933 };
1934
1935 Ok(Some(
1936 call_items
1937 .into_iter()
1938 .map(|call_item| {
1939 let file_id = call_item.target.file_id;
1940 let line_index = snap.file_line_index(file_id)?;
1941 let item = to_proto::call_hierarchy_item(&snap, call_item.target)?;
1942 Ok(CallHierarchyIncomingCall {
1943 from: item,
1944 from_ranges: call_item
1945 .ranges
1946 .iter()
1947 .filter(|it| it.file_id == file_id)
1949 .map(|it| to_proto::range(&line_index, it.range))
1950 .collect(),
1951 })
1952 })
1953 .collect::<anyhow::Result<_>>()?,
1954 ))
1955}
1956
1957pub(crate) fn handle_call_hierarchy_outgoing(
1958 snap: GlobalStateSnapshot,
1959 params: CallHierarchyOutgoingCallsParams,
1960) -> anyhow::Result<Option<Vec<CallHierarchyOutgoingCall>>> {
1961 let _p = tracing::info_span!("handle_call_hierarchy_outgoing").entered();
1962 let item = params.item;
1963
1964 let doc = TextDocumentIdentifier::new(item.uri);
1965 let frange = try_default!(from_proto::file_range(&snap, &doc, item.selection_range)?);
1966 let fpos = FilePosition { file_id: frange.file_id, offset: frange.range.start() };
1967 let line_index = snap.file_line_index(fpos.file_id)?;
1968
1969 let config = snap.config.call_hierarchy(snap.minicore());
1970 let call_items = match snap.analysis.outgoing_calls(&config, fpos)? {
1971 None => return Ok(None),
1972 Some(it) => it,
1973 };
1974
1975 let mut res = vec![];
1976
1977 for call_item in call_items.into_iter() {
1978 let item = to_proto::call_hierarchy_item(&snap, call_item.target)?;
1979 res.push(CallHierarchyOutgoingCall {
1980 to: item,
1981 from_ranges: call_item
1982 .ranges
1983 .into_iter()
1984 .filter(|it| it.file_id == fpos.file_id)
1986 .map(|it| to_proto::range(&line_index, it.range))
1987 .collect(),
1988 });
1989 }
1990
1991 Ok(Some(res))
1992}
1993
1994pub(crate) fn handle_semantic_tokens_full(
1995 snap: GlobalStateSnapshot,
1996 params: SemanticTokensParams,
1997) -> anyhow::Result<Option<SemanticTokens>> {
1998 let _p = tracing::info_span!("handle_semantic_tokens_full").entered();
1999
2000 let file_id = try_default!(from_proto::file_id(&snap, ¶ms.text_document.uri)?);
2001 let text = snap.analysis.file_text(file_id)?;
2002 let line_index = snap.file_line_index(file_id)?;
2003
2004 let mut highlight_config = snap.config.highlighting_config(snap.minicore());
2005 highlight_config.syntactic_name_ref_highlighting =
2007 snap.workspaces.is_empty() || !snap.proc_macros_loaded;
2008
2009 let highlights = snap.analysis.highlight(highlight_config, file_id)?;
2010 let semantic_tokens = to_proto::semantic_tokens(
2011 &text,
2012 &line_index,
2013 highlights,
2014 snap.config.semantics_tokens_augments_syntax_tokens(),
2015 snap.config.highlighting_non_standard_tokens(),
2016 );
2017
2018 snap.semantic_tokens_cache.lock().insert(params.text_document.uri, semantic_tokens.clone());
2020
2021 Ok(Some(semantic_tokens))
2022}
2023
2024pub(crate) fn handle_semantic_tokens_full_delta(
2025 snap: GlobalStateSnapshot,
2026 params: SemanticTokensDeltaParams,
2027) -> anyhow::Result<Option<SemanticTokensDeltaResponse>> {
2028 let _p = tracing::info_span!("handle_semantic_tokens_full_delta").entered();
2029
2030 let file_id = try_default!(from_proto::file_id(&snap, ¶ms.text_document.uri)?);
2031 let text = snap.analysis.file_text(file_id)?;
2032 let line_index = snap.file_line_index(file_id)?;
2033
2034 let mut highlight_config = snap.config.highlighting_config(snap.minicore());
2035 highlight_config.syntactic_name_ref_highlighting =
2037 snap.workspaces.is_empty() || !snap.proc_macros_loaded;
2038
2039 let highlights = snap.analysis.highlight(highlight_config, file_id)?;
2040 let semantic_tokens = to_proto::semantic_tokens(
2041 &text,
2042 &line_index,
2043 highlights,
2044 snap.config.semantics_tokens_augments_syntax_tokens(),
2045 snap.config.highlighting_non_standard_tokens(),
2046 );
2047
2048 let cached_tokens = snap.semantic_tokens_cache.lock().remove(¶ms.text_document.uri);
2049
2050 if let Some(cached_tokens @ lsp_types::SemanticTokens { result_id: Some(prev_id), .. }) =
2051 &cached_tokens
2052 && *prev_id == params.previous_result_id
2053 {
2054 let delta = to_proto::semantic_token_delta(cached_tokens, &semantic_tokens);
2055 snap.semantic_tokens_cache.lock().insert(params.text_document.uri, semantic_tokens);
2056 return Ok(Some(delta.into()));
2057 }
2058
2059 let semantic_tokens_clone = semantic_tokens.clone();
2061 snap.semantic_tokens_cache.lock().insert(params.text_document.uri, semantic_tokens_clone);
2062
2063 Ok(Some(semantic_tokens.into()))
2064}
2065
2066pub(crate) fn handle_semantic_tokens_range(
2067 snap: GlobalStateSnapshot,
2068 params: SemanticTokensRangeParams,
2069) -> anyhow::Result<Option<SemanticTokens>> {
2070 let _p = tracing::info_span!("handle_semantic_tokens_range").entered();
2071
2072 let frange = try_default!(from_proto::file_range(&snap, ¶ms.text_document, params.range)?);
2073 let text = snap.analysis.file_text(frange.file_id)?;
2074 let line_index = snap.file_line_index(frange.file_id)?;
2075
2076 let mut highlight_config = snap.config.highlighting_config(snap.minicore());
2077 highlight_config.syntactic_name_ref_highlighting =
2079 snap.workspaces.is_empty() || !snap.proc_macros_loaded;
2080
2081 let highlights = snap.analysis.highlight_range(highlight_config, frange)?;
2082 let semantic_tokens = to_proto::semantic_tokens(
2083 &text,
2084 &line_index,
2085 highlights,
2086 snap.config.semantics_tokens_augments_syntax_tokens(),
2087 snap.config.highlighting_non_standard_tokens(),
2088 );
2089 Ok(Some(semantic_tokens))
2090}
2091
2092pub(crate) fn handle_open_docs(
2093 snap: GlobalStateSnapshot,
2094 params: lsp_types::TextDocumentPositionParams,
2095) -> anyhow::Result<ExternalDocsResponse> {
2096 let _p = tracing::info_span!("handle_open_docs").entered();
2097 let position = try_default!(from_proto::file_position(&snap, ¶ms)?);
2098
2099 let ws_and_sysroot = snap.workspaces.iter().find_map(|ws| match &ws.kind {
2100 ProjectWorkspaceKind::Cargo { cargo, .. }
2101 | ProjectWorkspaceKind::DetachedFile { cargo: Some((cargo, _, _)), .. } => {
2102 Some((cargo, &ws.sysroot))
2103 }
2104 ProjectWorkspaceKind::Json { .. } => None,
2105 ProjectWorkspaceKind::DetachedFile { .. } => None,
2106 });
2107
2108 let (cargo, sysroot) = match ws_and_sysroot {
2109 Some((ws, sysroot)) => (Some(ws), Some(sysroot)),
2110 _ => (None, None),
2111 };
2112
2113 let sysroot = sysroot.and_then(|p| p.root()).map(|it| it.as_str());
2114 let target_dir = cargo.map(|cargo| cargo.target_directory()).map(|p| p.as_str());
2115
2116 let Ok(remote_urls) = snap.analysis.external_docs(position, target_dir, sysroot) else {
2117 return if snap.config.local_docs() {
2118 Ok(ExternalDocsResponse::WithLocal(Default::default()))
2119 } else {
2120 Ok(ExternalDocsResponse::Simple(None))
2121 };
2122 };
2123
2124 let web = remote_urls.web_url.and_then(|it| Uri::parse(&it).ok());
2125 let local = remote_urls.local_url.and_then(|it| Uri::parse(&it).ok());
2126
2127 if snap.config.local_docs() {
2128 Ok(ExternalDocsResponse::WithLocal(ExternalDocsPair { web, local }))
2129 } else {
2130 Ok(ExternalDocsResponse::Simple(web))
2131 }
2132}
2133
2134pub(crate) fn handle_open_cargo_toml(
2135 snap: GlobalStateSnapshot,
2136 params: lsp_ext::OpenCargoTomlParams,
2137) -> anyhow::Result<Option<lsp_types::DefinitionResponse>> {
2138 let _p = tracing::info_span!("handle_open_cargo_toml").entered();
2139 let file_id = try_default!(from_proto::file_id(&snap, ¶ms.text_document.uri)?);
2140
2141 let cargo_spec = match TargetSpec::for_file(&snap, file_id)? {
2142 Some(TargetSpec::Cargo(it)) => it,
2143 Some(TargetSpec::ProjectJson(_)) | None => return Ok(None),
2144 };
2145
2146 let cargo_toml_url = to_proto::url_from_abs_path(&cargo_spec.cargo_toml);
2147 let res = lsp_types::DefinitionResponse::Definition(lsp_types::Definition::Location(
2148 Location::new(cargo_toml_url, Range::default()),
2149 ));
2150 Ok(Some(res))
2151}
2152
2153pub(crate) fn handle_move_item(
2154 snap: GlobalStateSnapshot,
2155 params: lsp_ext::MoveItemParams,
2156) -> anyhow::Result<Vec<lsp_ext::SnippetTextEdit>> {
2157 let _p = tracing::info_span!("handle_move_item").entered();
2158 let file_id = try_default!(from_proto::file_id(&snap, ¶ms.text_document.uri)?);
2159 let range = try_default!(from_proto::file_range(&snap, ¶ms.text_document, params.range)?);
2160
2161 let direction = match params.direction {
2162 lsp_ext::MoveItemDirection::Up => ide::Direction::Up,
2163 lsp_ext::MoveItemDirection::Down => ide::Direction::Down,
2164 };
2165
2166 match snap.analysis.move_item(range, direction)? {
2167 Some(text_edit) => {
2168 let line_index = snap.file_line_index(file_id)?;
2169 Ok(to_proto::snippet_text_edit_vec(
2170 &line_index,
2171 true,
2172 text_edit,
2173 snap.config.change_annotation_support(),
2174 ))
2175 }
2176 None => Ok(vec![]),
2177 }
2178}
2179
2180pub(crate) fn handle_view_recursive_memory_layout(
2181 snap: GlobalStateSnapshot,
2182 params: lsp_types::TextDocumentPositionParams,
2183) -> anyhow::Result<Option<lsp_ext::RecursiveMemoryLayout>> {
2184 let _p = tracing::info_span!("handle_view_recursive_memory_layout").entered();
2185 let file_id = try_default!(from_proto::file_id(&snap, ¶ms.text_document.uri)?);
2186 let line_index = snap.file_line_index(file_id)?;
2187 let offset = from_proto::offset(&line_index, params.position)?;
2188
2189 let res = snap.analysis.get_recursive_memory_layout(FilePosition { file_id, offset })?;
2190 Ok(res.map(|it| lsp_ext::RecursiveMemoryLayout {
2191 nodes: it
2192 .nodes
2193 .iter()
2194 .map(|n| lsp_ext::MemoryLayoutNode {
2195 item_name: n.item_name.clone(),
2196 typename: n.typename.clone(),
2197 size: n.size,
2198 offset: n.offset,
2199 alignment: n.alignment,
2200 parent_idx: n.parent_idx,
2201 children_start: n.children_start,
2202 children_len: n.children_len,
2203 })
2204 .collect(),
2205 }))
2206}
2207
2208fn to_command_link(command: lsp_types::Command, tooltip: String) -> lsp_ext::CommandLink {
2209 lsp_ext::CommandLink { tooltip: Some(tooltip), command }
2210}
2211
2212fn show_impl_command_link(
2213 snap: &GlobalStateSnapshot,
2214 position: &FilePosition,
2215 implementations: bool,
2216 show_references: bool,
2217) -> Option<lsp_ext::CommandLinkGroup> {
2218 if implementations
2219 && show_references
2220 && let Some(nav_data) = snap
2221 .analysis
2222 .goto_implementation(&snap.config.goto_implementation(), *position)
2223 .unwrap_or(None)
2224 {
2225 let uri = to_proto::url(snap, position.file_id);
2226 let line_index = snap.file_line_index(position.file_id).ok()?;
2227 let position = to_proto::position(&line_index, position.offset);
2228 let locations: Vec<_> = nav_data
2229 .info
2230 .into_iter()
2231 .filter_map(|nav| to_proto::location_from_nav(snap, &nav).ok())
2232 .collect();
2233 let title = to_proto::implementation_title(locations.len());
2234 let command = to_proto::command::show_references(title, &uri, position, locations);
2235
2236 return Some(lsp_ext::CommandLinkGroup {
2237 commands: vec![to_command_link(command, "Go to implementations".into())],
2238 ..Default::default()
2239 });
2240 }
2241 None
2242}
2243
2244fn show_ref_command_link(
2245 snap: &GlobalStateSnapshot,
2246 position: &FilePosition,
2247 references: bool,
2248 show_reference: bool,
2249) -> Option<lsp_ext::CommandLinkGroup> {
2250 if references
2251 && show_reference
2252 && let Some(ref_search_res) = snap
2253 .analysis
2254 .find_all_refs(
2255 *position,
2256 &FindAllRefsConfig {
2257 search_scope: None,
2258
2259 ra_fixture: snap.config.ra_fixture(snap.minicore()),
2260 exclude_imports: snap.config.find_all_refs_exclude_imports(),
2261 exclude_tests: snap.config.find_all_refs_exclude_tests(),
2262 },
2263 )
2264 .unwrap_or(None)
2265 {
2266 let uri = to_proto::url(snap, position.file_id);
2267 let line_index = snap.file_line_index(position.file_id).ok()?;
2268 let position = to_proto::position(&line_index, position.offset);
2269 let locations: Vec<_> = ref_search_res
2270 .into_iter()
2271 .flat_map(|res| res.references)
2272 .flat_map(|(file_id, ranges)| {
2273 ranges.into_iter().map(move |(range, _)| FileRange { file_id, range })
2274 })
2275 .unique()
2276 .filter_map(|range| to_proto::location(snap, range).ok())
2277 .collect();
2278 let title = to_proto::reference_title(locations.len());
2279 let command = to_proto::command::show_references(title, &uri, position, locations);
2280
2281 return Some(lsp_ext::CommandLinkGroup {
2282 commands: vec![to_command_link(command, "Go to references".into())],
2283 ..Default::default()
2284 });
2285 }
2286 None
2287}
2288
2289fn runnable_action_links(
2290 snap: &GlobalStateSnapshot,
2291 runnable: Runnable,
2292 hover_actions_config: &HoverActionsConfig,
2293 client_commands_config: &ClientCommandsConfig,
2294) -> Option<lsp_ext::CommandLinkGroup> {
2295 if !hover_actions_config.runnable() {
2296 return None;
2297 }
2298
2299 let target_spec = TargetSpec::for_file(snap, runnable.nav.file_id).ok()?;
2300 if should_skip_target(&runnable, target_spec.as_ref()) {
2301 return None;
2302 }
2303
2304 if !(client_commands_config.run_single || client_commands_config.debug_single) {
2305 return None;
2306 }
2307
2308 let title = runnable.title();
2309 let update_test = runnable.update_test;
2310 let r = to_proto::runnable(snap, runnable).ok()??;
2311
2312 let mut group = lsp_ext::CommandLinkGroup::default();
2313
2314 if hover_actions_config.run && client_commands_config.run_single {
2315 let run_command = to_proto::command::run_single(&r, &title);
2316 group.commands.push(to_command_link(run_command, r.label.clone()));
2317 }
2318
2319 if hover_actions_config.debug && client_commands_config.debug_single {
2320 let dbg_command = to_proto::command::debug_single(&r);
2321 group.commands.push(to_command_link(dbg_command, r.label.clone()));
2322 }
2323
2324 if hover_actions_config.update_test && client_commands_config.run_single {
2325 let label = update_test.label();
2326 if let Some(r) = to_proto::make_update_runnable(&r, update_test) {
2327 let update_command = to_proto::command::run_single(&r, label.unwrap().as_str());
2328 group.commands.push(to_command_link(update_command, r.label));
2329 }
2330 }
2331
2332 Some(group)
2333}
2334
2335fn goto_type_action_links(
2336 snap: &GlobalStateSnapshot,
2337 nav_targets: &[HoverGotoTypeData],
2338 hover_actions: &HoverActionsConfig,
2339 client_commands: &ClientCommandsConfig,
2340) -> Option<lsp_ext::CommandLinkGroup> {
2341 if !hover_actions.goto_type_def || nav_targets.is_empty() || !client_commands.goto_location {
2342 return None;
2343 }
2344
2345 Some(lsp_ext::CommandLinkGroup {
2346 title: Some("Go to ".into()),
2347 commands: nav_targets
2348 .iter()
2349 .filter_map(|it| {
2350 to_proto::command::goto_location(snap, &it.nav)
2351 .map(|cmd| to_command_link(cmd, it.mod_path.clone()))
2352 })
2353 .collect(),
2354 })
2355}
2356
2357fn prepare_hover_actions(
2358 snap: &GlobalStateSnapshot,
2359 actions: &[HoverAction],
2360) -> Vec<lsp_ext::CommandLinkGroup> {
2361 let hover_actions = snap.config.hover_actions();
2362 let client_commands = snap.config.client_commands();
2363 actions
2364 .iter()
2365 .filter_map(|it| match it {
2366 HoverAction::Implementation(position) => show_impl_command_link(
2367 snap,
2368 position,
2369 hover_actions.implementations,
2370 client_commands.show_reference,
2371 ),
2372 HoverAction::Reference(position) => show_ref_command_link(
2373 snap,
2374 position,
2375 hover_actions.references,
2376 client_commands.show_reference,
2377 ),
2378 HoverAction::Runnable(r) => {
2379 runnable_action_links(snap, r.clone(), &hover_actions, &client_commands)
2380 }
2381 HoverAction::GoToType(targets) => {
2382 goto_type_action_links(snap, targets, &hover_actions, &client_commands)
2383 }
2384 })
2385 .collect()
2386}
2387
2388fn should_skip_target(runnable: &Runnable, cargo_spec: Option<&TargetSpec>) -> bool {
2389 match runnable.kind {
2390 RunnableKind::Bin => {
2391 match &cargo_spec {
2393 Some(spec) => !matches!(
2394 spec.target_kind(),
2395 TargetKind::Bin | TargetKind::Example | TargetKind::Test | TargetKind::Bench
2396 ),
2397 None => true,
2398 }
2399 }
2400 _ => false,
2401 }
2402}
2403
2404fn run_rustfmt(
2405 snap: &GlobalStateSnapshot,
2406 text_document: &TextDocumentIdentifier,
2407 range: Option<lsp_types::Range>,
2408) -> anyhow::Result<Option<Vec<lsp_types::TextEdit>>> {
2409 let file_id = try_default!(from_proto::file_id(snap, &text_document.uri)?);
2410 let file = snap.analysis.file_text(file_id)?;
2411
2412 let line_index = snap.file_line_index(file_id)?;
2413 let source_root_id = snap.analysis.source_root_id(file_id).ok();
2414 let crates = snap.analysis.relevant_crates_for(file_id)?;
2415
2416 let current_dir = match text_document.uri.to_file_path() {
2420 Ok(mut path) => {
2421 if path.pop() && path.is_dir() { path } else { std::env::current_dir()? }
2423 }
2424 Err(_) => {
2425 tracing::error!(
2426 text_document = ?text_document.uri,
2427 "Unable to get path, rustfmt.toml might be ignored"
2428 );
2429 std::env::current_dir()?
2430 }
2431 };
2432
2433 let mut command = match snap.config.rustfmt(source_root_id) {
2434 RustfmtConfig::Rustfmt { extra_args, enable_range_formatting } => {
2435 let Ok(editions) = crates
2438 .iter()
2439 .map(|&crate_id| snap.analysis.crate_edition(crate_id))
2440 .collect::<Result<Vec<_>, _>>()
2441 else {
2442 return Ok(None);
2443 };
2444 let edition = editions.iter().copied().max();
2445
2446 let mut cmd = toolchain::command(
2448 toolchain::Tool::Rustfmt.path(),
2449 current_dir,
2450 snap.config.extra_env(source_root_id),
2451 );
2452 cmd.args(extra_args);
2453
2454 if let Some(edition) = edition {
2455 cmd.arg("--edition");
2456 cmd.arg(edition.to_string());
2457 }
2458
2459 if let Some(range) = range {
2460 if !enable_range_formatting {
2461 return Err(LspError::new(
2462 ErrorCode::InvalidRequest as i32,
2463 String::from(
2464 "rustfmt range formatting is unstable. \
2465 Opt-in by using a nightly build of rustfmt and setting \
2466 `rustfmt.rangeFormatting.enable` to true in your LSP configuration",
2467 ),
2468 )
2469 .into());
2470 }
2471
2472 let frange = try_default!(from_proto::file_range(snap, text_document, range)?);
2473 let start_line = line_index.index.line_col(frange.range.start()).line;
2474 let end_line = line_index.index.line_col(frange.range.end()).line;
2475
2476 cmd.arg("--unstable-features");
2477 cmd.arg("--file-lines");
2478 cmd.arg(
2479 json!([{
2480 "file": "stdin",
2481 "range": [start_line + 1, end_line + 1]
2483 }])
2484 .to_string(),
2485 );
2486 }
2487
2488 cmd
2489 }
2490 RustfmtConfig::CustomCommand { command, args } => {
2491 let cmd = Utf8PathBuf::from(&command);
2492 let target_spec = TargetSpec::for_file(snap, file_id).ok().flatten();
2493 let extra_env = snap.config.extra_env(source_root_id);
2494 let mut cmd = match target_spec {
2495 Some(TargetSpec::Cargo(_)) => {
2496 let cmd_path = if command.contains(std::path::MAIN_SEPARATOR)
2500 || (cfg!(windows) && command.contains('/'))
2501 {
2502 let project_root = Utf8PathBuf::from_path_buf(current_dir.clone())
2503 .ok()
2504 .and_then(|p| AbsPathBuf::try_from(p).ok());
2505 let project_root = project_root
2506 .as_ref()
2507 .map(|dir| snap.config.workspace_root_for(dir))
2508 .unwrap_or(snap.config.default_root_path());
2509 project_root.join(cmd).into()
2510 } else {
2511 cmd
2512 };
2513 toolchain::command(cmd_path, current_dir, extra_env)
2514 }
2515 _ => toolchain::command(cmd, current_dir, extra_env),
2516 };
2517
2518 cmd.args(args);
2519 cmd
2520 }
2521 };
2522
2523 let output = {
2524 let _p = tracing::info_span!("rustfmt", ?command).entered();
2525
2526 let mut rustfmt = command
2527 .stdin(Stdio::piped())
2528 .stdout(Stdio::piped())
2529 .stderr(Stdio::piped())
2530 .spawn()
2531 .context(format!("Failed to spawn {command:?}"))?;
2532
2533 rustfmt.stdin.as_mut().unwrap().write_all(file.as_bytes())?;
2534
2535 rustfmt.wait_with_output()?
2536 };
2537
2538 let captured_stdout = String::from_utf8(output.stdout)?;
2539 let captured_stderr = String::from_utf8(output.stderr).unwrap_or_default();
2540
2541 if !output.status.success() {
2542 let rustfmt_not_installed =
2543 captured_stderr.contains("not installed") || captured_stderr.contains("not available");
2544
2545 return match output.status.code() {
2546 Some(1) if !rustfmt_not_installed => {
2547 tracing::warn!(
2553 ?command,
2554 %captured_stderr,
2555 "rustfmt exited with status 1"
2556 );
2557 Ok(None)
2558 }
2559 Some(101)
2561 if !rustfmt_not_installed
2562 && (captured_stderr.starts_with("error[")
2563 || captured_stderr.starts_with("error:")) =>
2564 {
2565 Ok(None)
2566 }
2567 _ => {
2568 tracing::error!(
2570 ?command,
2571 %output.status,
2572 %captured_stdout,
2573 %captured_stderr,
2574 "rustfmt failed"
2575 );
2576 Ok(None)
2577 }
2578 };
2579 }
2580
2581 let (new_text, new_line_endings) = LineEndings::normalize(captured_stdout);
2582
2583 if line_index.endings != new_line_endings {
2584 Ok(Some(to_proto::text_edit_vec(
2588 &line_index,
2589 TextEdit::replace(TextRange::up_to(TextSize::of(&*file)), new_text),
2590 )))
2591 } else if *file == new_text {
2592 Ok(None)
2594 } else {
2595 Ok(Some(to_proto::text_edit_vec(&line_index, diff(&file, &new_text))))
2596 }
2597}
2598
2599pub(crate) fn fetch_dependency_list(
2600 state: GlobalStateSnapshot,
2601 _params: FetchDependencyListParams,
2602) -> anyhow::Result<FetchDependencyListResult> {
2603 let crates = state.analysis.fetch_crates()?;
2604 let crate_infos = crates
2605 .into_iter()
2606 .filter_map(|it| {
2607 let root_file_path = state.file_id_to_file_path(it.root_file_id);
2608 crate_path(&root_file_path).and_then(to_url).map(|path| CrateInfoResult {
2609 name: it.name,
2610 version: it.version,
2611 path,
2612 })
2613 })
2614 .collect();
2615 Ok(FetchDependencyListResult { crates: crate_infos })
2616}
2617
2618pub(crate) fn internal_testing_fetch_config(
2619 state: GlobalStateSnapshot,
2620 params: InternalTestingFetchConfigParams,
2621) -> anyhow::Result<Option<InternalTestingFetchConfigResponse>> {
2622 let source_root = match params.text_document {
2623 Some(it) => Some(
2624 state
2625 .analysis
2626 .source_root_id(try_default!(from_proto::file_id(&state, &it.uri)?))
2627 .map_err(anyhow::Error::from)?,
2628 ),
2629 None => None,
2630 };
2631 Ok(Some(match params.config {
2632 InternalTestingFetchConfigOption::AssistEmitMustUse => {
2633 InternalTestingFetchConfigResponse::AssistEmitMustUse(
2634 state.config.assist(source_root).assist_emit_must_use,
2635 )
2636 }
2637 InternalTestingFetchConfigOption::CheckWorkspace => {
2638 InternalTestingFetchConfigResponse::CheckWorkspace(
2639 state.config.flycheck_workspace(source_root),
2640 )
2641 }
2642 }))
2643}
2644
2645pub(crate) fn handle_evaluate_predicate(
2646 snap: GlobalStateSnapshot,
2647 params: lsp_ext::EvaluatePredicateParams,
2648) -> anyhow::Result<lsp_ext::EvaluatePredicateResult> {
2649 let _p = tracing::info_span!("handle_evaluate_predicate").entered();
2650 let file_id = try_default!(from_proto::file_id(&snap, ¶ms.text_document.uri)?);
2651 let line_index = snap.file_line_index(file_id)?;
2652 let offset = from_proto::offset(&line_index, params.position)?;
2653
2654 let result = snap.analysis.evaluate_predicate(params.text, FilePosition { file_id, offset })?;
2655 let status = match result.status {
2656 ide::PredicateEvaluationStatus::Holds => lsp_ext::PredicateEvaluationStatus::Holds,
2657 ide::PredicateEvaluationStatus::NotProven => lsp_ext::PredicateEvaluationStatus::NotProven,
2658 ide::PredicateEvaluationStatus::Invalid => lsp_ext::PredicateEvaluationStatus::Invalid,
2659 ide::PredicateEvaluationStatus::Unsupported => {
2660 lsp_ext::PredicateEvaluationStatus::Unsupported
2661 }
2662 };
2663
2664 Ok(lsp_ext::EvaluatePredicateResult { status, message: result.message })
2665}
2666
2667pub(crate) fn get_failed_obligations(
2668 snap: GlobalStateSnapshot,
2669 params: GetFailedObligationsParams,
2670) -> anyhow::Result<String> {
2671 let _p = tracing::info_span!("get_failed_obligations").entered();
2672 let file_id = try_default!(from_proto::file_id(&snap, ¶ms.text_document.uri)?);
2673 let line_index = snap.file_line_index(file_id)?;
2674 let offset = from_proto::offset(&line_index, params.position)?;
2675
2676 Ok(snap.analysis.get_failed_obligations(offset, file_id)?)
2677}
2678
2679fn crate_path(root_file_path: &VfsPath) -> Option<VfsPath> {
2691 let mut current_dir = root_file_path.parent();
2692 while let Some(path) = current_dir {
2693 let cargo_toml_path = path.join("../Cargo.toml")?;
2694 if fs::metadata(cargo_toml_path.as_path()?).is_ok() {
2695 let crate_path = cargo_toml_path.parent()?;
2696 return Some(crate_path);
2697 }
2698 current_dir = path.parent();
2699 }
2700 None
2701}
2702
2703fn to_url(path: VfsPath) -> Option<Uri> {
2704 let path = path.as_path()?;
2705 let str_path = path.as_os_str().to_str()?;
2706 Uri::from_file_path(str_path).ok()
2707}
2708
2709fn resource_ops_supported(config: &Config, kind: &DocumentChange) -> anyhow::Result<()> {
2710 let op = match kind {
2711 lsp_types::DocumentChange::CreateFile(_) => ResourceOperationKind::Create,
2712 lsp_types::DocumentChange::RenameFile(_) => ResourceOperationKind::Rename,
2713 lsp_types::DocumentChange::DeleteFile(_) => ResourceOperationKind::Delete,
2714 lsp_types::DocumentChange::TextDocumentEdit(_) => return Ok(()),
2715 };
2716 if !matches!(config.workspace_edit_resource_operations(), Some(resops) if resops.contains(&op))
2717 {
2718 return Err(LspError::new(
2719 ErrorCode::RequestFailed as i32,
2720 format!(
2721 "Client does not support {} capability.",
2722 match op {
2723 ResourceOperationKind::Create => "create",
2724 ResourceOperationKind::Rename => "rename",
2725 ResourceOperationKind::Delete => "delete",
2726 ResourceOperationKind::Custom(_) => unreachable!(),
2727 }
2728 ),
2729 )
2730 .into());
2731 }
2732
2733 Ok(())
2734}
2735
2736pub(crate) fn diff(left: &str, right: &str) -> TextEdit {
2737 use dissimilar::Chunk;
2738
2739 let chunks = dissimilar::diff(left, right);
2740
2741 let mut builder = TextEdit::builder();
2742 let mut pos = TextSize::default();
2743
2744 let mut chunks = chunks.into_iter().peekable();
2745 while let Some(chunk) = chunks.next() {
2746 if let (Chunk::Delete(deleted), Some(&Chunk::Insert(inserted))) = (chunk, chunks.peek()) {
2747 chunks.next().unwrap();
2748 let deleted_len = TextSize::of(deleted);
2749 builder.replace(TextRange::at(pos, deleted_len), inserted.into());
2750 pos += deleted_len;
2751 continue;
2752 }
2753
2754 match chunk {
2755 Chunk::Equal(text) => {
2756 pos += TextSize::of(text);
2757 }
2758 Chunk::Delete(deleted) => {
2759 let deleted_len = TextSize::of(deleted);
2760 builder.delete(TextRange::at(pos, deleted_len));
2761 pos += deleted_len;
2762 }
2763 Chunk::Insert(inserted) => {
2764 builder.insert(pos, inserted.into());
2765 }
2766 }
2767 }
2768 builder.finish()
2769}
2770
2771#[test]
2772fn diff_smoke_test() {
2773 let mut original = String::from("fn foo(a:u32){\n}");
2774 let result = "fn foo(a: u32) {}";
2775 let edit = diff(&original, result);
2776 edit.apply(&mut original);
2777 assert_eq!(original, result);
2778}