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