1use anyhow::{Context as _, Result};
2use async_trait::async_trait;
3use collections::HashMap;
4use futures::StreamExt;
5use gpui::{App, AppContext, AsyncApp, SharedString, Task};
6use http_client::github::AssetKind;
7use http_client::github::{GitHubLspBinaryVersion, latest_github_release};
8use http_client::github_download::{GithubBinaryMetadata, download_server_binary};
9pub use language::*;
10use lsp::{InitializeParams, LanguageServerBinary};
11use project::lsp_store::rust_analyzer_ext::CARGO_DIAGNOSTICS_SOURCE_NAME;
12use project::project_settings::ProjectSettings;
13use regex::Regex;
14use serde_json::json;
15use settings::Settings as _;
16use smol::fs::{self};
17use std::fmt::Display;
18use std::ops::Range;
19use std::{
20 borrow::Cow,
21 path::{Path, PathBuf},
22 sync::{Arc, LazyLock},
23};
24use task::{TaskTemplate, TaskTemplates, TaskVariables, VariableName};
25use util::fs::{make_file_executable, remove_matching};
26use util::merge_json_value_into;
27use util::rel_path::RelPath;
28use util::{ResultExt, maybe};
29
30use crate::language_settings::language_settings;
31
32pub struct RustLspAdapter;
33
34#[cfg(target_os = "macos")]
35impl RustLspAdapter {
36 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Gz;
37 const ARCH_SERVER_NAME: &str = "apple-darwin";
38}
39
40#[cfg(target_os = "linux")]
41impl RustLspAdapter {
42 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Gz;
43 const ARCH_SERVER_NAME: &str = "unknown-linux";
44}
45
46#[cfg(target_os = "freebsd")]
47impl RustLspAdapter {
48 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Gz;
49 const ARCH_SERVER_NAME: &str = "unknown-freebsd";
50}
51
52#[cfg(target_os = "windows")]
53impl RustLspAdapter {
54 const GITHUB_ASSET_KIND: AssetKind = AssetKind::Zip;
55 const ARCH_SERVER_NAME: &str = "pc-windows-msvc";
56}
57
58const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("rust-analyzer");
59
60#[cfg(target_os = "linux")]
61enum LibcType {
62 Gnu,
63 Musl,
64}
65
66impl RustLspAdapter {
67 #[cfg(target_os = "linux")]
68 async fn determine_libc_type() -> LibcType {
69 use futures::pin_mut;
70 use smol::process::Command;
71
72 async fn from_ldd_version() -> Option<LibcType> {
73 let ldd_output = Command::new("ldd").arg("--version").output().await.ok()?;
74 let ldd_version = String::from_utf8_lossy(&ldd_output.stdout);
75
76 if ldd_version.contains("GNU libc") || ldd_version.contains("GLIBC") {
77 Some(LibcType::Gnu)
78 } else if ldd_version.contains("musl") {
79 Some(LibcType::Musl)
80 } else {
81 None
82 }
83 }
84
85 if let Some(libc_type) = from_ldd_version().await {
86 return libc_type;
87 }
88
89 let Ok(dir_entries) = smol::fs::read_dir("/lib").await else {
90 // defaulting to gnu because nix doesn't have /lib files due to not following FHS
91 return LibcType::Gnu;
92 };
93 let dir_entries = dir_entries.filter_map(async move |e| e.ok());
94 pin_mut!(dir_entries);
95
96 let mut has_musl = false;
97 let mut has_gnu = false;
98
99 while let Some(entry) = dir_entries.next().await {
100 let file_name = entry.file_name();
101 let file_name = file_name.to_string_lossy();
102 if file_name.starts_with("ld-musl-") {
103 has_musl = true;
104 } else if file_name.starts_with("ld-linux-") {
105 has_gnu = true;
106 }
107 }
108
109 match (has_musl, has_gnu) {
110 (true, _) => LibcType::Musl,
111 (_, true) => LibcType::Gnu,
112 _ => LibcType::Gnu,
113 }
114 }
115
116 #[cfg(target_os = "linux")]
117 async fn build_arch_server_name_linux() -> String {
118 let libc = match Self::determine_libc_type().await {
119 LibcType::Musl => "musl",
120 LibcType::Gnu => "gnu",
121 };
122
123 format!("{}-{}", Self::ARCH_SERVER_NAME, libc)
124 }
125
126 async fn build_asset_name() -> String {
127 let extension = match Self::GITHUB_ASSET_KIND {
128 AssetKind::TarGz => "tar.gz",
129 AssetKind::Gz => "gz",
130 AssetKind::Zip => "zip",
131 };
132
133 #[cfg(target_os = "linux")]
134 let arch_server_name = Self::build_arch_server_name_linux().await;
135 #[cfg(not(target_os = "linux"))]
136 let arch_server_name = Self::ARCH_SERVER_NAME.to_string();
137
138 format!(
139 "{}-{}-{}.{}",
140 SERVER_NAME,
141 std::env::consts::ARCH,
142 &arch_server_name,
143 extension
144 )
145 }
146}
147
148pub(crate) struct CargoManifestProvider;
149
150impl ManifestProvider for CargoManifestProvider {
151 fn name(&self) -> ManifestName {
152 SharedString::new_static("Cargo.toml").into()
153 }
154
155 fn search(
156 &self,
157 ManifestQuery {
158 path,
159 depth,
160 delegate,
161 }: ManifestQuery,
162 ) -> Option<Arc<RelPath>> {
163 let mut outermost_cargo_toml = None;
164 for path in path.ancestors().take(depth) {
165 let p = path.join(RelPath::unix("Cargo.toml").unwrap());
166 if delegate.exists(&p, Some(false)) {
167 outermost_cargo_toml = Some(Arc::from(path));
168 }
169 }
170
171 outermost_cargo_toml
172 }
173}
174
175#[async_trait(?Send)]
176impl LspAdapter for RustLspAdapter {
177 fn name(&self) -> LanguageServerName {
178 SERVER_NAME
179 }
180
181 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
182 vec![CARGO_DIAGNOSTICS_SOURCE_NAME.to_owned()]
183 }
184
185 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
186 Some("rust-analyzer/flycheck".into())
187 }
188
189 fn process_diagnostics(
190 &self,
191 params: &mut lsp::PublishDiagnosticsParams,
192 _: LanguageServerId,
193 _: Option<&'_ Buffer>,
194 ) {
195 static REGEX: LazyLock<Regex> =
196 LazyLock::new(|| Regex::new(r"(?m)`([^`]+)\n`$").expect("Failed to create REGEX"));
197
198 for diagnostic in &mut params.diagnostics {
199 for message in diagnostic
200 .related_information
201 .iter_mut()
202 .flatten()
203 .map(|info| &mut info.message)
204 .chain([&mut diagnostic.message])
205 {
206 if let Cow::Owned(sanitized) = REGEX.replace_all(message, "`$1`") {
207 *message = sanitized;
208 }
209 }
210 }
211 }
212
213 fn diagnostic_message_to_markdown(&self, message: &str) -> Option<String> {
214 static REGEX: LazyLock<Regex> =
215 LazyLock::new(|| Regex::new(r"(?m)\n *").expect("Failed to create REGEX"));
216 Some(REGEX.replace_all(message, "\n\n").to_string())
217 }
218
219 async fn label_for_completion(
220 &self,
221 completion: &lsp::CompletionItem,
222 language: &Arc<Language>,
223 ) -> Option<CodeLabel> {
224 // rust-analyzer calls these detail left and detail right in terms of where it expects things to be rendered
225 // this usually contains signatures of the thing to be completed
226 let detail_right = completion
227 .label_details
228 .as_ref()
229 .and_then(|detail| detail.description.as_ref())
230 .or(completion.detail.as_ref())
231 .map(|detail| detail.trim());
232 // this tends to contain alias and import information
233 let detail_left = completion
234 .label_details
235 .as_ref()
236 .and_then(|detail| detail.detail.as_deref());
237 let mk_label = |text: String, filter_range: &dyn Fn() -> Range<usize>, runs| {
238 let filter_range = completion
239 .filter_text
240 .as_deref()
241 .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
242 .or_else(|| {
243 text.find(&completion.label)
244 .map(|ix| ix..ix + completion.label.len())
245 })
246 .unwrap_or_else(filter_range);
247
248 CodeLabel::new(text, filter_range, runs)
249 };
250 let mut label = match (detail_right, completion.kind) {
251 (Some(signature), Some(lsp::CompletionItemKind::FIELD)) => {
252 let name = &completion.label;
253 let text = format!("{name}: {signature}");
254 let prefix = "struct S { ";
255 let source = Rope::from_iter([prefix, &text, " }"]);
256 let runs =
257 language.highlight_text(&source, prefix.len()..prefix.len() + text.len());
258 mk_label(text, &|| 0..completion.label.len(), runs)
259 }
260 (
261 Some(signature),
262 Some(lsp::CompletionItemKind::CONSTANT | lsp::CompletionItemKind::VARIABLE),
263 ) if completion.insert_text_format != Some(lsp::InsertTextFormat::SNIPPET) => {
264 let name = &completion.label;
265 let text = format!("{name}: {signature}",);
266 let prefix = "let ";
267 let source = Rope::from_iter([prefix, &text, " = ();"]);
268 let runs =
269 language.highlight_text(&source, prefix.len()..prefix.len() + text.len());
270 mk_label(text, &|| 0..completion.label.len(), runs)
271 }
272 (
273 function_signature,
274 Some(lsp::CompletionItemKind::FUNCTION | lsp::CompletionItemKind::METHOD),
275 ) => {
276 const FUNCTION_PREFIXES: [&str; 6] = [
277 "async fn",
278 "async unsafe fn",
279 "const fn",
280 "const unsafe fn",
281 "unsafe fn",
282 "fn",
283 ];
284 let fn_prefixed = FUNCTION_PREFIXES.iter().find_map(|&prefix| {
285 function_signature?
286 .strip_prefix(prefix)
287 .map(|suffix| (prefix, suffix))
288 });
289 let label = if let Some(label) = completion
290 .label
291 .strip_suffix("(…)")
292 .or_else(|| completion.label.strip_suffix("()"))
293 {
294 label
295 } else {
296 &completion.label
297 };
298
299 static FULL_SIGNATURE_REGEX: LazyLock<Regex> =
300 LazyLock::new(|| Regex::new(r"fn (.?+)\(").expect("Failed to create REGEX"));
301 if let Some((function_signature, match_)) = function_signature
302 .filter(|it| it.contains(&label))
303 .and_then(|it| Some((it, FULL_SIGNATURE_REGEX.find(it)?)))
304 {
305 let source = Rope::from(function_signature);
306 let runs = language.highlight_text(&source, 0..function_signature.len());
307 mk_label(
308 function_signature.to_owned(),
309 &|| match_.range().start - 3..match_.range().end - 1,
310 runs,
311 )
312 } else if let Some((prefix, suffix)) = fn_prefixed {
313 let text = format!("{label}{suffix}");
314 let source = Rope::from_iter([prefix, " ", &text, " {}"]);
315 let run_start = prefix.len() + 1;
316 let runs = language.highlight_text(&source, run_start..run_start + text.len());
317 mk_label(text, &|| 0..label.len(), runs)
318 } else if completion
319 .detail
320 .as_ref()
321 .is_some_and(|detail| detail.starts_with("macro_rules! "))
322 {
323 let text = completion.label.clone();
324 let len = text.len();
325 let source = Rope::from(text.as_str());
326 let runs = language.highlight_text(&source, 0..len);
327 mk_label(text, &|| 0..completion.label.len(), runs)
328 } else if detail_left.is_none() {
329 return None;
330 } else {
331 mk_label(
332 completion.label.clone(),
333 &|| 0..completion.label.len(),
334 vec![],
335 )
336 }
337 }
338 (_, kind) => {
339 let highlight_name = kind.and_then(|kind| match kind {
340 lsp::CompletionItemKind::STRUCT
341 | lsp::CompletionItemKind::INTERFACE
342 | lsp::CompletionItemKind::ENUM => Some("type"),
343 lsp::CompletionItemKind::ENUM_MEMBER => Some("variant"),
344 lsp::CompletionItemKind::KEYWORD => Some("keyword"),
345 lsp::CompletionItemKind::VALUE | lsp::CompletionItemKind::CONSTANT => {
346 Some("constant")
347 }
348 _ => None,
349 });
350
351 let label = completion.label.clone();
352 let mut runs = vec![];
353 if let Some(highlight_name) = highlight_name {
354 let highlight_id = language.grammar()?.highlight_id_for_name(highlight_name)?;
355 runs.push((
356 0..label.rfind('(').unwrap_or(completion.label.len()),
357 highlight_id,
358 ));
359 } else if detail_left.is_none() {
360 return None;
361 }
362
363 mk_label(label, &|| 0..completion.label.len(), runs)
364 }
365 };
366
367 if let Some(detail_left) = detail_left {
368 label.text.push(' ');
369 if !detail_left.starts_with('(') {
370 label.text.push('(');
371 }
372 label.text.push_str(detail_left);
373 if !detail_left.ends_with(')') {
374 label.text.push(')');
375 }
376 }
377 Some(label)
378 }
379
380 async fn label_for_symbol(
381 &self,
382 name: &str,
383 kind: lsp::SymbolKind,
384 language: &Arc<Language>,
385 ) -> Option<CodeLabel> {
386 let (prefix, suffix) = match kind {
387 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => ("fn ", " () {}"),
388 lsp::SymbolKind::STRUCT => ("struct ", " {}"),
389 lsp::SymbolKind::ENUM => ("enum ", " {}"),
390 lsp::SymbolKind::INTERFACE => ("trait ", " {}"),
391 lsp::SymbolKind::CONSTANT => ("const ", ": () = ();"),
392 lsp::SymbolKind::MODULE => ("mod ", " {}"),
393 lsp::SymbolKind::TYPE_PARAMETER => ("type ", " {}"),
394 _ => return None,
395 };
396
397 let filter_range = prefix.len()..prefix.len() + name.len();
398 let display_range = 0..filter_range.end;
399 Some(CodeLabel::new(
400 format!("{prefix}{name}"),
401 filter_range,
402 language.highlight_text(&Rope::from_iter([prefix, name, suffix]), display_range),
403 ))
404 }
405
406 fn prepare_initialize_params(
407 &self,
408 mut original: InitializeParams,
409 cx: &App,
410 ) -> Result<InitializeParams> {
411 let enable_lsp_tasks = ProjectSettings::get_global(cx)
412 .lsp
413 .get(&SERVER_NAME)
414 .is_some_and(|s| s.enable_lsp_tasks);
415 if enable_lsp_tasks {
416 let experimental = json!({
417 "runnables": {
418 "kinds": [ "cargo", "shell" ],
419 },
420 });
421 if let Some(original_experimental) = &mut original.capabilities.experimental {
422 merge_json_value_into(experimental, original_experimental);
423 } else {
424 original.capabilities.experimental = Some(experimental);
425 }
426 }
427
428 Ok(original)
429 }
430}
431
432impl LspInstaller for RustLspAdapter {
433 type BinaryVersion = GitHubLspBinaryVersion;
434 async fn check_if_user_installed(
435 &self,
436 delegate: &dyn LspAdapterDelegate,
437 _: Option<Toolchain>,
438 _: &AsyncApp,
439 ) -> Option<LanguageServerBinary> {
440 let path = delegate.which("rust-analyzer".as_ref()).await?;
441 let env = delegate.shell_env().await;
442
443 // It is surprisingly common for ~/.cargo/bin/rust-analyzer to be a symlink to
444 // /usr/bin/rust-analyzer that fails when you run it; so we need to test it.
445 log::info!("found rust-analyzer in PATH. trying to run `rust-analyzer --help`");
446 let result = delegate
447 .try_exec(LanguageServerBinary {
448 path: path.clone(),
449 arguments: vec!["--help".into()],
450 env: Some(env.clone()),
451 })
452 .await;
453 if let Err(err) = result {
454 log::debug!(
455 "failed to run rust-analyzer after detecting it in PATH: binary: {:?}: {}",
456 path,
457 err
458 );
459 return None;
460 }
461
462 Some(LanguageServerBinary {
463 path,
464 env: Some(env),
465 arguments: vec![],
466 })
467 }
468
469 async fn fetch_latest_server_version(
470 &self,
471 delegate: &dyn LspAdapterDelegate,
472 pre_release: bool,
473 _: &mut AsyncApp,
474 ) -> Result<GitHubLspBinaryVersion> {
475 let release = latest_github_release(
476 "rust-lang/rust-analyzer",
477 true,
478 pre_release,
479 delegate.http_client(),
480 )
481 .await?;
482 let asset_name = Self::build_asset_name().await;
483 let asset = release
484 .assets
485 .into_iter()
486 .find(|asset| asset.name == asset_name)
487 .with_context(|| format!("no asset found matching `{asset_name:?}`"))?;
488 Ok(GitHubLspBinaryVersion {
489 name: release.tag_name,
490 url: asset.browser_download_url,
491 digest: asset.digest,
492 })
493 }
494
495 async fn fetch_server_binary(
496 &self,
497 version: GitHubLspBinaryVersion,
498 container_dir: PathBuf,
499 delegate: &dyn LspAdapterDelegate,
500 ) -> Result<LanguageServerBinary> {
501 let GitHubLspBinaryVersion {
502 name,
503 url,
504 digest: expected_digest,
505 } = version;
506 let destination_path = container_dir.join(format!("rust-analyzer-{name}"));
507 let server_path = match Self::GITHUB_ASSET_KIND {
508 AssetKind::TarGz | AssetKind::Gz => destination_path.clone(), // Tar and gzip extract in place.
509 AssetKind::Zip => destination_path.clone().join("rust-analyzer.exe"), // zip contains a .exe
510 };
511
512 let binary = LanguageServerBinary {
513 path: server_path.clone(),
514 env: None,
515 arguments: Default::default(),
516 };
517
518 let metadata_path = destination_path.with_extension("metadata");
519 let metadata = GithubBinaryMetadata::read_from_file(&metadata_path)
520 .await
521 .ok();
522 if let Some(metadata) = metadata {
523 let validity_check = async || {
524 delegate
525 .try_exec(LanguageServerBinary {
526 path: server_path.clone(),
527 arguments: vec!["--version".into()],
528 env: None,
529 })
530 .await
531 .inspect_err(|err| {
532 log::warn!("Unable to run {server_path:?} asset, redownloading: {err}",)
533 })
534 };
535 if let (Some(actual_digest), Some(expected_digest)) =
536 (&metadata.digest, &expected_digest)
537 {
538 if actual_digest == expected_digest {
539 if validity_check().await.is_ok() {
540 return Ok(binary);
541 }
542 } else {
543 log::info!(
544 "SHA-256 mismatch for {destination_path:?} asset, downloading new asset. Expected: {expected_digest}, Got: {actual_digest}"
545 );
546 }
547 } else if validity_check().await.is_ok() {
548 return Ok(binary);
549 }
550 }
551
552 download_server_binary(
553 &*delegate.http_client(),
554 &url,
555 expected_digest.as_deref(),
556 &destination_path,
557 Self::GITHUB_ASSET_KIND,
558 )
559 .await?;
560 make_file_executable(&server_path).await?;
561 remove_matching(&container_dir, |path| path != destination_path).await;
562 GithubBinaryMetadata::write_to_file(
563 &GithubBinaryMetadata {
564 metadata_version: 1,
565 digest: expected_digest,
566 },
567 &metadata_path,
568 )
569 .await?;
570
571 Ok(LanguageServerBinary {
572 path: server_path,
573 env: None,
574 arguments: Default::default(),
575 })
576 }
577
578 async fn cached_server_binary(
579 &self,
580 container_dir: PathBuf,
581 _: &dyn LspAdapterDelegate,
582 ) -> Option<LanguageServerBinary> {
583 get_cached_server_binary(container_dir).await
584 }
585}
586
587pub(crate) struct RustContextProvider;
588
589const RUST_PACKAGE_TASK_VARIABLE: VariableName =
590 VariableName::Custom(Cow::Borrowed("RUST_PACKAGE"));
591
592/// The bin name corresponding to the current file in Cargo.toml
593const RUST_BIN_NAME_TASK_VARIABLE: VariableName =
594 VariableName::Custom(Cow::Borrowed("RUST_BIN_NAME"));
595
596/// The bin kind (bin/example) corresponding to the current file in Cargo.toml
597const RUST_BIN_KIND_TASK_VARIABLE: VariableName =
598 VariableName::Custom(Cow::Borrowed("RUST_BIN_KIND"));
599
600/// The flag to list required features for executing a bin, if any
601const RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE: VariableName =
602 VariableName::Custom(Cow::Borrowed("RUST_BIN_REQUIRED_FEATURES_FLAG"));
603
604/// The list of required features for executing a bin, if any
605const RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE: VariableName =
606 VariableName::Custom(Cow::Borrowed("RUST_BIN_REQUIRED_FEATURES"));
607
608const RUST_TEST_FRAGMENT_TASK_VARIABLE: VariableName =
609 VariableName::Custom(Cow::Borrowed("RUST_TEST_FRAGMENT"));
610
611const RUST_DOC_TEST_NAME_TASK_VARIABLE: VariableName =
612 VariableName::Custom(Cow::Borrowed("RUST_DOC_TEST_NAME"));
613
614const RUST_TEST_NAME_TASK_VARIABLE: VariableName =
615 VariableName::Custom(Cow::Borrowed("RUST_TEST_NAME"));
616
617const RUST_MANIFEST_DIRNAME_TASK_VARIABLE: VariableName =
618 VariableName::Custom(Cow::Borrowed("RUST_MANIFEST_DIRNAME"));
619
620impl ContextProvider for RustContextProvider {
621 fn build_context(
622 &self,
623 task_variables: &TaskVariables,
624 location: ContextLocation<'_>,
625 project_env: Option<HashMap<String, String>>,
626 _: Arc<dyn LanguageToolchainStore>,
627 cx: &mut gpui::App,
628 ) -> Task<Result<TaskVariables>> {
629 let local_abs_path = location
630 .file_location
631 .buffer
632 .read(cx)
633 .file()
634 .and_then(|file| Some(file.as_local()?.abs_path(cx)));
635
636 let mut variables = TaskVariables::default();
637
638 if let (Some(path), Some(stem)) = (&local_abs_path, task_variables.get(&VariableName::Stem))
639 {
640 let fragment = test_fragment(&variables, path, stem);
641 variables.insert(RUST_TEST_FRAGMENT_TASK_VARIABLE, fragment);
642 };
643 if let Some(test_name) =
644 task_variables.get(&VariableName::Custom(Cow::Borrowed("_test_name")))
645 {
646 variables.insert(RUST_TEST_NAME_TASK_VARIABLE, test_name.into());
647 }
648 if let Some(doc_test_name) =
649 task_variables.get(&VariableName::Custom(Cow::Borrowed("_doc_test_name")))
650 {
651 variables.insert(RUST_DOC_TEST_NAME_TASK_VARIABLE, doc_test_name.into());
652 }
653 cx.background_spawn(async move {
654 if let Some(path) = local_abs_path
655 .as_deref()
656 .and_then(|local_abs_path| local_abs_path.parent())
657 && let Some(package_name) =
658 human_readable_package_name(path, project_env.as_ref()).await
659 {
660 variables.insert(RUST_PACKAGE_TASK_VARIABLE.clone(), package_name);
661 }
662 if let Some(path) = local_abs_path.as_ref()
663 && let Some((target, manifest_path)) =
664 target_info_from_abs_path(path, project_env.as_ref()).await
665 {
666 if let Some(target) = target {
667 variables.extend(TaskVariables::from_iter([
668 (RUST_PACKAGE_TASK_VARIABLE.clone(), target.package_name),
669 (RUST_BIN_NAME_TASK_VARIABLE.clone(), target.target_name),
670 (
671 RUST_BIN_KIND_TASK_VARIABLE.clone(),
672 target.target_kind.to_string(),
673 ),
674 ]));
675 if target.required_features.is_empty() {
676 variables.insert(RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE, "".into());
677 variables.insert(RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE, "".into());
678 } else {
679 variables.insert(
680 RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE.clone(),
681 "--features".to_string(),
682 );
683 variables.insert(
684 RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE.clone(),
685 target.required_features.join(","),
686 );
687 }
688 }
689 variables.extend(TaskVariables::from_iter([(
690 RUST_MANIFEST_DIRNAME_TASK_VARIABLE.clone(),
691 manifest_path.to_string_lossy().into_owned(),
692 )]));
693 }
694 Ok(variables)
695 })
696 }
697
698 fn associated_tasks(
699 &self,
700 file: Option<Arc<dyn language::File>>,
701 cx: &App,
702 ) -> Task<Option<TaskTemplates>> {
703 const DEFAULT_RUN_NAME_STR: &str = "RUST_DEFAULT_PACKAGE_RUN";
704 const CUSTOM_TARGET_DIR: &str = "RUST_TARGET_DIR";
705
706 let language_sets = language_settings(Some("Rust".into()), file.as_ref(), cx);
707 let package_to_run = language_sets
708 .tasks
709 .variables
710 .get(DEFAULT_RUN_NAME_STR)
711 .cloned();
712 let custom_target_dir = language_sets
713 .tasks
714 .variables
715 .get(CUSTOM_TARGET_DIR)
716 .cloned();
717 let run_task_args = if let Some(package_to_run) = package_to_run {
718 vec!["run".into(), "-p".into(), package_to_run]
719 } else {
720 vec!["run".into()]
721 };
722 let mut task_templates = vec![
723 TaskTemplate {
724 label: format!(
725 "Check (package: {})",
726 RUST_PACKAGE_TASK_VARIABLE.template_value(),
727 ),
728 command: "cargo".into(),
729 args: vec![
730 "check".into(),
731 "-p".into(),
732 RUST_PACKAGE_TASK_VARIABLE.template_value(),
733 ],
734 cwd: Some("$ZED_DIRNAME".to_owned()),
735 ..TaskTemplate::default()
736 },
737 TaskTemplate {
738 label: "Check all targets (workspace)".into(),
739 command: "cargo".into(),
740 args: vec!["check".into(), "--workspace".into(), "--all-targets".into()],
741 cwd: Some("$ZED_DIRNAME".to_owned()),
742 ..TaskTemplate::default()
743 },
744 TaskTemplate {
745 label: format!(
746 "Test '{}' (package: {})",
747 RUST_TEST_NAME_TASK_VARIABLE.template_value(),
748 RUST_PACKAGE_TASK_VARIABLE.template_value(),
749 ),
750 command: "cargo".into(),
751 args: vec![
752 "test".into(),
753 "-p".into(),
754 RUST_PACKAGE_TASK_VARIABLE.template_value(),
755 "--".into(),
756 "--nocapture".into(),
757 "--include-ignored".into(),
758 RUST_TEST_NAME_TASK_VARIABLE.template_value(),
759 ],
760 tags: vec!["rust-test".to_owned()],
761 cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
762 ..TaskTemplate::default()
763 },
764 TaskTemplate {
765 label: format!(
766 "Doc test '{}' (package: {})",
767 RUST_DOC_TEST_NAME_TASK_VARIABLE.template_value(),
768 RUST_PACKAGE_TASK_VARIABLE.template_value(),
769 ),
770 command: "cargo".into(),
771 args: vec![
772 "test".into(),
773 "--doc".into(),
774 "-p".into(),
775 RUST_PACKAGE_TASK_VARIABLE.template_value(),
776 "--".into(),
777 "--nocapture".into(),
778 "--include-ignored".into(),
779 RUST_DOC_TEST_NAME_TASK_VARIABLE.template_value(),
780 ],
781 tags: vec!["rust-doc-test".to_owned()],
782 cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
783 ..TaskTemplate::default()
784 },
785 TaskTemplate {
786 label: format!(
787 "Test mod '{}' (package: {})",
788 VariableName::Stem.template_value(),
789 RUST_PACKAGE_TASK_VARIABLE.template_value(),
790 ),
791 command: "cargo".into(),
792 args: vec![
793 "test".into(),
794 "-p".into(),
795 RUST_PACKAGE_TASK_VARIABLE.template_value(),
796 "--".into(),
797 RUST_TEST_FRAGMENT_TASK_VARIABLE.template_value(),
798 ],
799 tags: vec!["rust-mod-test".to_owned()],
800 cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
801 ..TaskTemplate::default()
802 },
803 TaskTemplate {
804 label: format!(
805 "Run {} {} (package: {})",
806 RUST_BIN_KIND_TASK_VARIABLE.template_value(),
807 RUST_BIN_NAME_TASK_VARIABLE.template_value(),
808 RUST_PACKAGE_TASK_VARIABLE.template_value(),
809 ),
810 command: "cargo".into(),
811 args: vec![
812 "run".into(),
813 "-p".into(),
814 RUST_PACKAGE_TASK_VARIABLE.template_value(),
815 format!("--{}", RUST_BIN_KIND_TASK_VARIABLE.template_value()),
816 RUST_BIN_NAME_TASK_VARIABLE.template_value(),
817 RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE.template_value(),
818 RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE.template_value(),
819 ],
820 cwd: Some("$ZED_DIRNAME".to_owned()),
821 tags: vec!["rust-main".to_owned()],
822 ..TaskTemplate::default()
823 },
824 TaskTemplate {
825 label: format!(
826 "Test (package: {})",
827 RUST_PACKAGE_TASK_VARIABLE.template_value()
828 ),
829 command: "cargo".into(),
830 args: vec![
831 "test".into(),
832 "-p".into(),
833 RUST_PACKAGE_TASK_VARIABLE.template_value(),
834 ],
835 cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
836 ..TaskTemplate::default()
837 },
838 TaskTemplate {
839 label: "Run".into(),
840 command: "cargo".into(),
841 args: run_task_args,
842 cwd: Some("$ZED_DIRNAME".to_owned()),
843 ..TaskTemplate::default()
844 },
845 TaskTemplate {
846 label: "Clean".into(),
847 command: "cargo".into(),
848 args: vec!["clean".into()],
849 cwd: Some("$ZED_DIRNAME".to_owned()),
850 ..TaskTemplate::default()
851 },
852 ];
853
854 if let Some(custom_target_dir) = custom_target_dir {
855 task_templates = task_templates
856 .into_iter()
857 .map(|mut task_template| {
858 let mut args = task_template.args.split_off(1);
859 task_template.args.append(&mut vec![
860 "--target-dir".to_string(),
861 custom_target_dir.clone(),
862 ]);
863 task_template.args.append(&mut args);
864
865 task_template
866 })
867 .collect();
868 }
869
870 Task::ready(Some(TaskTemplates(task_templates)))
871 }
872
873 fn lsp_task_source(&self) -> Option<LanguageServerName> {
874 Some(SERVER_NAME)
875 }
876}
877
878/// Part of the data structure of Cargo metadata
879#[derive(Debug, serde::Deserialize)]
880struct CargoMetadata {
881 packages: Vec<CargoPackage>,
882}
883
884#[derive(Debug, serde::Deserialize)]
885struct CargoPackage {
886 id: String,
887 targets: Vec<CargoTarget>,
888 manifest_path: Arc<Path>,
889}
890
891#[derive(Debug, serde::Deserialize)]
892struct CargoTarget {
893 name: String,
894 kind: Vec<String>,
895 src_path: String,
896 #[serde(rename = "required-features", default)]
897 required_features: Vec<String>,
898}
899
900#[derive(Debug, PartialEq)]
901enum TargetKind {
902 Bin,
903 Example,
904}
905
906impl Display for TargetKind {
907 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
908 match self {
909 TargetKind::Bin => write!(f, "bin"),
910 TargetKind::Example => write!(f, "example"),
911 }
912 }
913}
914
915impl TryFrom<&str> for TargetKind {
916 type Error = ();
917 fn try_from(value: &str) -> Result<Self, ()> {
918 match value {
919 "bin" => Ok(Self::Bin),
920 "example" => Ok(Self::Example),
921 _ => Err(()),
922 }
923 }
924}
925/// Which package and binary target are we in?
926#[derive(Debug, PartialEq)]
927struct TargetInfo {
928 package_name: String,
929 target_name: String,
930 target_kind: TargetKind,
931 required_features: Vec<String>,
932}
933
934async fn target_info_from_abs_path(
935 abs_path: &Path,
936 project_env: Option<&HashMap<String, String>>,
937) -> Option<(Option<TargetInfo>, Arc<Path>)> {
938 let mut command = util::command::new_smol_command("cargo");
939 if let Some(envs) = project_env {
940 command.envs(envs);
941 }
942 let output = command
943 .current_dir(abs_path.parent()?)
944 .arg("metadata")
945 .arg("--no-deps")
946 .arg("--format-version")
947 .arg("1")
948 .output()
949 .await
950 .log_err()?
951 .stdout;
952
953 let metadata: CargoMetadata = serde_json::from_slice(&output).log_err()?;
954 target_info_from_metadata(metadata, abs_path)
955}
956
957fn target_info_from_metadata(
958 metadata: CargoMetadata,
959 abs_path: &Path,
960) -> Option<(Option<TargetInfo>, Arc<Path>)> {
961 let mut manifest_path = None;
962 for package in metadata.packages {
963 let Some(manifest_dir_path) = package.manifest_path.parent() else {
964 continue;
965 };
966
967 let Some(path_from_manifest_dir) = abs_path.strip_prefix(manifest_dir_path).ok() else {
968 continue;
969 };
970 let candidate_path_length = path_from_manifest_dir.components().count();
971 // Pick the most specific manifest path
972 if let Some((path, current_length)) = &mut manifest_path {
973 if candidate_path_length > *current_length {
974 *path = Arc::from(manifest_dir_path);
975 *current_length = candidate_path_length;
976 }
977 } else {
978 manifest_path = Some((Arc::from(manifest_dir_path), candidate_path_length));
979 };
980
981 for target in package.targets {
982 let Some(bin_kind) = target
983 .kind
984 .iter()
985 .find_map(|kind| TargetKind::try_from(kind.as_ref()).ok())
986 else {
987 continue;
988 };
989 let target_path = PathBuf::from(target.src_path);
990 if target_path == abs_path {
991 return manifest_path.map(|(path, _)| {
992 (
993 package_name_from_pkgid(&package.id).map(|package_name| TargetInfo {
994 package_name: package_name.to_owned(),
995 target_name: target.name,
996 required_features: target.required_features,
997 target_kind: bin_kind,
998 }),
999 path,
1000 )
1001 });
1002 }
1003 }
1004 }
1005
1006 manifest_path.map(|(path, _)| (None, path))
1007}
1008
1009async fn human_readable_package_name(
1010 package_directory: &Path,
1011 project_env: Option<&HashMap<String, String>>,
1012) -> Option<String> {
1013 let mut command = util::command::new_smol_command("cargo");
1014 if let Some(envs) = project_env {
1015 command.envs(envs);
1016 }
1017 let pkgid = String::from_utf8(
1018 command
1019 .current_dir(package_directory)
1020 .arg("pkgid")
1021 .output()
1022 .await
1023 .log_err()?
1024 .stdout,
1025 )
1026 .ok()?;
1027 Some(package_name_from_pkgid(&pkgid)?.to_owned())
1028}
1029
1030// For providing local `cargo check -p $pkgid` task, we do not need most of the information we have returned.
1031// Output example in the root of Zed project:
1032// ```sh
1033// ❯ cargo pkgid zed
1034// path+file:///absolute/path/to/project/zed/crates/zed#0.131.0
1035// ```
1036// Another variant, if a project has a custom package name or hyphen in the name:
1037// ```
1038// path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0
1039// ```
1040//
1041// Extracts the package name from the output according to the spec:
1042// https://doc.rust-lang.org/cargo/reference/pkgid-spec.html#specification-grammar
1043fn package_name_from_pkgid(pkgid: &str) -> Option<&str> {
1044 fn split_off_suffix(input: &str, suffix_start: char) -> &str {
1045 match input.rsplit_once(suffix_start) {
1046 Some((without_suffix, _)) => without_suffix,
1047 None => input,
1048 }
1049 }
1050
1051 let (version_prefix, version_suffix) = pkgid.trim().rsplit_once('#')?;
1052 let package_name = match version_suffix.rsplit_once('@') {
1053 Some((custom_package_name, _version)) => custom_package_name,
1054 None => {
1055 let host_and_path = split_off_suffix(version_prefix, '?');
1056 let (_, package_name) = host_and_path.rsplit_once('/')?;
1057 package_name
1058 }
1059 };
1060 Some(package_name)
1061}
1062
1063async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
1064 maybe!(async {
1065 let mut last = None;
1066 let mut entries = fs::read_dir(&container_dir).await?;
1067 while let Some(entry) = entries.next().await {
1068 let path = entry?.path();
1069 if path.extension().is_some_and(|ext| ext == "metadata") {
1070 continue;
1071 }
1072 last = Some(path);
1073 }
1074
1075 let path = last.context("no cached binary")?;
1076 let path = match RustLspAdapter::GITHUB_ASSET_KIND {
1077 AssetKind::TarGz | AssetKind::Gz => path, // Tar and gzip extract in place.
1078 AssetKind::Zip => path.join("rust-analyzer.exe"), // zip contains a .exe
1079 };
1080
1081 anyhow::Ok(LanguageServerBinary {
1082 path,
1083 env: None,
1084 arguments: Default::default(),
1085 })
1086 })
1087 .await
1088 .log_err()
1089}
1090
1091fn test_fragment(variables: &TaskVariables, path: &Path, stem: &str) -> String {
1092 let fragment = if stem == "lib" {
1093 // This isn't quite right---it runs the tests for the entire library, rather than
1094 // just for the top-level `mod tests`. But we don't really have the means here to
1095 // filter out just that module.
1096 Some("--lib".to_owned())
1097 } else if stem == "mod" {
1098 maybe!({ Some(path.parent()?.file_name()?.to_string_lossy().into_owned()) })
1099 } else if stem == "main" {
1100 if let (Some(bin_name), Some(bin_kind)) = (
1101 variables.get(&RUST_BIN_NAME_TASK_VARIABLE),
1102 variables.get(&RUST_BIN_KIND_TASK_VARIABLE),
1103 ) {
1104 Some(format!("--{bin_kind}={bin_name}"))
1105 } else {
1106 None
1107 }
1108 } else {
1109 Some(stem.to_owned())
1110 };
1111 fragment.unwrap_or_else(|| "--".to_owned())
1112}
1113
1114#[cfg(test)]
1115mod tests {
1116 use std::num::NonZeroU32;
1117
1118 use super::*;
1119 use crate::language;
1120 use gpui::{BorrowAppContext, Hsla, TestAppContext};
1121 use lsp::CompletionItemLabelDetails;
1122 use settings::SettingsStore;
1123 use theme::SyntaxTheme;
1124 use util::path;
1125
1126 #[gpui::test]
1127 async fn test_process_rust_diagnostics() {
1128 let mut params = lsp::PublishDiagnosticsParams {
1129 uri: lsp::Uri::from_file_path(path!("/a")).unwrap(),
1130 version: None,
1131 diagnostics: vec![
1132 // no newlines
1133 lsp::Diagnostic {
1134 message: "use of moved value `a`".to_string(),
1135 ..Default::default()
1136 },
1137 // newline at the end of a code span
1138 lsp::Diagnostic {
1139 message: "consider importing this struct: `use b::c;\n`".to_string(),
1140 ..Default::default()
1141 },
1142 // code span starting right after a newline
1143 lsp::Diagnostic {
1144 message: "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
1145 .to_string(),
1146 ..Default::default()
1147 },
1148 ],
1149 };
1150 RustLspAdapter.process_diagnostics(&mut params, LanguageServerId(0), None);
1151
1152 assert_eq!(params.diagnostics[0].message, "use of moved value `a`");
1153
1154 // remove trailing newline from code span
1155 assert_eq!(
1156 params.diagnostics[1].message,
1157 "consider importing this struct: `use b::c;`"
1158 );
1159
1160 // do not remove newline before the start of code span
1161 assert_eq!(
1162 params.diagnostics[2].message,
1163 "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
1164 );
1165 }
1166
1167 #[gpui::test]
1168 async fn test_rust_label_for_completion() {
1169 let adapter = Arc::new(RustLspAdapter);
1170 let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1171 let grammar = language.grammar().unwrap();
1172 let theme = SyntaxTheme::new_test([
1173 ("type", Hsla::default()),
1174 ("keyword", Hsla::default()),
1175 ("function", Hsla::default()),
1176 ("property", Hsla::default()),
1177 ]);
1178
1179 language.set_theme(&theme);
1180
1181 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1182 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1183 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1184 let highlight_field = grammar.highlight_id_for_name("property").unwrap();
1185
1186 assert_eq!(
1187 adapter
1188 .label_for_completion(
1189 &lsp::CompletionItem {
1190 kind: Some(lsp::CompletionItemKind::FUNCTION),
1191 label: "hello(…)".to_string(),
1192 label_details: Some(CompletionItemLabelDetails {
1193 detail: Some("(use crate::foo)".into()),
1194 description: Some("fn(&mut Option<T>) -> Vec<T>".to_string())
1195 }),
1196 ..Default::default()
1197 },
1198 &language
1199 )
1200 .await,
1201 Some(CodeLabel::new(
1202 "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1203 0..5,
1204 vec![
1205 (0..5, highlight_function),
1206 (7..10, highlight_keyword),
1207 (11..17, highlight_type),
1208 (18..19, highlight_type),
1209 (25..28, highlight_type),
1210 (29..30, highlight_type),
1211 ],
1212 ))
1213 );
1214 assert_eq!(
1215 adapter
1216 .label_for_completion(
1217 &lsp::CompletionItem {
1218 kind: Some(lsp::CompletionItemKind::FUNCTION),
1219 label: "hello(…)".to_string(),
1220 label_details: Some(CompletionItemLabelDetails {
1221 detail: Some("(use crate::foo)".into()),
1222 description: Some("async fn(&mut Option<T>) -> Vec<T>".to_string()),
1223 }),
1224 ..Default::default()
1225 },
1226 &language
1227 )
1228 .await,
1229 Some(CodeLabel::new(
1230 "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1231 0..5,
1232 vec![
1233 (0..5, highlight_function),
1234 (7..10, highlight_keyword),
1235 (11..17, highlight_type),
1236 (18..19, highlight_type),
1237 (25..28, highlight_type),
1238 (29..30, highlight_type),
1239 ],
1240 ))
1241 );
1242 assert_eq!(
1243 adapter
1244 .label_for_completion(
1245 &lsp::CompletionItem {
1246 kind: Some(lsp::CompletionItemKind::FIELD),
1247 label: "len".to_string(),
1248 detail: Some("usize".to_string()),
1249 ..Default::default()
1250 },
1251 &language
1252 )
1253 .await,
1254 Some(CodeLabel::new(
1255 "len: usize".to_string(),
1256 0..3,
1257 vec![(0..3, highlight_field), (5..10, highlight_type),],
1258 ))
1259 );
1260
1261 assert_eq!(
1262 adapter
1263 .label_for_completion(
1264 &lsp::CompletionItem {
1265 kind: Some(lsp::CompletionItemKind::FUNCTION),
1266 label: "hello(…)".to_string(),
1267 label_details: Some(CompletionItemLabelDetails {
1268 detail: Some("(use crate::foo)".to_string()),
1269 description: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
1270 }),
1271
1272 ..Default::default()
1273 },
1274 &language
1275 )
1276 .await,
1277 Some(CodeLabel::new(
1278 "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1279 0..5,
1280 vec![
1281 (0..5, highlight_function),
1282 (7..10, highlight_keyword),
1283 (11..17, highlight_type),
1284 (18..19, highlight_type),
1285 (25..28, highlight_type),
1286 (29..30, highlight_type),
1287 ],
1288 ))
1289 );
1290
1291 assert_eq!(
1292 adapter
1293 .label_for_completion(
1294 &lsp::CompletionItem {
1295 kind: Some(lsp::CompletionItemKind::FUNCTION),
1296 label: "hello".to_string(),
1297 label_details: Some(CompletionItemLabelDetails {
1298 detail: Some("(use crate::foo)".to_string()),
1299 description: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
1300 }),
1301 ..Default::default()
1302 },
1303 &language
1304 )
1305 .await,
1306 Some(CodeLabel::new(
1307 "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1308 0..5,
1309 vec![
1310 (0..5, highlight_function),
1311 (7..10, highlight_keyword),
1312 (11..17, highlight_type),
1313 (18..19, highlight_type),
1314 (25..28, highlight_type),
1315 (29..30, highlight_type),
1316 ],
1317 ))
1318 );
1319
1320 assert_eq!(
1321 adapter
1322 .label_for_completion(
1323 &lsp::CompletionItem {
1324 kind: Some(lsp::CompletionItemKind::METHOD),
1325 label: "await.as_deref_mut()".to_string(),
1326 filter_text: Some("as_deref_mut".to_string()),
1327 label_details: Some(CompletionItemLabelDetails {
1328 detail: None,
1329 description: Some("fn(&mut self) -> IterMut<'_, T>".to_string()),
1330 }),
1331 ..Default::default()
1332 },
1333 &language
1334 )
1335 .await,
1336 Some(CodeLabel::new(
1337 "await.as_deref_mut(&mut self) -> IterMut<'_, T>".to_string(),
1338 6..18,
1339 vec![
1340 (6..18, HighlightId(2)),
1341 (20..23, HighlightId(1)),
1342 (33..40, HighlightId(0)),
1343 (45..46, HighlightId(0))
1344 ],
1345 ))
1346 );
1347
1348 assert_eq!(
1349 adapter
1350 .label_for_completion(
1351 &lsp::CompletionItem {
1352 kind: Some(lsp::CompletionItemKind::METHOD),
1353 label: "as_deref_mut()".to_string(),
1354 filter_text: Some("as_deref_mut".to_string()),
1355 label_details: Some(CompletionItemLabelDetails {
1356 detail: None,
1357 description: Some(
1358 "pub fn as_deref_mut(&mut self) -> IterMut<'_, T>".to_string()
1359 ),
1360 }),
1361 ..Default::default()
1362 },
1363 &language
1364 )
1365 .await,
1366 Some(CodeLabel::new(
1367 "pub fn as_deref_mut(&mut self) -> IterMut<'_, T>".to_string(),
1368 7..19,
1369 vec![
1370 (0..3, HighlightId(1)),
1371 (4..6, HighlightId(1)),
1372 (7..19, HighlightId(2)),
1373 (21..24, HighlightId(1)),
1374 (34..41, HighlightId(0)),
1375 (46..47, HighlightId(0))
1376 ],
1377 ))
1378 );
1379
1380 assert_eq!(
1381 adapter
1382 .label_for_completion(
1383 &lsp::CompletionItem {
1384 kind: Some(lsp::CompletionItemKind::FIELD),
1385 label: "inner_value".to_string(),
1386 filter_text: Some("value".to_string()),
1387 detail: Some("String".to_string()),
1388 ..Default::default()
1389 },
1390 &language,
1391 )
1392 .await,
1393 Some(CodeLabel::new(
1394 "inner_value: String".to_string(),
1395 6..11,
1396 vec![(0..11, HighlightId(3)), (13..19, HighlightId(0))],
1397 ))
1398 );
1399 }
1400
1401 #[gpui::test]
1402 async fn test_rust_label_for_symbol() {
1403 let adapter = Arc::new(RustLspAdapter);
1404 let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1405 let grammar = language.grammar().unwrap();
1406 let theme = SyntaxTheme::new_test([
1407 ("type", Hsla::default()),
1408 ("keyword", Hsla::default()),
1409 ("function", Hsla::default()),
1410 ("property", Hsla::default()),
1411 ]);
1412
1413 language.set_theme(&theme);
1414
1415 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1416 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1417 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1418
1419 assert_eq!(
1420 adapter
1421 .label_for_symbol("hello", lsp::SymbolKind::FUNCTION, &language)
1422 .await,
1423 Some(CodeLabel::new(
1424 "fn hello".to_string(),
1425 3..8,
1426 vec![(0..2, highlight_keyword), (3..8, highlight_function)],
1427 ))
1428 );
1429
1430 assert_eq!(
1431 adapter
1432 .label_for_symbol("World", lsp::SymbolKind::TYPE_PARAMETER, &language)
1433 .await,
1434 Some(CodeLabel::new(
1435 "type World".to_string(),
1436 5..10,
1437 vec![(0..4, highlight_keyword), (5..10, highlight_type)],
1438 ))
1439 );
1440 }
1441
1442 #[gpui::test]
1443 async fn test_rust_autoindent(cx: &mut TestAppContext) {
1444 // cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
1445 cx.update(|cx| {
1446 let test_settings = SettingsStore::test(cx);
1447 cx.set_global(test_settings);
1448 language::init(cx);
1449 cx.update_global::<SettingsStore, _>(|store, cx| {
1450 store.update_user_settings(cx, |s| {
1451 s.project.all_languages.defaults.tab_size = NonZeroU32::new(2);
1452 });
1453 });
1454 });
1455
1456 let language = crate::language("rust", tree_sitter_rust::LANGUAGE.into());
1457
1458 cx.new(|cx| {
1459 let mut buffer = Buffer::local("", cx).with_language(language, cx);
1460
1461 // indent between braces
1462 buffer.set_text("fn a() {}", cx);
1463 let ix = buffer.len() - 1;
1464 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1465 assert_eq!(buffer.text(), "fn a() {\n \n}");
1466
1467 // indent between braces, even after empty lines
1468 buffer.set_text("fn a() {\n\n\n}", cx);
1469 let ix = buffer.len() - 2;
1470 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1471 assert_eq!(buffer.text(), "fn a() {\n\n\n \n}");
1472
1473 // indent a line that continues a field expression
1474 buffer.set_text("fn a() {\n \n}", cx);
1475 let ix = buffer.len() - 2;
1476 buffer.edit([(ix..ix, "b\n.c")], Some(AutoindentMode::EachLine), cx);
1477 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n}");
1478
1479 // indent further lines that continue the field expression, even after empty lines
1480 let ix = buffer.len() - 2;
1481 buffer.edit([(ix..ix, "\n\n.d")], Some(AutoindentMode::EachLine), cx);
1482 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n \n .d\n}");
1483
1484 // dedent the line after the field expression
1485 let ix = buffer.len() - 2;
1486 buffer.edit([(ix..ix, ";\ne")], Some(AutoindentMode::EachLine), cx);
1487 assert_eq!(
1488 buffer.text(),
1489 "fn a() {\n b\n .c\n \n .d;\n e\n}"
1490 );
1491
1492 // indent inside a struct within a call
1493 buffer.set_text("const a: B = c(D {});", cx);
1494 let ix = buffer.len() - 3;
1495 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1496 assert_eq!(buffer.text(), "const a: B = c(D {\n \n});");
1497
1498 // indent further inside a nested call
1499 let ix = buffer.len() - 4;
1500 buffer.edit([(ix..ix, "e: f(\n\n)")], Some(AutoindentMode::EachLine), cx);
1501 assert_eq!(buffer.text(), "const a: B = c(D {\n e: f(\n \n )\n});");
1502
1503 // keep that indent after an empty line
1504 let ix = buffer.len() - 8;
1505 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1506 assert_eq!(
1507 buffer.text(),
1508 "const a: B = c(D {\n e: f(\n \n \n )\n});"
1509 );
1510
1511 buffer
1512 });
1513 }
1514
1515 #[test]
1516 fn test_package_name_from_pkgid() {
1517 for (input, expected) in [
1518 (
1519 "path+file:///absolute/path/to/project/zed/crates/zed#0.131.0",
1520 "zed",
1521 ),
1522 (
1523 "path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0",
1524 "my-custom-package",
1525 ),
1526 ] {
1527 assert_eq!(package_name_from_pkgid(input), Some(expected));
1528 }
1529 }
1530
1531 #[test]
1532 fn test_target_info_from_metadata() {
1533 for (input, absolute_path, expected) in [
1534 (
1535 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"}]}]}"#,
1536 "/path/to/zed/src/main.rs",
1537 Some((
1538 Some(TargetInfo {
1539 package_name: "zed".into(),
1540 target_name: "zed".into(),
1541 required_features: Vec::new(),
1542 target_kind: TargetKind::Bin,
1543 }),
1544 Arc::from("/path/to/zed".as_ref()),
1545 )),
1546 ),
1547 (
1548 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"}]}]}"#,
1549 "/path/to/custom-package/src/main.rs",
1550 Some((
1551 Some(TargetInfo {
1552 package_name: "my-custom-package".into(),
1553 target_name: "my-custom-bin".into(),
1554 required_features: Vec::new(),
1555 target_kind: TargetKind::Bin,
1556 }),
1557 Arc::from("/path/to/custom-package".as_ref()),
1558 )),
1559 ),
1560 (
1561 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"}]}"#,
1562 "/path/to/custom-package/src/main.rs",
1563 Some((
1564 Some(TargetInfo {
1565 package_name: "my-custom-package".into(),
1566 target_name: "my-custom-bin".into(),
1567 required_features: Vec::new(),
1568 target_kind: TargetKind::Example,
1569 }),
1570 Arc::from("/path/to/custom-package".as_ref()),
1571 )),
1572 ),
1573 (
1574 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"]}]}]}"#,
1575 "/path/to/custom-package/src/main.rs",
1576 Some((
1577 Some(TargetInfo {
1578 package_name: "my-custom-package".into(),
1579 target_name: "my-custom-bin".into(),
1580 required_features: vec!["foo".to_owned(), "bar".to_owned()],
1581 target_kind: TargetKind::Example,
1582 }),
1583 Arc::from("/path/to/custom-package".as_ref()),
1584 )),
1585 ),
1586 (
1587 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"}]}"#,
1588 "/path/to/custom-package/src/main.rs",
1589 Some((
1590 Some(TargetInfo {
1591 package_name: "my-custom-package".into(),
1592 target_name: "my-custom-bin".into(),
1593 required_features: vec![],
1594 target_kind: TargetKind::Example,
1595 }),
1596 Arc::from("/path/to/custom-package".as_ref()),
1597 )),
1598 ),
1599 (
1600 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"}]}"#,
1601 "/path/to/custom-package/src/main.rs",
1602 Some((None, Arc::from("/path/to/custom-package".as_ref()))),
1603 ),
1604 ] {
1605 let metadata: CargoMetadata = serde_json::from_str(input).context(input).unwrap();
1606
1607 let absolute_path = Path::new(absolute_path);
1608
1609 assert_eq!(target_info_from_metadata(metadata, absolute_path), expected);
1610 }
1611 }
1612
1613 #[test]
1614 fn test_rust_test_fragment() {
1615 #[track_caller]
1616 fn check(
1617 variables: impl IntoIterator<Item = (VariableName, &'static str)>,
1618 path: &str,
1619 expected: &str,
1620 ) {
1621 let path = Path::new(path);
1622 let found = test_fragment(
1623 &TaskVariables::from_iter(variables.into_iter().map(|(k, v)| (k, v.to_owned()))),
1624 path,
1625 path.file_stem().unwrap().to_str().unwrap(),
1626 );
1627 assert_eq!(expected, found);
1628 }
1629
1630 check([], "/project/src/lib.rs", "--lib");
1631 check([], "/project/src/foo/mod.rs", "foo");
1632 check(
1633 [
1634 (RUST_BIN_KIND_TASK_VARIABLE.clone(), "bin"),
1635 (RUST_BIN_NAME_TASK_VARIABLE, "x"),
1636 ],
1637 "/project/src/main.rs",
1638 "--bin=x",
1639 );
1640 check([], "/project/src/main.rs", "--");
1641 }
1642}