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