1use anyhow::{Context as _, Result};
2use async_trait::async_trait;
3use collections::HashMap;
4use futures::StreamExt;
5use futures::lock::OwnedMutexGuard;
6use gpui::{App, AppContext, AsyncApp, Entity, SharedString, Task};
7use http_client::github::AssetKind;
8use http_client::github::{GitHubLspBinaryVersion, latest_github_release};
9use http_client::github_download::{GithubBinaryMetadata, download_server_binary};
10pub use language::*;
11use lsp::{InitializeParams, LanguageServerBinary, LanguageServerBinaryOptions};
12use project::lsp_store::rust_analyzer_ext::CARGO_DIAGNOSTICS_SOURCE_NAME;
13use project::project_settings::ProjectSettings;
14use regex::Regex;
15use serde_json::json;
16use settings::{SemanticTokenRules, Settings as _};
17use smallvec::SmallVec;
18use smol::fs::{self};
19use std::cmp::Reverse;
20use std::fmt::Display;
21use std::ops::Range;
22use std::{
23 borrow::Cow,
24 path::{Path, PathBuf},
25 sync::{Arc, LazyLock},
26};
27use task::{TaskTemplate, TaskTemplates, TaskVariables, VariableName};
28use util::command::Stdio;
29use util::fs::{make_file_executable, remove_matching};
30use util::merge_json_value_into;
31use util::rel_path::RelPath;
32use util::{ResultExt, maybe};
33
34use crate::language_settings::LanguageSettings;
35
36pub(crate) fn semantic_token_rules() -> SemanticTokenRules {
37 let content = grammars::get_file("rust/semantic_token_rules.json")
38 .expect("missing rust/semantic_token_rules.json");
39 let json = std::str::from_utf8(&content.data).expect("invalid utf-8 in semantic_token_rules");
40 settings::parse_json_with_comments::<SemanticTokenRules>(json)
41 .expect("failed to parse rust semantic_token_rules.json")
42}
43
44pub struct RustLspAdapter;
45
46#[cfg(target_os = "macos")]
47impl RustLspAdapter {
48 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Gz;
49 const ARCH_SERVER_NAME: &str = "apple-darwin";
50}
51
52#[cfg(target_os = "linux")]
53impl RustLspAdapter {
54 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Gz;
55 const ARCH_SERVER_NAME: &str = "unknown-linux";
56}
57
58#[cfg(target_os = "freebsd")]
59impl RustLspAdapter {
60 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Gz;
61 const ARCH_SERVER_NAME: &str = "unknown-freebsd";
62}
63
64#[cfg(target_os = "windows")]
65impl RustLspAdapter {
66 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Zip;
67 const ARCH_SERVER_NAME: &str = "pc-windows-msvc";
68}
69
70const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("rust-analyzer");
71
72#[cfg(target_os = "linux")]
73enum LibcType {
74 Gnu,
75 Musl,
76}
77
78impl RustLspAdapter {
79 fn convert_rust_analyzer_schema(raw_schema: &serde_json::Value) -> serde_json::Value {
80 let Some(schema_array) = raw_schema.as_array() else {
81 return raw_schema.clone();
82 };
83
84 let mut root_properties = serde_json::Map::new();
85
86 for item in schema_array {
87 if let Some(props) = item.get("properties").and_then(|p| p.as_object()) {
88 for (key, value) in props {
89 let parts: Vec<&str> = key.split('.').collect();
90
91 if parts.is_empty() {
92 continue;
93 }
94
95 let parts_to_process = if parts.first() == Some(&"rust-analyzer") {
96 &parts[1..]
97 } else {
98 &parts[..]
99 };
100
101 if parts_to_process.is_empty() {
102 continue;
103 }
104
105 let mut current = &mut root_properties;
106
107 for (i, part) in parts_to_process.iter().enumerate() {
108 let is_last = i == parts_to_process.len() - 1;
109
110 if is_last {
111 current.insert(part.to_string(), value.clone());
112 } else {
113 let next_current = current
114 .entry(part.to_string())
115 .or_insert_with(|| {
116 serde_json::json!({
117 "type": "object",
118 "properties": {}
119 })
120 })
121 .as_object_mut()
122 .expect("should be an object")
123 .entry("properties")
124 .or_insert_with(|| serde_json::json!({}))
125 .as_object_mut()
126 .expect("properties should be an object");
127
128 current = next_current;
129 }
130 }
131 }
132 }
133 }
134
135 serde_json::json!({
136 "type": "object",
137 "properties": root_properties
138 })
139 }
140
141 #[cfg(target_os = "linux")]
142 async fn determine_libc_type() -> LibcType {
143 use futures::pin_mut;
144
145 async fn from_ldd_version() -> Option<LibcType> {
146 use util::command::new_command;
147
148 let ldd_output = new_command("ldd").arg("--version").output().await.ok()?;
149 let ldd_version = String::from_utf8_lossy(&ldd_output.stdout);
150
151 if ldd_version.contains("GNU libc") || ldd_version.contains("GLIBC") {
152 Some(LibcType::Gnu)
153 } else if ldd_version.contains("musl") {
154 Some(LibcType::Musl)
155 } else {
156 None
157 }
158 }
159
160 if let Some(libc_type) = from_ldd_version().await {
161 return libc_type;
162 }
163
164 let Ok(dir_entries) = smol::fs::read_dir("/lib").await else {
165 // defaulting to gnu because nix doesn't have /lib files due to not following FHS
166 return LibcType::Gnu;
167 };
168 let dir_entries = dir_entries.filter_map(async move |e| e.ok());
169 pin_mut!(dir_entries);
170
171 let mut has_musl = false;
172 let mut has_gnu = false;
173
174 while let Some(entry) = dir_entries.next().await {
175 let file_name = entry.file_name();
176 let file_name = file_name.to_string_lossy();
177 if file_name.starts_with("ld-musl-") {
178 has_musl = true;
179 } else if file_name.starts_with("ld-linux-") {
180 has_gnu = true;
181 }
182 }
183
184 match (has_musl, has_gnu) {
185 (true, _) => LibcType::Musl,
186 (_, true) => LibcType::Gnu,
187 _ => LibcType::Gnu,
188 }
189 }
190
191 #[cfg(target_os = "linux")]
192 async fn build_arch_server_name_linux() -> String {
193 let libc = match Self::determine_libc_type().await {
194 LibcType::Musl => "musl",
195 LibcType::Gnu => "gnu",
196 };
197
198 format!("{}-{}", Self::ARCH_SERVER_NAME, libc)
199 }
200
201 async fn build_asset_name() -> String {
202 let extension = match Self::GITHUB_ASSET_KIND {
203 AssetKind::TarGz => "tar.gz",
204 AssetKind::TarBz2 => "tar.bz2",
205 AssetKind::Gz => "gz",
206 AssetKind::Zip => "zip",
207 };
208
209 #[cfg(target_os = "linux")]
210 let arch_server_name = Self::build_arch_server_name_linux().await;
211 #[cfg(not(target_os = "linux"))]
212 let arch_server_name = Self::ARCH_SERVER_NAME.to_string();
213
214 format!(
215 "{}-{}-{}.{}",
216 SERVER_NAME,
217 std::env::consts::ARCH,
218 &arch_server_name,
219 extension
220 )
221 }
222}
223
224pub(crate) struct CargoManifestProvider;
225
226impl ManifestProvider for CargoManifestProvider {
227 fn name(&self) -> ManifestName {
228 SharedString::new_static("Cargo.toml").into()
229 }
230
231 fn search(
232 &self,
233 ManifestQuery {
234 path,
235 depth,
236 delegate,
237 }: ManifestQuery,
238 ) -> Option<Arc<RelPath>> {
239 let mut outermost_cargo_toml = None;
240 for path in path.ancestors().take(depth) {
241 let p = path.join(RelPath::unix("Cargo.toml").unwrap());
242 if delegate.exists(&p, Some(false)) {
243 outermost_cargo_toml = Some(Arc::from(path));
244 }
245 }
246
247 outermost_cargo_toml
248 }
249}
250
251#[async_trait(?Send)]
252impl LspAdapter for RustLspAdapter {
253 fn name(&self) -> LanguageServerName {
254 SERVER_NAME
255 }
256
257 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
258 vec![CARGO_DIAGNOSTICS_SOURCE_NAME.to_owned()]
259 }
260
261 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
262 Some("rust-analyzer/flycheck".into())
263 }
264
265 fn process_diagnostics(&self, params: &mut lsp::PublishDiagnosticsParams, _: LanguageServerId) {
266 static REGEX: LazyLock<Regex> =
267 LazyLock::new(|| Regex::new(r"(?m)`([^`]+)\n`$").expect("Failed to create REGEX"));
268
269 for diagnostic in &mut params.diagnostics {
270 for message in diagnostic
271 .related_information
272 .iter_mut()
273 .flatten()
274 .map(|info| &mut info.message)
275 .chain([&mut diagnostic.message])
276 {
277 if let Cow::Owned(sanitized) = REGEX.replace_all(message, "`$1`") {
278 *message = sanitized;
279 }
280 }
281 }
282 }
283
284 fn diagnostic_message_to_markdown(&self, message: &str) -> Option<String> {
285 static REGEX: LazyLock<Regex> =
286 LazyLock::new(|| Regex::new(r"(?m)\n *").expect("Failed to create REGEX"));
287 Some(REGEX.replace_all(message, "\n\n").to_string())
288 }
289
290 async fn label_for_completion(
291 &self,
292 completion: &lsp::CompletionItem,
293 language: &Arc<Language>,
294 ) -> Option<CodeLabel> {
295 // rust-analyzer calls these detail left and detail right in terms of where it expects things to be rendered
296 // this usually contains signatures of the thing to be completed
297 let detail_right = completion
298 .label_details
299 .as_ref()
300 .and_then(|detail| detail.description.as_ref())
301 .or(completion.detail.as_ref())
302 .map(|detail| detail.trim());
303 // this tends to contain alias and import information
304 let mut detail_left = completion
305 .label_details
306 .as_ref()
307 .and_then(|detail| detail.detail.as_deref());
308 let mk_label = |text: String, filter_range: &dyn Fn() -> Range<usize>, runs| {
309 let filter_range = completion
310 .filter_text
311 .as_deref()
312 .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
313 .or_else(|| {
314 text.find(&completion.label)
315 .map(|ix| ix..ix + completion.label.len())
316 })
317 .unwrap_or_else(filter_range);
318
319 CodeLabel::new(text, filter_range, runs)
320 };
321 let mut label = match (detail_right, completion.kind) {
322 (Some(signature), Some(lsp::CompletionItemKind::FIELD)) => {
323 let name = &completion.label;
324 let text = format!("{name}: {signature}");
325 let prefix = "struct S { ";
326 let source = Rope::from_iter([prefix, &text, " }"]);
327 let runs =
328 language.highlight_text(&source, prefix.len()..prefix.len() + text.len());
329 mk_label(text, &|| 0..completion.label.len(), runs)
330 }
331 (
332 Some(signature),
333 Some(lsp::CompletionItemKind::CONSTANT | lsp::CompletionItemKind::VARIABLE),
334 ) if completion.insert_text_format != Some(lsp::InsertTextFormat::SNIPPET) => {
335 let name = &completion.label;
336 let text = format!("{name}: {signature}",);
337 let prefix = "let ";
338 let source = Rope::from_iter([prefix, &text, " = ();"]);
339 let runs =
340 language.highlight_text(&source, prefix.len()..prefix.len() + text.len());
341 mk_label(text, &|| 0..completion.label.len(), runs)
342 }
343 (
344 function_signature,
345 Some(lsp::CompletionItemKind::FUNCTION | lsp::CompletionItemKind::METHOD),
346 ) => {
347 const FUNCTION_PREFIXES: [&str; 6] = [
348 "async fn",
349 "async unsafe fn",
350 "const fn",
351 "const unsafe fn",
352 "unsafe fn",
353 "fn",
354 ];
355 let fn_prefixed = FUNCTION_PREFIXES.iter().find_map(|&prefix| {
356 function_signature?
357 .strip_prefix(prefix)
358 .map(|suffix| (prefix, suffix))
359 });
360 let label = if let Some(label) = completion
361 .label
362 .strip_suffix("(…)")
363 .or_else(|| completion.label.strip_suffix("()"))
364 {
365 label
366 } else {
367 &completion.label
368 };
369
370 static FULL_SIGNATURE_REGEX: LazyLock<Regex> =
371 LazyLock::new(|| Regex::new(r"fn (.?+)\(").expect("Failed to create REGEX"));
372 if let Some((function_signature, match_)) = function_signature
373 .filter(|it| it.contains(&label))
374 .and_then(|it| Some((it, FULL_SIGNATURE_REGEX.find(it)?)))
375 {
376 let source = Rope::from(function_signature);
377 let runs = language.highlight_text(&source, 0..function_signature.len());
378 mk_label(
379 function_signature.to_owned(),
380 &|| match_.range().start - 3..match_.range().end - 1,
381 runs,
382 )
383 } else if let Some((prefix, suffix)) = fn_prefixed {
384 let text = format!("{label}{suffix}");
385 let source = Rope::from_iter([prefix, " ", &text, " {}"]);
386 let run_start = prefix.len() + 1;
387 let runs = language.highlight_text(&source, run_start..run_start + text.len());
388 mk_label(text, &|| 0..label.len(), runs)
389 } else if completion
390 .detail
391 .as_ref()
392 .is_some_and(|detail| detail.starts_with("macro_rules! "))
393 {
394 let text = completion.label.clone();
395 let len = text.len();
396 let source = Rope::from(text.as_str());
397 let runs = language.highlight_text(&source, 0..len);
398 mk_label(text, &|| 0..completion.label.len(), runs)
399 } else if detail_left.is_none() {
400 return None;
401 } else {
402 mk_label(
403 completion.label.clone(),
404 &|| 0..completion.label.len(),
405 vec![],
406 )
407 }
408 }
409 (_, kind) => {
410 let mut label;
411 let mut runs = vec![];
412
413 if completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
414 && let Some(
415 lsp::CompletionTextEdit::InsertAndReplace(lsp::InsertReplaceEdit {
416 new_text,
417 ..
418 })
419 | lsp::CompletionTextEdit::Edit(lsp::TextEdit { new_text, .. }),
420 ) = completion.text_edit.as_ref()
421 && let Ok(mut snippet) = snippet::Snippet::parse(new_text)
422 && snippet.tabstops.len() > 1
423 {
424 label = String::new();
425
426 // we never display the final tabstop
427 snippet.tabstops.remove(snippet.tabstops.len() - 1);
428
429 let mut text_pos = 0;
430
431 let mut all_stop_ranges = snippet
432 .tabstops
433 .into_iter()
434 .flat_map(|stop| stop.ranges)
435 .collect::<SmallVec<[_; 8]>>();
436 all_stop_ranges.sort_unstable_by_key(|a| (a.start, Reverse(a.end)));
437
438 for range in &all_stop_ranges {
439 let start_pos = range.start as usize;
440 let end_pos = range.end as usize;
441
442 label.push_str(&snippet.text[text_pos..start_pos]);
443
444 if start_pos == end_pos {
445 let caret_start = label.len();
446 label.push('…');
447 runs.push((caret_start..label.len(), HighlightId::TABSTOP_INSERT_ID));
448 } else {
449 let label_start = label.len();
450 label.push_str(&snippet.text[start_pos..end_pos]);
451 let label_end = label.len();
452 runs.push((label_start..label_end, HighlightId::TABSTOP_REPLACE_ID));
453 }
454
455 text_pos = end_pos;
456 }
457
458 label.push_str(&snippet.text[text_pos..]);
459
460 if detail_left.is_some_and(|detail_left| detail_left == new_text) {
461 // We only include the left detail if it isn't the snippet again
462 detail_left.take();
463 }
464
465 runs.extend(language.highlight_text(&Rope::from(&label), 0..label.len()));
466 } else {
467 let highlight_name = kind.and_then(|kind| match kind {
468 lsp::CompletionItemKind::STRUCT
469 | lsp::CompletionItemKind::INTERFACE
470 | lsp::CompletionItemKind::ENUM => Some("type"),
471 lsp::CompletionItemKind::ENUM_MEMBER => Some("variant"),
472 lsp::CompletionItemKind::KEYWORD => Some("keyword"),
473 lsp::CompletionItemKind::VALUE | lsp::CompletionItemKind::CONSTANT => {
474 Some("constant")
475 }
476 _ => None,
477 });
478
479 label = completion.label.clone();
480
481 if let Some(highlight_name) = highlight_name {
482 let highlight_id =
483 language.grammar()?.highlight_id_for_name(highlight_name)?;
484 runs.push((
485 0..label.rfind('(').unwrap_or(completion.label.len()),
486 highlight_id,
487 ));
488 } else if detail_left.is_none()
489 && kind != Some(lsp::CompletionItemKind::SNIPPET)
490 {
491 return None;
492 }
493 }
494
495 let label_len = label.len();
496
497 mk_label(label, &|| 0..label_len, runs)
498 }
499 };
500
501 if let Some(detail_left) = detail_left {
502 label.text.push(' ');
503 if !detail_left.starts_with('(') {
504 label.text.push('(');
505 }
506 label.text.push_str(detail_left);
507 if !detail_left.ends_with(')') {
508 label.text.push(')');
509 }
510 }
511
512 Some(label)
513 }
514
515 async fn initialization_options_schema(
516 self: Arc<Self>,
517 delegate: &Arc<dyn LspAdapterDelegate>,
518 cached_binary: OwnedMutexGuard<Option<(bool, LanguageServerBinary)>>,
519 cx: &mut AsyncApp,
520 ) -> Option<serde_json::Value> {
521 let binary = self
522 .get_language_server_command(
523 delegate.clone(),
524 None,
525 LanguageServerBinaryOptions {
526 allow_path_lookup: true,
527 allow_binary_download: false,
528 pre_release: false,
529 },
530 cached_binary,
531 cx.clone(),
532 )
533 .await
534 .0
535 .ok()?;
536
537 let mut command = util::command::new_command(&binary.path);
538 command
539 .arg("--print-config-schema")
540 .stdout(Stdio::piped())
541 .stderr(Stdio::piped());
542 let cmd = command
543 .spawn()
544 .map_err(|e| log::debug!("failed to spawn command {command:?}: {e}"))
545 .ok()?;
546 let output = cmd
547 .output()
548 .await
549 .map_err(|e| log::debug!("failed to execute command {command:?}: {e}"))
550 .ok()?;
551 if !output.status.success() {
552 return None;
553 }
554
555 let raw_schema: serde_json::Value = serde_json::from_slice(output.stdout.as_slice())
556 .map_err(|e| log::debug!("failed to parse rust-analyzer's JSON schema output: {e}"))
557 .ok()?;
558
559 // Convert rust-analyzer's array-based schema format to nested JSON Schema
560 let converted_schema = Self::convert_rust_analyzer_schema(&raw_schema);
561 Some(converted_schema)
562 }
563
564 async fn label_for_symbol(
565 &self,
566 symbol: &language::Symbol,
567 language: &Arc<Language>,
568 ) -> Option<CodeLabel> {
569 let name = &symbol.name;
570 let (prefix, suffix) = match symbol.kind {
571 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => ("fn ", "();"),
572 lsp::SymbolKind::STRUCT => ("struct ", ";"),
573 lsp::SymbolKind::ENUM => ("enum ", "{}"),
574 lsp::SymbolKind::INTERFACE => ("trait ", "{}"),
575 lsp::SymbolKind::CONSTANT => ("const ", ":()=();"),
576 lsp::SymbolKind::MODULE => ("mod ", ";"),
577 lsp::SymbolKind::PACKAGE => ("extern crate ", ";"),
578 lsp::SymbolKind::TYPE_PARAMETER => ("type ", "=();"),
579 lsp::SymbolKind::ENUM_MEMBER => {
580 let prefix = "enum E {";
581 return Some(CodeLabel::new(
582 name.to_string(),
583 0..name.len(),
584 language.highlight_text(
585 &Rope::from_iter([prefix, name, "}"]),
586 prefix.len()..prefix.len() + name.len(),
587 ),
588 ));
589 }
590 _ => return None,
591 };
592
593 let filter_range = prefix.len()..prefix.len() + name.len();
594 let display_range = 0..filter_range.end;
595 Some(CodeLabel::new(
596 format!("{prefix}{name}"),
597 filter_range,
598 language.highlight_text(&Rope::from_iter([prefix, name, suffix]), display_range),
599 ))
600 }
601
602 fn prepare_initialize_params(
603 &self,
604 mut original: InitializeParams,
605 cx: &App,
606 ) -> Result<InitializeParams> {
607 let enable_lsp_tasks = ProjectSettings::get_global(cx)
608 .lsp
609 .get(&SERVER_NAME)
610 .is_some_and(|s| s.enable_lsp_tasks);
611
612 let mut experimental = json!({
613 "commands": {
614 "commands": [
615 "rust-analyzer.showReferences",
616 "rust-analyzer.gotoLocation",
617 "rust-analyzer.triggerParameterHints",
618 "rust-analyzer.rename",
619 ]
620 }
621 });
622
623 if enable_lsp_tasks {
624 merge_json_value_into(
625 json!({
626 "runnables": {
627 "kinds": [ "cargo", "shell" ],
628 },
629 "commands": {
630 "commands": [
631 "rust-analyzer.runSingle",
632 "rust-analyzer.debugSingle",
633 ]
634 }
635 }),
636 &mut experimental,
637 );
638 }
639
640 if let Some(original_experimental) = &mut original.capabilities.experimental {
641 merge_json_value_into(experimental, original_experimental);
642 } else {
643 original.capabilities.experimental = Some(experimental);
644 }
645
646 Ok(original)
647 }
648}
649
650impl LspInstaller for RustLspAdapter {
651 type BinaryVersion = GitHubLspBinaryVersion;
652 async fn check_if_user_installed(
653 &self,
654 delegate: &dyn LspAdapterDelegate,
655 _: Option<Toolchain>,
656 _: &AsyncApp,
657 ) -> Option<LanguageServerBinary> {
658 let path = delegate.which("rust-analyzer".as_ref()).await?;
659 let env = delegate.shell_env().await;
660
661 // It is surprisingly common for ~/.cargo/bin/rust-analyzer to be a symlink to
662 // /usr/bin/rust-analyzer that fails when you run it; so we need to test it.
663 log::debug!("found rust-analyzer in PATH. trying to run `rust-analyzer --help`");
664 let result = delegate
665 .try_exec(LanguageServerBinary {
666 path: path.clone(),
667 arguments: vec!["--help".into()],
668 env: Some(env.clone()),
669 })
670 .await;
671 if let Err(err) = result {
672 log::debug!(
673 "failed to run rust-analyzer after detecting it in PATH: binary: {:?}: {}",
674 path,
675 err
676 );
677 return None;
678 }
679
680 Some(LanguageServerBinary {
681 path,
682 env: Some(env),
683 arguments: vec![],
684 })
685 }
686
687 async fn fetch_latest_server_version(
688 &self,
689 delegate: &dyn LspAdapterDelegate,
690 pre_release: bool,
691 _: &mut AsyncApp,
692 ) -> Result<GitHubLspBinaryVersion> {
693 let release = latest_github_release(
694 "rust-lang/rust-analyzer",
695 true,
696 pre_release,
697 delegate.http_client(),
698 )
699 .await?;
700 let asset_name = Self::build_asset_name().await;
701 let asset = release
702 .assets
703 .into_iter()
704 .find(|asset| asset.name == asset_name)
705 .with_context(|| format!("no asset found matching `{asset_name:?}`"))?;
706 Ok(GitHubLspBinaryVersion {
707 name: release.tag_name,
708 url: asset.browser_download_url,
709 digest: asset.digest,
710 })
711 }
712
713 async fn fetch_server_binary(
714 &self,
715 version: GitHubLspBinaryVersion,
716 container_dir: PathBuf,
717 delegate: &dyn LspAdapterDelegate,
718 ) -> Result<LanguageServerBinary> {
719 let GitHubLspBinaryVersion {
720 name,
721 url,
722 digest: expected_digest,
723 } = version;
724 let destination_path = container_dir.join(format!("rust-analyzer-{name}"));
725 let server_path = match Self::GITHUB_ASSET_KIND {
726 AssetKind::TarGz | AssetKind::TarBz2 | AssetKind::Gz => destination_path.clone(), // Tar and gzip extract in place.
727 AssetKind::Zip => destination_path.clone().join("rust-analyzer.exe"), // zip contains a .exe
728 };
729
730 let binary = LanguageServerBinary {
731 path: server_path.clone(),
732 env: None,
733 arguments: Default::default(),
734 };
735
736 let metadata_path = destination_path.with_extension("metadata");
737 let metadata = GithubBinaryMetadata::read_from_file(&metadata_path)
738 .await
739 .ok();
740 if let Some(metadata) = metadata {
741 let validity_check = async || {
742 delegate
743 .try_exec(LanguageServerBinary {
744 path: server_path.clone(),
745 arguments: vec!["--version".into()],
746 env: None,
747 })
748 .await
749 .inspect_err(|err| {
750 log::warn!("Unable to run {server_path:?} asset, redownloading: {err:#}",)
751 })
752 };
753 if let (Some(actual_digest), Some(expected_digest)) =
754 (&metadata.digest, &expected_digest)
755 {
756 if actual_digest == expected_digest {
757 if validity_check().await.is_ok() {
758 return Ok(binary);
759 }
760 } else {
761 log::info!(
762 "SHA-256 mismatch for {destination_path:?} asset, downloading new asset. Expected: {expected_digest}, Got: {actual_digest}"
763 );
764 }
765 } else if validity_check().await.is_ok() {
766 return Ok(binary);
767 }
768 }
769
770 download_server_binary(
771 &*delegate.http_client(),
772 &url,
773 expected_digest.as_deref(),
774 &destination_path,
775 Self::GITHUB_ASSET_KIND,
776 )
777 .await?;
778 make_file_executable(&server_path).await?;
779 remove_matching(&container_dir, |path| path != destination_path).await;
780 GithubBinaryMetadata::write_to_file(
781 &GithubBinaryMetadata {
782 metadata_version: 1,
783 digest: expected_digest,
784 },
785 &metadata_path,
786 )
787 .await?;
788
789 Ok(LanguageServerBinary {
790 path: server_path,
791 env: None,
792 arguments: Default::default(),
793 })
794 }
795
796 async fn cached_server_binary(
797 &self,
798 container_dir: PathBuf,
799 _: &dyn LspAdapterDelegate,
800 ) -> Option<LanguageServerBinary> {
801 get_cached_server_binary(container_dir).await
802 }
803}
804
805pub(crate) struct RustContextProvider;
806
807const RUST_PACKAGE_TASK_VARIABLE: VariableName =
808 VariableName::Custom(Cow::Borrowed("RUST_PACKAGE"));
809
810/// The bin name corresponding to the current file in Cargo.toml
811const RUST_BIN_NAME_TASK_VARIABLE: VariableName =
812 VariableName::Custom(Cow::Borrowed("RUST_BIN_NAME"));
813
814/// The bin kind (bin/example) corresponding to the current file in Cargo.toml
815const RUST_BIN_KIND_TASK_VARIABLE: VariableName =
816 VariableName::Custom(Cow::Borrowed("RUST_BIN_KIND"));
817
818/// The flag to list required features for executing a bin, if any
819const RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE: VariableName =
820 VariableName::Custom(Cow::Borrowed("RUST_BIN_REQUIRED_FEATURES_FLAG"));
821
822/// The list of required features for executing a bin, if any
823const RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE: VariableName =
824 VariableName::Custom(Cow::Borrowed("RUST_BIN_REQUIRED_FEATURES"));
825
826const RUST_TEST_FRAGMENT_TASK_VARIABLE: VariableName =
827 VariableName::Custom(Cow::Borrowed("RUST_TEST_FRAGMENT"));
828
829const RUST_DOC_TEST_NAME_TASK_VARIABLE: VariableName =
830 VariableName::Custom(Cow::Borrowed("RUST_DOC_TEST_NAME"));
831
832const RUST_TEST_NAME_TASK_VARIABLE: VariableName =
833 VariableName::Custom(Cow::Borrowed("RUST_TEST_NAME"));
834
835const RUST_MANIFEST_DIRNAME_TASK_VARIABLE: VariableName =
836 VariableName::Custom(Cow::Borrowed("RUST_MANIFEST_DIRNAME"));
837
838impl ContextProvider for RustContextProvider {
839 fn build_context(
840 &self,
841 task_variables: &TaskVariables,
842 location: ContextLocation<'_>,
843 project_env: Option<HashMap<String, String>>,
844 _: Arc<dyn LanguageToolchainStore>,
845 cx: &mut gpui::App,
846 ) -> Task<Result<TaskVariables>> {
847 let local_abs_path = location
848 .file_location
849 .buffer
850 .read(cx)
851 .file()
852 .and_then(|file| Some(file.as_local()?.abs_path(cx)));
853
854 let mut variables = TaskVariables::default();
855
856 if let (Some(path), Some(stem)) = (&local_abs_path, task_variables.get(&VariableName::Stem))
857 {
858 let fragment = test_fragment(&variables, path, stem);
859 variables.insert(RUST_TEST_FRAGMENT_TASK_VARIABLE, fragment);
860 };
861 if let Some(test_name) =
862 task_variables.get(&VariableName::Custom(Cow::Borrowed("_test_name")))
863 {
864 variables.insert(RUST_TEST_NAME_TASK_VARIABLE, test_name.into());
865 }
866 if let Some(doc_test_name) =
867 task_variables.get(&VariableName::Custom(Cow::Borrowed("_doc_test_name")))
868 {
869 variables.insert(RUST_DOC_TEST_NAME_TASK_VARIABLE, doc_test_name.into());
870 }
871 cx.background_spawn(async move {
872 if let Some(path) = local_abs_path
873 .as_deref()
874 .and_then(|local_abs_path| local_abs_path.parent())
875 && let Some(package_name) =
876 human_readable_package_name(path, project_env.as_ref()).await
877 {
878 variables.insert(RUST_PACKAGE_TASK_VARIABLE.clone(), package_name);
879 }
880 if let Some(path) = local_abs_path.as_ref()
881 && let Some((target, manifest_path)) =
882 target_info_from_abs_path(path, project_env.as_ref()).await
883 {
884 if let Some(target) = target {
885 variables.extend(TaskVariables::from_iter([
886 (RUST_PACKAGE_TASK_VARIABLE.clone(), target.package_name),
887 (RUST_BIN_NAME_TASK_VARIABLE.clone(), target.target_name),
888 (
889 RUST_BIN_KIND_TASK_VARIABLE.clone(),
890 target.target_kind.to_string(),
891 ),
892 ]));
893 if target.required_features.is_empty() {
894 variables.insert(RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE, "".into());
895 variables.insert(RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE, "".into());
896 } else {
897 variables.insert(
898 RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE.clone(),
899 "--features".to_string(),
900 );
901 variables.insert(
902 RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE.clone(),
903 target.required_features.join(","),
904 );
905 }
906 }
907 variables.extend(TaskVariables::from_iter([(
908 RUST_MANIFEST_DIRNAME_TASK_VARIABLE.clone(),
909 manifest_path.to_string_lossy().into_owned(),
910 )]));
911 }
912 Ok(variables)
913 })
914 }
915
916 fn associated_tasks(
917 &self,
918 buffer: Option<Entity<Buffer>>,
919 cx: &App,
920 ) -> Task<Option<TaskTemplates>> {
921 const DEFAULT_RUN_NAME_STR: &str = "RUST_DEFAULT_PACKAGE_RUN";
922 const CUSTOM_TARGET_DIR: &str = "RUST_TARGET_DIR";
923
924 let language = LanguageName::new_static("Rust");
925 let settings = LanguageSettings::resolve(buffer.map(|b| b.read(cx)), Some(&language), cx);
926 let package_to_run = settings.tasks.variables.get(DEFAULT_RUN_NAME_STR).cloned();
927 let custom_target_dir = settings.tasks.variables.get(CUSTOM_TARGET_DIR).cloned();
928 let run_task_args = if let Some(package_to_run) = package_to_run {
929 vec!["run".into(), "-p".into(), package_to_run]
930 } else {
931 vec!["run".into()]
932 };
933 let mut task_templates = vec![
934 TaskTemplate {
935 label: format!(
936 "Check (package: {})",
937 RUST_PACKAGE_TASK_VARIABLE.template_value(),
938 ),
939 command: "cargo".into(),
940 args: vec![
941 "check".into(),
942 "-p".into(),
943 RUST_PACKAGE_TASK_VARIABLE.template_value(),
944 ],
945 cwd: Some("$ZED_DIRNAME".to_owned()),
946 ..TaskTemplate::default()
947 },
948 TaskTemplate {
949 label: "Check all targets (workspace)".into(),
950 command: "cargo".into(),
951 args: vec!["check".into(), "--workspace".into(), "--all-targets".into()],
952 cwd: Some("$ZED_DIRNAME".to_owned()),
953 ..TaskTemplate::default()
954 },
955 TaskTemplate {
956 label: format!(
957 "Test '{}' (package: {})",
958 RUST_TEST_NAME_TASK_VARIABLE.template_value(),
959 RUST_PACKAGE_TASK_VARIABLE.template_value(),
960 ),
961 command: "cargo".into(),
962 args: vec![
963 "test".into(),
964 "-p".into(),
965 RUST_PACKAGE_TASK_VARIABLE.template_value(),
966 "--".into(),
967 "--nocapture".into(),
968 "--include-ignored".into(),
969 RUST_TEST_NAME_TASK_VARIABLE.template_value(),
970 ],
971 tags: vec!["rust-test".to_owned()],
972 cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
973 ..TaskTemplate::default()
974 },
975 TaskTemplate {
976 label: format!(
977 "Doc test '{}' (package: {})",
978 RUST_DOC_TEST_NAME_TASK_VARIABLE.template_value(),
979 RUST_PACKAGE_TASK_VARIABLE.template_value(),
980 ),
981 command: "cargo".into(),
982 args: vec![
983 "test".into(),
984 "--doc".into(),
985 "-p".into(),
986 RUST_PACKAGE_TASK_VARIABLE.template_value(),
987 "--".into(),
988 "--nocapture".into(),
989 "--include-ignored".into(),
990 RUST_DOC_TEST_NAME_TASK_VARIABLE.template_value(),
991 ],
992 tags: vec!["rust-doc-test".to_owned()],
993 cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
994 ..TaskTemplate::default()
995 },
996 TaskTemplate {
997 label: format!(
998 "Test mod '{}' (package: {})",
999 VariableName::Stem.template_value(),
1000 RUST_PACKAGE_TASK_VARIABLE.template_value(),
1001 ),
1002 command: "cargo".into(),
1003 args: vec![
1004 "test".into(),
1005 "-p".into(),
1006 RUST_PACKAGE_TASK_VARIABLE.template_value(),
1007 "--".into(),
1008 RUST_TEST_FRAGMENT_TASK_VARIABLE.template_value(),
1009 ],
1010 tags: vec!["rust-mod-test".to_owned()],
1011 cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
1012 ..TaskTemplate::default()
1013 },
1014 TaskTemplate {
1015 label: format!(
1016 "Run {} {} (package: {})",
1017 RUST_BIN_KIND_TASK_VARIABLE.template_value(),
1018 RUST_BIN_NAME_TASK_VARIABLE.template_value(),
1019 RUST_PACKAGE_TASK_VARIABLE.template_value(),
1020 ),
1021 command: "cargo".into(),
1022 args: vec![
1023 "run".into(),
1024 "-p".into(),
1025 RUST_PACKAGE_TASK_VARIABLE.template_value(),
1026 format!("--{}", RUST_BIN_KIND_TASK_VARIABLE.template_value()),
1027 RUST_BIN_NAME_TASK_VARIABLE.template_value(),
1028 RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE.template_value(),
1029 RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE.template_value(),
1030 ],
1031 cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
1032 tags: vec!["rust-main".to_owned()],
1033 ..TaskTemplate::default()
1034 },
1035 TaskTemplate {
1036 label: format!(
1037 "Test (package: {})",
1038 RUST_PACKAGE_TASK_VARIABLE.template_value()
1039 ),
1040 command: "cargo".into(),
1041 args: vec![
1042 "test".into(),
1043 "-p".into(),
1044 RUST_PACKAGE_TASK_VARIABLE.template_value(),
1045 ],
1046 cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
1047 ..TaskTemplate::default()
1048 },
1049 TaskTemplate {
1050 label: "Run".into(),
1051 command: "cargo".into(),
1052 args: run_task_args,
1053 cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
1054 ..TaskTemplate::default()
1055 },
1056 TaskTemplate {
1057 label: "Clean".into(),
1058 command: "cargo".into(),
1059 args: vec!["clean".into()],
1060 cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
1061 ..TaskTemplate::default()
1062 },
1063 ];
1064
1065 if let Some(custom_target_dir) = custom_target_dir {
1066 task_templates = task_templates
1067 .into_iter()
1068 .map(|mut task_template| {
1069 let mut args = task_template.args.split_off(1);
1070 task_template.args.append(&mut vec![
1071 "--target-dir".to_string(),
1072 custom_target_dir.clone(),
1073 ]);
1074 task_template.args.append(&mut args);
1075
1076 task_template
1077 })
1078 .collect();
1079 }
1080
1081 Task::ready(Some(TaskTemplates(task_templates)))
1082 }
1083
1084 fn lsp_task_source(&self) -> Option<LanguageServerName> {
1085 Some(SERVER_NAME)
1086 }
1087}
1088
1089/// Part of the data structure of Cargo metadata
1090#[derive(Debug, serde::Deserialize)]
1091struct CargoMetadata {
1092 packages: Vec<CargoPackage>,
1093}
1094
1095#[derive(Debug, serde::Deserialize)]
1096struct CargoPackage {
1097 id: String,
1098 targets: Vec<CargoTarget>,
1099 manifest_path: Arc<Path>,
1100}
1101
1102#[derive(Debug, serde::Deserialize)]
1103struct CargoTarget {
1104 name: String,
1105 kind: Vec<String>,
1106 src_path: String,
1107 #[serde(rename = "required-features", default)]
1108 required_features: Vec<String>,
1109}
1110
1111#[derive(Debug, PartialEq)]
1112enum TargetKind {
1113 Bin,
1114 Example,
1115}
1116
1117impl Display for TargetKind {
1118 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1119 match self {
1120 TargetKind::Bin => write!(f, "bin"),
1121 TargetKind::Example => write!(f, "example"),
1122 }
1123 }
1124}
1125
1126impl TryFrom<&str> for TargetKind {
1127 type Error = ();
1128 fn try_from(value: &str) -> Result<Self, ()> {
1129 match value {
1130 "bin" => Ok(Self::Bin),
1131 "example" => Ok(Self::Example),
1132 _ => Err(()),
1133 }
1134 }
1135}
1136/// Which package and binary target are we in?
1137#[derive(Debug, PartialEq)]
1138struct TargetInfo {
1139 package_name: String,
1140 target_name: String,
1141 target_kind: TargetKind,
1142 required_features: Vec<String>,
1143}
1144
1145async fn target_info_from_abs_path(
1146 abs_path: &Path,
1147 project_env: Option<&HashMap<String, String>>,
1148) -> Option<(Option<TargetInfo>, Arc<Path>)> {
1149 let mut command = util::command::new_command("cargo");
1150 if let Some(envs) = project_env {
1151 command.envs(envs);
1152 }
1153 let output = command
1154 .current_dir(abs_path.parent()?)
1155 .arg("metadata")
1156 .arg("--no-deps")
1157 .arg("--format-version")
1158 .arg("1")
1159 .output()
1160 .await
1161 .log_err()?
1162 .stdout;
1163
1164 let metadata: CargoMetadata = serde_json::from_slice(&output).log_err()?;
1165 target_info_from_metadata(metadata, abs_path)
1166}
1167
1168fn target_info_from_metadata(
1169 metadata: CargoMetadata,
1170 abs_path: &Path,
1171) -> Option<(Option<TargetInfo>, Arc<Path>)> {
1172 let mut manifest_path = None;
1173 for package in metadata.packages {
1174 let Some(manifest_dir_path) = package.manifest_path.parent() else {
1175 continue;
1176 };
1177
1178 let Some(path_from_manifest_dir) = abs_path.strip_prefix(manifest_dir_path).ok() else {
1179 continue;
1180 };
1181 let candidate_path_length = path_from_manifest_dir.components().count();
1182 // Pick the most specific manifest path
1183 if let Some((path, current_length)) = &mut manifest_path {
1184 if candidate_path_length > *current_length {
1185 *path = Arc::from(manifest_dir_path);
1186 *current_length = candidate_path_length;
1187 }
1188 } else {
1189 manifest_path = Some((Arc::from(manifest_dir_path), candidate_path_length));
1190 };
1191
1192 for target in package.targets {
1193 let Some(bin_kind) = target
1194 .kind
1195 .iter()
1196 .find_map(|kind| TargetKind::try_from(kind.as_ref()).ok())
1197 else {
1198 continue;
1199 };
1200 let target_path = PathBuf::from(target.src_path);
1201 if target_path == abs_path {
1202 return manifest_path.map(|(path, _)| {
1203 (
1204 package_name_from_pkgid(&package.id).map(|package_name| TargetInfo {
1205 package_name: package_name.to_owned(),
1206 target_name: target.name,
1207 required_features: target.required_features,
1208 target_kind: bin_kind,
1209 }),
1210 path,
1211 )
1212 });
1213 }
1214 }
1215 }
1216
1217 manifest_path.map(|(path, _)| (None, path))
1218}
1219
1220async fn human_readable_package_name(
1221 package_directory: &Path,
1222 project_env: Option<&HashMap<String, String>>,
1223) -> Option<String> {
1224 let mut command = util::command::new_command("cargo");
1225 if let Some(envs) = project_env {
1226 command.envs(envs);
1227 }
1228 let pkgid = String::from_utf8(
1229 command
1230 .current_dir(package_directory)
1231 .arg("pkgid")
1232 .output()
1233 .await
1234 .log_err()?
1235 .stdout,
1236 )
1237 .ok()?;
1238 Some(package_name_from_pkgid(&pkgid)?.to_owned())
1239}
1240
1241// For providing local `cargo check -p $pkgid` task, we do not need most of the information we have returned.
1242// Output example in the root of Zed project:
1243// ```sh
1244// ❯ cargo pkgid zed
1245// path+file:///absolute/path/to/project/zed/crates/zed#0.131.0
1246// ```
1247// Another variant, if a project has a custom package name or hyphen in the name:
1248// ```
1249// path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0
1250// ```
1251//
1252// Extracts the package name from the output according to the spec:
1253// https://doc.rust-lang.org/cargo/reference/pkgid-spec.html#specification-grammar
1254fn package_name_from_pkgid(pkgid: &str) -> Option<&str> {
1255 fn split_off_suffix(input: &str, suffix_start: char) -> &str {
1256 match input.rsplit_once(suffix_start) {
1257 Some((without_suffix, _)) => without_suffix,
1258 None => input,
1259 }
1260 }
1261
1262 let (version_prefix, version_suffix) = pkgid.trim().rsplit_once('#')?;
1263 let package_name = match version_suffix.rsplit_once('@') {
1264 Some((custom_package_name, _version)) => custom_package_name,
1265 None => {
1266 let host_and_path = split_off_suffix(version_prefix, '?');
1267 let (_, package_name) = host_and_path.rsplit_once('/')?;
1268 package_name
1269 }
1270 };
1271 Some(package_name)
1272}
1273
1274async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
1275 let binary_result = maybe!(async {
1276 let mut last = None;
1277 let mut entries = fs::read_dir(&container_dir)
1278 .await
1279 .with_context(|| format!("listing {container_dir:?}"))?;
1280 while let Some(entry) = entries.next().await {
1281 let path = entry?.path();
1282 if path.extension().is_some_and(|ext| ext == "metadata") {
1283 continue;
1284 }
1285 last = Some(path);
1286 }
1287
1288 let path = match last {
1289 Some(last) => last,
1290 None => return Ok(None),
1291 };
1292 let path = match RustLspAdapter::GITHUB_ASSET_KIND {
1293 AssetKind::TarGz | AssetKind::TarBz2 | AssetKind::Gz => path, // Tar and gzip extract in place.
1294 AssetKind::Zip => path.join("rust-analyzer.exe"), // zip contains a .exe
1295 };
1296
1297 anyhow::Ok(Some(LanguageServerBinary {
1298 path,
1299 env: None,
1300 arguments: Vec::new(),
1301 }))
1302 })
1303 .await;
1304
1305 match binary_result {
1306 Ok(Some(binary)) => Some(binary),
1307 Ok(None) => {
1308 log::info!("No cached rust-analyzer binary found");
1309 None
1310 }
1311 Err(e) => {
1312 log::error!("Failed to look up cached rust-analyzer binary: {e:#}");
1313 None
1314 }
1315 }
1316}
1317
1318fn test_fragment(variables: &TaskVariables, path: &Path, stem: &str) -> String {
1319 let fragment = if stem == "lib" {
1320 // This isn't quite right---it runs the tests for the entire library, rather than
1321 // just for the top-level `mod tests`. But we don't really have the means here to
1322 // filter out just that module.
1323 Some("--lib".to_owned())
1324 } else if stem == "mod" {
1325 maybe!({ Some(path.parent()?.file_name()?.to_string_lossy().into_owned()) })
1326 } else if stem == "main" {
1327 if let (Some(bin_name), Some(bin_kind)) = (
1328 variables.get(&RUST_BIN_NAME_TASK_VARIABLE),
1329 variables.get(&RUST_BIN_KIND_TASK_VARIABLE),
1330 ) {
1331 Some(format!("--{bin_kind}={bin_name}"))
1332 } else {
1333 None
1334 }
1335 } else {
1336 Some(stem.to_owned())
1337 };
1338 fragment.unwrap_or_else(|| "--".to_owned())
1339}
1340
1341#[cfg(test)]
1342mod tests {
1343 use std::num::NonZeroU32;
1344
1345 use super::*;
1346 use crate::language;
1347 use gpui::{BorrowAppContext, Hsla, TestAppContext};
1348 use lsp::CompletionItemLabelDetails;
1349 use settings::SettingsStore;
1350 use theme::SyntaxTheme;
1351 use util::path;
1352
1353 #[gpui::test]
1354 async fn test_process_rust_diagnostics() {
1355 let mut params = lsp::PublishDiagnosticsParams {
1356 uri: lsp::Uri::from_file_path(path!("/a")).unwrap(),
1357 version: None,
1358 diagnostics: vec![
1359 // no newlines
1360 lsp::Diagnostic {
1361 message: "use of moved value `a`".to_string(),
1362 ..Default::default()
1363 },
1364 // newline at the end of a code span
1365 lsp::Diagnostic {
1366 message: "consider importing this struct: `use b::c;\n`".to_string(),
1367 ..Default::default()
1368 },
1369 // code span starting right after a newline
1370 lsp::Diagnostic {
1371 message: "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
1372 .to_string(),
1373 ..Default::default()
1374 },
1375 ],
1376 };
1377 RustLspAdapter.process_diagnostics(&mut params, LanguageServerId(0));
1378
1379 assert_eq!(params.diagnostics[0].message, "use of moved value `a`");
1380
1381 // remove trailing newline from code span
1382 assert_eq!(
1383 params.diagnostics[1].message,
1384 "consider importing this struct: `use b::c;`"
1385 );
1386
1387 // do not remove newline before the start of code span
1388 assert_eq!(
1389 params.diagnostics[2].message,
1390 "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
1391 );
1392 }
1393
1394 #[gpui::test]
1395 async fn test_rust_label_for_completion() {
1396 let adapter = Arc::new(RustLspAdapter);
1397 let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1398 let grammar = language.grammar().unwrap();
1399 let theme = SyntaxTheme::new_test([
1400 ("type", Hsla::default()),
1401 ("keyword", Hsla::default()),
1402 ("function", Hsla::default()),
1403 ("property", Hsla::default()),
1404 ]);
1405
1406 language.set_theme(&theme);
1407
1408 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1409 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1410 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1411 let highlight_field = grammar.highlight_id_for_name("property").unwrap();
1412
1413 assert_eq!(
1414 adapter
1415 .label_for_completion(
1416 &lsp::CompletionItem {
1417 kind: Some(lsp::CompletionItemKind::FUNCTION),
1418 label: "hello(…)".to_string(),
1419 label_details: Some(CompletionItemLabelDetails {
1420 detail: Some("(use crate::foo)".into()),
1421 description: Some("fn(&mut Option<T>) -> Vec<T>".to_string())
1422 }),
1423 ..Default::default()
1424 },
1425 &language
1426 )
1427 .await,
1428 Some(CodeLabel::new(
1429 "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1430 0..5,
1431 vec![
1432 (0..5, highlight_function),
1433 (7..10, highlight_keyword),
1434 (11..17, highlight_type),
1435 (18..19, highlight_type),
1436 (25..28, highlight_type),
1437 (29..30, highlight_type),
1438 ],
1439 ))
1440 );
1441 assert_eq!(
1442 adapter
1443 .label_for_completion(
1444 &lsp::CompletionItem {
1445 kind: Some(lsp::CompletionItemKind::FUNCTION),
1446 label: "hello(…)".to_string(),
1447 label_details: Some(CompletionItemLabelDetails {
1448 detail: Some("(use crate::foo)".into()),
1449 description: Some("async fn(&mut Option<T>) -> Vec<T>".to_string()),
1450 }),
1451 ..Default::default()
1452 },
1453 &language
1454 )
1455 .await,
1456 Some(CodeLabel::new(
1457 "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1458 0..5,
1459 vec![
1460 (0..5, highlight_function),
1461 (7..10, highlight_keyword),
1462 (11..17, highlight_type),
1463 (18..19, highlight_type),
1464 (25..28, highlight_type),
1465 (29..30, highlight_type),
1466 ],
1467 ))
1468 );
1469 assert_eq!(
1470 adapter
1471 .label_for_completion(
1472 &lsp::CompletionItem {
1473 kind: Some(lsp::CompletionItemKind::FIELD),
1474 label: "len".to_string(),
1475 detail: Some("usize".to_string()),
1476 ..Default::default()
1477 },
1478 &language
1479 )
1480 .await,
1481 Some(CodeLabel::new(
1482 "len: usize".to_string(),
1483 0..3,
1484 vec![(0..3, highlight_field), (5..10, highlight_type),],
1485 ))
1486 );
1487
1488 assert_eq!(
1489 adapter
1490 .label_for_completion(
1491 &lsp::CompletionItem {
1492 kind: Some(lsp::CompletionItemKind::FUNCTION),
1493 label: "hello(…)".to_string(),
1494 label_details: Some(CompletionItemLabelDetails {
1495 detail: Some("(use crate::foo)".to_string()),
1496 description: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
1497 }),
1498
1499 ..Default::default()
1500 },
1501 &language
1502 )
1503 .await,
1504 Some(CodeLabel::new(
1505 "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1506 0..5,
1507 vec![
1508 (0..5, highlight_function),
1509 (7..10, highlight_keyword),
1510 (11..17, highlight_type),
1511 (18..19, highlight_type),
1512 (25..28, highlight_type),
1513 (29..30, highlight_type),
1514 ],
1515 ))
1516 );
1517
1518 assert_eq!(
1519 adapter
1520 .label_for_completion(
1521 &lsp::CompletionItem {
1522 kind: Some(lsp::CompletionItemKind::FUNCTION),
1523 label: "hello".to_string(),
1524 label_details: Some(CompletionItemLabelDetails {
1525 detail: Some("(use crate::foo)".to_string()),
1526 description: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
1527 }),
1528 ..Default::default()
1529 },
1530 &language
1531 )
1532 .await,
1533 Some(CodeLabel::new(
1534 "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1535 0..5,
1536 vec![
1537 (0..5, highlight_function),
1538 (7..10, highlight_keyword),
1539 (11..17, highlight_type),
1540 (18..19, highlight_type),
1541 (25..28, highlight_type),
1542 (29..30, highlight_type),
1543 ],
1544 ))
1545 );
1546
1547 assert_eq!(
1548 adapter
1549 .label_for_completion(
1550 &lsp::CompletionItem {
1551 kind: Some(lsp::CompletionItemKind::METHOD),
1552 label: "await.as_deref_mut()".to_string(),
1553 filter_text: Some("as_deref_mut".to_string()),
1554 label_details: Some(CompletionItemLabelDetails {
1555 detail: None,
1556 description: Some("fn(&mut self) -> IterMut<'_, T>".to_string()),
1557 }),
1558 ..Default::default()
1559 },
1560 &language
1561 )
1562 .await,
1563 Some(CodeLabel::new(
1564 "await.as_deref_mut(&mut self) -> IterMut<'_, T>".to_string(),
1565 6..18,
1566 vec![
1567 (6..18, HighlightId::new(2)),
1568 (20..23, HighlightId::new(1)),
1569 (33..40, HighlightId::new(0)),
1570 (45..46, HighlightId::new(0))
1571 ],
1572 ))
1573 );
1574
1575 assert_eq!(
1576 adapter
1577 .label_for_completion(
1578 &lsp::CompletionItem {
1579 kind: Some(lsp::CompletionItemKind::METHOD),
1580 label: "as_deref_mut()".to_string(),
1581 filter_text: Some("as_deref_mut".to_string()),
1582 label_details: Some(CompletionItemLabelDetails {
1583 detail: None,
1584 description: Some(
1585 "pub fn as_deref_mut(&mut self) -> IterMut<'_, T>".to_string()
1586 ),
1587 }),
1588 ..Default::default()
1589 },
1590 &language
1591 )
1592 .await,
1593 Some(CodeLabel::new(
1594 "pub fn as_deref_mut(&mut self) -> IterMut<'_, T>".to_string(),
1595 7..19,
1596 vec![
1597 (0..3, HighlightId::new(1)),
1598 (4..6, HighlightId::new(1)),
1599 (7..19, HighlightId::new(2)),
1600 (21..24, HighlightId::new(1)),
1601 (34..41, HighlightId::new(0)),
1602 (46..47, HighlightId::new(0))
1603 ],
1604 ))
1605 );
1606
1607 assert_eq!(
1608 adapter
1609 .label_for_completion(
1610 &lsp::CompletionItem {
1611 kind: Some(lsp::CompletionItemKind::FIELD),
1612 label: "inner_value".to_string(),
1613 filter_text: Some("value".to_string()),
1614 detail: Some("String".to_string()),
1615 ..Default::default()
1616 },
1617 &language,
1618 )
1619 .await,
1620 Some(CodeLabel::new(
1621 "inner_value: String".to_string(),
1622 6..11,
1623 vec![(0..11, HighlightId::new(3)), (13..19, HighlightId::new(0))],
1624 ))
1625 );
1626
1627 // Snippet with insert tabstop (empty placeholder)
1628 assert_eq!(
1629 adapter
1630 .label_for_completion(
1631 &lsp::CompletionItem {
1632 kind: Some(lsp::CompletionItemKind::SNIPPET),
1633 label: "println!".to_string(),
1634 insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
1635 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1636 range: lsp::Range::default(),
1637 new_text: "println!(\"$1\", $2)$0".to_string(),
1638 })),
1639 ..Default::default()
1640 },
1641 &language,
1642 )
1643 .await,
1644 Some(CodeLabel::new(
1645 "println!(\"…\", …)".to_string(),
1646 0..8,
1647 vec![
1648 (10..13, HighlightId::TABSTOP_INSERT_ID),
1649 (16..19, HighlightId::TABSTOP_INSERT_ID),
1650 (0..7, HighlightId::new(2)),
1651 (7..8, HighlightId::new(2)),
1652 ],
1653 ))
1654 );
1655
1656 // Snippet with replace tabstop (placeholder with default text)
1657 assert_eq!(
1658 adapter
1659 .label_for_completion(
1660 &lsp::CompletionItem {
1661 kind: Some(lsp::CompletionItemKind::SNIPPET),
1662 label: "vec!".to_string(),
1663 insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
1664 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1665 range: lsp::Range::default(),
1666 new_text: "vec![${1:elem}]$0".to_string(),
1667 })),
1668 ..Default::default()
1669 },
1670 &language,
1671 )
1672 .await,
1673 Some(CodeLabel::new(
1674 "vec![elem]".to_string(),
1675 0..4,
1676 vec![
1677 (5..9, HighlightId::TABSTOP_REPLACE_ID),
1678 (0..3, HighlightId::new(2)),
1679 (3..4, HighlightId::new(2)),
1680 ],
1681 ))
1682 );
1683
1684 // Snippet with tabstop appearing more than once
1685 assert_eq!(
1686 adapter
1687 .label_for_completion(
1688 &lsp::CompletionItem {
1689 kind: Some(lsp::CompletionItemKind::SNIPPET),
1690 label: "if let".to_string(),
1691 insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
1692 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1693 range: lsp::Range::default(),
1694 new_text: "if let ${1:pat} = $1 {\n $0\n}".to_string(),
1695 })),
1696 ..Default::default()
1697 },
1698 &language,
1699 )
1700 .await,
1701 Some(CodeLabel::new(
1702 "if let pat = … {\n \n}".to_string(),
1703 0..6,
1704 vec![
1705 (7..10, HighlightId::TABSTOP_REPLACE_ID),
1706 (13..16, HighlightId::TABSTOP_INSERT_ID),
1707 (0..2, HighlightId::new(1)),
1708 (3..6, HighlightId::new(1)),
1709 ],
1710 ))
1711 );
1712
1713 // Snippet with tabstops not in left-to-right order
1714 assert_eq!(
1715 adapter
1716 .label_for_completion(
1717 &lsp::CompletionItem {
1718 kind: Some(lsp::CompletionItemKind::SNIPPET),
1719 label: "for".to_string(),
1720 insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
1721 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1722 range: lsp::Range::default(),
1723 new_text: "for ${2:item} in ${1:iter} {\n $0\n}".to_string(),
1724 })),
1725 ..Default::default()
1726 },
1727 &language,
1728 )
1729 .await,
1730 Some(CodeLabel::new(
1731 "for item in iter {\n \n}".to_string(),
1732 0..3,
1733 vec![
1734 (4..8, HighlightId::TABSTOP_REPLACE_ID),
1735 (12..16, HighlightId::TABSTOP_REPLACE_ID),
1736 (0..3, HighlightId::new(1)),
1737 (9..11, HighlightId::new(1)),
1738 ],
1739 ))
1740 );
1741
1742 // Postfix completion without actual tabstops (only implicit final $0)
1743 // The label should use completion.label so it can be filtered by "ref"
1744 let ref_completion = adapter
1745 .label_for_completion(
1746 &lsp::CompletionItem {
1747 kind: Some(lsp::CompletionItemKind::SNIPPET),
1748 label: "ref".to_string(),
1749 filter_text: Some("ref".to_string()),
1750 label_details: Some(CompletionItemLabelDetails {
1751 detail: None,
1752 description: Some("&expr".to_string()),
1753 }),
1754 detail: Some("&expr".to_string()),
1755 insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
1756 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1757 range: lsp::Range::default(),
1758 new_text: "&String::new()".to_string(),
1759 })),
1760 ..Default::default()
1761 },
1762 &language,
1763 )
1764 .await;
1765 assert!(
1766 ref_completion.is_some(),
1767 "ref postfix completion should have a label"
1768 );
1769 let ref_label = ref_completion.unwrap();
1770 let filter_text = &ref_label.text[ref_label.filter_range.clone()];
1771 assert!(
1772 filter_text.contains("ref"),
1773 "filter range text '{filter_text}' should contain 'ref' for filtering to work",
1774 );
1775
1776 // Test for correct range calculation with mixed empty and non-empty tabstops.(See https://github.com/zed-industries/zed/issues/44825)
1777 let res = adapter
1778 .label_for_completion(
1779 &lsp::CompletionItem {
1780 kind: Some(lsp::CompletionItemKind::STRUCT),
1781 label: "Particles".to_string(),
1782 insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
1783 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1784 range: lsp::Range::default(),
1785 new_text: "Particles { pos_x: $1, pos_y: $2, vel_x: $3, vel_y: $4, acc_x: ${5:()}, acc_y: ${6:()}, mass: $7 }$0".to_string(),
1786 })),
1787 ..Default::default()
1788 },
1789 &language,
1790 )
1791 .await
1792 .unwrap();
1793
1794 assert_eq!(
1795 res,
1796 CodeLabel::new(
1797 "Particles { pos_x: …, pos_y: …, vel_x: …, vel_y: …, acc_x: (), acc_y: (), mass: … }".to_string(),
1798 0..9,
1799 vec![
1800 (19..22, HighlightId::TABSTOP_INSERT_ID),
1801 (31..34, HighlightId::TABSTOP_INSERT_ID),
1802 (43..46, HighlightId::TABSTOP_INSERT_ID),
1803 (55..58, HighlightId::TABSTOP_INSERT_ID),
1804 (67..69, HighlightId::TABSTOP_REPLACE_ID),
1805 (78..80, HighlightId::TABSTOP_REPLACE_ID),
1806 (88..91, HighlightId::TABSTOP_INSERT_ID),
1807 (0..9, highlight_type),
1808 (60..65, highlight_field),
1809 (71..76, highlight_field),
1810 ],
1811 )
1812 );
1813 }
1814
1815 #[gpui::test]
1816 async fn test_rust_label_for_symbol() {
1817 let adapter = Arc::new(RustLspAdapter);
1818 let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1819 let grammar = language.grammar().unwrap();
1820 let theme = SyntaxTheme::new_test([
1821 ("type", Hsla::default()),
1822 ("keyword", Hsla::default()),
1823 ("function", Hsla::default()),
1824 ("property", Hsla::default()),
1825 ]);
1826
1827 language.set_theme(&theme);
1828
1829 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1830 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1831 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1832
1833 assert_eq!(
1834 adapter
1835 .label_for_symbol(
1836 &language::Symbol {
1837 name: "hello".to_string(),
1838 kind: lsp::SymbolKind::FUNCTION,
1839 container_name: None,
1840 },
1841 &language
1842 )
1843 .await,
1844 Some(CodeLabel::new(
1845 "fn hello".to_string(),
1846 3..8,
1847 vec![(0..2, highlight_keyword), (3..8, highlight_function)],
1848 ))
1849 );
1850
1851 assert_eq!(
1852 adapter
1853 .label_for_symbol(
1854 &language::Symbol {
1855 name: "World".to_string(),
1856 kind: lsp::SymbolKind::TYPE_PARAMETER,
1857 container_name: None,
1858 },
1859 &language
1860 )
1861 .await,
1862 Some(CodeLabel::new(
1863 "type World".to_string(),
1864 5..10,
1865 vec![(0..4, highlight_keyword), (5..10, highlight_type)],
1866 ))
1867 );
1868
1869 assert_eq!(
1870 adapter
1871 .label_for_symbol(
1872 &language::Symbol {
1873 name: "zed".to_string(),
1874 kind: lsp::SymbolKind::PACKAGE,
1875 container_name: None,
1876 },
1877 &language
1878 )
1879 .await,
1880 Some(CodeLabel::new(
1881 "extern crate zed".to_string(),
1882 13..16,
1883 vec![(0..6, highlight_keyword), (7..12, highlight_keyword),],
1884 ))
1885 );
1886
1887 assert_eq!(
1888 adapter
1889 .label_for_symbol(
1890 &language::Symbol {
1891 name: "Variant".to_string(),
1892 kind: lsp::SymbolKind::ENUM_MEMBER,
1893 container_name: None,
1894 },
1895 &language
1896 )
1897 .await,
1898 Some(CodeLabel::new(
1899 "Variant".to_string(),
1900 0..7,
1901 vec![(0..7, highlight_type)],
1902 ))
1903 );
1904 }
1905
1906 #[gpui::test]
1907 async fn test_rust_autoindent(cx: &mut TestAppContext) {
1908 // cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
1909 cx.update(|cx| {
1910 let test_settings = SettingsStore::test(cx);
1911 cx.set_global(test_settings);
1912 cx.update_global::<SettingsStore, _>(|store, cx| {
1913 store.update_user_settings(cx, |s| {
1914 s.project.all_languages.defaults.tab_size = NonZeroU32::new(2);
1915 });
1916 });
1917 });
1918
1919 let language = crate::language("rust", tree_sitter_rust::LANGUAGE.into());
1920
1921 cx.new(|cx| {
1922 let mut buffer = Buffer::local("", cx).with_language(language, cx);
1923
1924 // indent between braces
1925 buffer.set_text("fn a() {}", cx);
1926 let ix = buffer.len() - 1;
1927 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1928 assert_eq!(buffer.text(), "fn a() {\n \n}");
1929
1930 // indent between braces, even after empty lines
1931 buffer.set_text("fn a() {\n\n\n}", cx);
1932 let ix = buffer.len() - 2;
1933 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1934 assert_eq!(buffer.text(), "fn a() {\n\n\n \n}");
1935
1936 // indent a line that continues a field expression
1937 buffer.set_text("fn a() {\n \n}", cx);
1938 let ix = buffer.len() - 2;
1939 buffer.edit([(ix..ix, "b\n.c")], Some(AutoindentMode::EachLine), cx);
1940 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n}");
1941
1942 // indent further lines that continue the field expression, even after empty lines
1943 let ix = buffer.len() - 2;
1944 buffer.edit([(ix..ix, "\n\n.d")], Some(AutoindentMode::EachLine), cx);
1945 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n \n .d\n}");
1946
1947 // dedent the line after the field expression
1948 let ix = buffer.len() - 2;
1949 buffer.edit([(ix..ix, ";\ne")], Some(AutoindentMode::EachLine), cx);
1950 assert_eq!(
1951 buffer.text(),
1952 "fn a() {\n b\n .c\n \n .d;\n e\n}"
1953 );
1954
1955 // indent inside a struct within a call
1956 buffer.set_text("const a: B = c(D {});", cx);
1957 let ix = buffer.len() - 3;
1958 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1959 assert_eq!(buffer.text(), "const a: B = c(D {\n \n});");
1960
1961 // indent further inside a nested call
1962 let ix = buffer.len() - 4;
1963 buffer.edit([(ix..ix, "e: f(\n\n)")], Some(AutoindentMode::EachLine), cx);
1964 assert_eq!(buffer.text(), "const a: B = c(D {\n e: f(\n \n )\n});");
1965
1966 // keep that indent after an empty line
1967 let ix = buffer.len() - 8;
1968 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1969 assert_eq!(
1970 buffer.text(),
1971 "const a: B = c(D {\n e: f(\n \n \n )\n});"
1972 );
1973
1974 buffer
1975 });
1976 }
1977
1978 #[test]
1979 fn test_package_name_from_pkgid() {
1980 for (input, expected) in [
1981 (
1982 "path+file:///absolute/path/to/project/zed/crates/zed#0.131.0",
1983 "zed",
1984 ),
1985 (
1986 "path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0",
1987 "my-custom-package",
1988 ),
1989 ] {
1990 assert_eq!(package_name_from_pkgid(input), Some(expected));
1991 }
1992 }
1993
1994 #[test]
1995 fn test_target_info_from_metadata() {
1996 for (input, absolute_path, expected) in [
1997 (
1998 r#"{"packages":[{"id":"path+file:///absolute/path/to/project/zed/crates/zed#0.131.0","manifest_path":"/path/to/zed/Cargo.toml","targets":[{"name":"zed","kind":["bin"],"src_path":"/path/to/zed/src/main.rs"}]}]}"#,
1999 "/path/to/zed/src/main.rs",
2000 Some((
2001 Some(TargetInfo {
2002 package_name: "zed".into(),
2003 target_name: "zed".into(),
2004 required_features: Vec::new(),
2005 target_kind: TargetKind::Bin,
2006 }),
2007 Arc::from("/path/to/zed".as_ref()),
2008 )),
2009 ),
2010 (
2011 r#"{"packages":[{"id":"path+file:///path/to/custom-package#my-custom-package@0.1.0","manifest_path":"/path/to/custom-package/Cargo.toml","targets":[{"name":"my-custom-bin","kind":["bin"],"src_path":"/path/to/custom-package/src/main.rs"}]}]}"#,
2012 "/path/to/custom-package/src/main.rs",
2013 Some((
2014 Some(TargetInfo {
2015 package_name: "my-custom-package".into(),
2016 target_name: "my-custom-bin".into(),
2017 required_features: Vec::new(),
2018 target_kind: TargetKind::Bin,
2019 }),
2020 Arc::from("/path/to/custom-package".as_ref()),
2021 )),
2022 ),
2023 (
2024 r#"{"packages":[{"id":"path+file:///path/to/custom-package#my-custom-package@0.1.0","targets":[{"name":"my-custom-bin","kind":["example"],"src_path":"/path/to/custom-package/src/main.rs"}],"manifest_path":"/path/to/custom-package/Cargo.toml"}]}"#,
2025 "/path/to/custom-package/src/main.rs",
2026 Some((
2027 Some(TargetInfo {
2028 package_name: "my-custom-package".into(),
2029 target_name: "my-custom-bin".into(),
2030 required_features: Vec::new(),
2031 target_kind: TargetKind::Example,
2032 }),
2033 Arc::from("/path/to/custom-package".as_ref()),
2034 )),
2035 ),
2036 (
2037 r#"{"packages":[{"id":"path+file:///path/to/custom-package#my-custom-package@0.1.0","manifest_path":"/path/to/custom-package/Cargo.toml","targets":[{"name":"my-custom-bin","kind":["example"],"src_path":"/path/to/custom-package/src/main.rs","required-features":["foo","bar"]}]}]}"#,
2038 "/path/to/custom-package/src/main.rs",
2039 Some((
2040 Some(TargetInfo {
2041 package_name: "my-custom-package".into(),
2042 target_name: "my-custom-bin".into(),
2043 required_features: vec!["foo".to_owned(), "bar".to_owned()],
2044 target_kind: TargetKind::Example,
2045 }),
2046 Arc::from("/path/to/custom-package".as_ref()),
2047 )),
2048 ),
2049 (
2050 r#"{"packages":[{"id":"path+file:///path/to/custom-package#my-custom-package@0.1.0","targets":[{"name":"my-custom-bin","kind":["example"],"src_path":"/path/to/custom-package/src/main.rs","required-features":[]}],"manifest_path":"/path/to/custom-package/Cargo.toml"}]}"#,
2051 "/path/to/custom-package/src/main.rs",
2052 Some((
2053 Some(TargetInfo {
2054 package_name: "my-custom-package".into(),
2055 target_name: "my-custom-bin".into(),
2056 required_features: vec![],
2057 target_kind: TargetKind::Example,
2058 }),
2059 Arc::from("/path/to/custom-package".as_ref()),
2060 )),
2061 ),
2062 (
2063 r#"{"packages":[{"id":"path+file:///path/to/custom-package#my-custom-package@0.1.0","targets":[{"name":"my-custom-package","kind":["lib"],"src_path":"/path/to/custom-package/src/main.rs"}],"manifest_path":"/path/to/custom-package/Cargo.toml"}]}"#,
2064 "/path/to/custom-package/src/main.rs",
2065 Some((None, Arc::from("/path/to/custom-package".as_ref()))),
2066 ),
2067 ] {
2068 let metadata: CargoMetadata = serde_json::from_str(input).context(input).unwrap();
2069
2070 let absolute_path = Path::new(absolute_path);
2071
2072 assert_eq!(target_info_from_metadata(metadata, absolute_path), expected);
2073 }
2074 }
2075
2076 #[test]
2077 fn test_rust_test_fragment() {
2078 #[track_caller]
2079 fn check(
2080 variables: impl IntoIterator<Item = (VariableName, &'static str)>,
2081 path: &str,
2082 expected: &str,
2083 ) {
2084 let path = Path::new(path);
2085 let found = test_fragment(
2086 &TaskVariables::from_iter(variables.into_iter().map(|(k, v)| (k, v.to_owned()))),
2087 path,
2088 path.file_stem().unwrap().to_str().unwrap(),
2089 );
2090 assert_eq!(expected, found);
2091 }
2092
2093 check([], "/project/src/lib.rs", "--lib");
2094 check([], "/project/src/foo/mod.rs", "foo");
2095 check(
2096 [
2097 (RUST_BIN_KIND_TASK_VARIABLE.clone(), "bin"),
2098 (RUST_BIN_NAME_TASK_VARIABLE, "x"),
2099 ],
2100 "/project/src/main.rs",
2101 "--bin=x",
2102 );
2103 check([], "/project/src/main.rs", "--");
2104 }
2105
2106 #[test]
2107 fn test_convert_rust_analyzer_schema() {
2108 let raw_schema = serde_json::json!([
2109 {
2110 "title": "Assist",
2111 "properties": {
2112 "rust-analyzer.assist.emitMustUse": {
2113 "markdownDescription": "Insert #[must_use] when generating `as_` methods for enum variants.",
2114 "default": false,
2115 "type": "boolean"
2116 }
2117 }
2118 },
2119 {
2120 "title": "Assist",
2121 "properties": {
2122 "rust-analyzer.assist.expressionFillDefault": {
2123 "markdownDescription": "Placeholder expression to use for missing expressions in assists.",
2124 "default": "todo",
2125 "type": "string"
2126 }
2127 }
2128 },
2129 {
2130 "title": "Cache Priming",
2131 "properties": {
2132 "rust-analyzer.cachePriming.enable": {
2133 "markdownDescription": "Warm up caches on project load.",
2134 "default": true,
2135 "type": "boolean"
2136 }
2137 }
2138 }
2139 ]);
2140
2141 let converted = RustLspAdapter::convert_rust_analyzer_schema(&raw_schema);
2142
2143 assert_eq!(
2144 converted.get("type").and_then(|v| v.as_str()),
2145 Some("object")
2146 );
2147
2148 let properties = converted
2149 .pointer("/properties")
2150 .expect("should have properties")
2151 .as_object()
2152 .expect("properties should be object");
2153
2154 assert!(properties.contains_key("assist"));
2155 assert!(properties.contains_key("cachePriming"));
2156 assert!(!properties.contains_key("rust-analyzer"));
2157
2158 let assist_props = properties
2159 .get("assist")
2160 .expect("should have assist")
2161 .pointer("/properties")
2162 .expect("assist should have properties")
2163 .as_object()
2164 .expect("assist properties should be object");
2165
2166 assert!(assist_props.contains_key("emitMustUse"));
2167 assert!(assist_props.contains_key("expressionFillDefault"));
2168
2169 let emit_must_use = assist_props
2170 .get("emitMustUse")
2171 .expect("should have emitMustUse");
2172 assert_eq!(
2173 emit_must_use.get("type").and_then(|v| v.as_str()),
2174 Some("boolean")
2175 );
2176 assert_eq!(
2177 emit_must_use.get("default").and_then(|v| v.as_bool()),
2178 Some(false)
2179 );
2180
2181 let cache_priming_props = properties
2182 .get("cachePriming")
2183 .expect("should have cachePriming")
2184 .pointer("/properties")
2185 .expect("cachePriming should have properties")
2186 .as_object()
2187 .expect("cachePriming properties should be object");
2188
2189 assert!(cache_priming_props.contains_key("enable"));
2190 }
2191}