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