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 let detail = completion
309 .label_details
310 .as_ref()
311 .and_then(|detail| detail.detail.as_ref())
312 .or(completion.detail.as_ref())
313 .map(|detail| detail.trim());
314 let function_signature = completion
315 .label_details
316 .as_ref()
317 .and_then(|detail| detail.description.as_deref())
318 .or(completion.detail.as_deref());
319 match (detail, completion.kind) {
320 (Some(detail), Some(lsp::CompletionItemKind::FIELD)) => {
321 let name = &completion.label;
322 let text = format!("{name}: {detail}");
323 let prefix = "struct S { ";
324 let source = Rope::from(format!("{prefix}{text} }}"));
325 let runs =
326 language.highlight_text(&source, prefix.len()..prefix.len() + text.len());
327 let filter_range = completion
328 .filter_text
329 .as_deref()
330 .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
331 .unwrap_or(0..name.len());
332 return Some(CodeLabel {
333 text,
334 runs,
335 filter_range,
336 });
337 }
338 (
339 Some(detail),
340 Some(lsp::CompletionItemKind::CONSTANT | lsp::CompletionItemKind::VARIABLE),
341 ) if completion.insert_text_format != Some(lsp::InsertTextFormat::SNIPPET) => {
342 let name = &completion.label;
343 let text = format!(
344 "{}: {}",
345 name,
346 completion.detail.as_deref().unwrap_or(detail)
347 );
348 let prefix = "let ";
349 let source = Rope::from(format!("{prefix}{text} = ();"));
350 let runs =
351 language.highlight_text(&source, prefix.len()..prefix.len() + text.len());
352 let filter_range = completion
353 .filter_text
354 .as_deref()
355 .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
356 .unwrap_or(0..name.len());
357 return Some(CodeLabel {
358 text,
359 runs,
360 filter_range,
361 });
362 }
363 (
364 Some(detail),
365 Some(lsp::CompletionItemKind::FUNCTION | lsp::CompletionItemKind::METHOD),
366 ) => {
367 static REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new("\\(…?\\)").unwrap());
368 const FUNCTION_PREFIXES: [&str; 6] = [
369 "async fn",
370 "async unsafe fn",
371 "const fn",
372 "const unsafe fn",
373 "unsafe fn",
374 "fn",
375 ];
376 // Is it function `async`?
377 let fn_keyword = FUNCTION_PREFIXES.iter().find_map(|prefix| {
378 function_signature.as_ref().and_then(|signature| {
379 signature
380 .strip_prefix(*prefix)
381 .map(|suffix| (*prefix, suffix))
382 })
383 });
384 // fn keyword should be followed by opening parenthesis.
385 if let Some((prefix, suffix)) = fn_keyword {
386 let mut text = REGEX.replace(&completion.label, suffix).to_string();
387 let source = Rope::from(format!("{prefix} {text} {{}}"));
388 let run_start = prefix.len() + 1;
389 let runs = language.highlight_text(&source, run_start..run_start + text.len());
390 if detail.starts_with("(") {
391 text.push(' ');
392 text.push_str(&detail);
393 }
394 let filter_range = completion
395 .filter_text
396 .as_deref()
397 .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
398 .unwrap_or(0..completion.label.find('(').unwrap_or(text.len()));
399 return Some(CodeLabel {
400 filter_range,
401 text,
402 runs,
403 });
404 } else if completion
405 .detail
406 .as_ref()
407 .map_or(false, |detail| detail.starts_with("macro_rules! "))
408 {
409 let text = completion.label.clone();
410 let len = text.len();
411 let source = Rope::from(text.as_str());
412 let runs = language.highlight_text(&source, 0..len);
413 let filter_range = completion
414 .filter_text
415 .as_deref()
416 .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
417 .unwrap_or(0..len);
418 return Some(CodeLabel {
419 filter_range,
420 text,
421 runs,
422 });
423 }
424 }
425 (_, Some(kind)) => {
426 let highlight_name = match kind {
427 lsp::CompletionItemKind::STRUCT
428 | lsp::CompletionItemKind::INTERFACE
429 | lsp::CompletionItemKind::ENUM => Some("type"),
430 lsp::CompletionItemKind::ENUM_MEMBER => Some("variant"),
431 lsp::CompletionItemKind::KEYWORD => Some("keyword"),
432 lsp::CompletionItemKind::VALUE | lsp::CompletionItemKind::CONSTANT => {
433 Some("constant")
434 }
435 _ => None,
436 };
437
438 let mut label = completion.label.clone();
439 if let Some(detail) = detail.filter(|detail| detail.starts_with("(")) {
440 label.push(' ');
441 label.push_str(detail);
442 }
443 let mut label = CodeLabel::plain(label, completion.filter_text.as_deref());
444 if let Some(highlight_name) = highlight_name {
445 let highlight_id = language.grammar()?.highlight_id_for_name(highlight_name)?;
446 label.runs.push((
447 0..label.text.rfind('(').unwrap_or(completion.label.len()),
448 highlight_id,
449 ));
450 }
451
452 return Some(label);
453 }
454 _ => {}
455 }
456 None
457 }
458
459 async fn label_for_symbol(
460 &self,
461 name: &str,
462 kind: lsp::SymbolKind,
463 language: &Arc<Language>,
464 ) -> Option<CodeLabel> {
465 let (text, filter_range, display_range) = match kind {
466 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
467 let text = format!("fn {} () {{}}", name);
468 let filter_range = 3..3 + name.len();
469 let display_range = 0..filter_range.end;
470 (text, filter_range, display_range)
471 }
472 lsp::SymbolKind::STRUCT => {
473 let text = format!("struct {} {{}}", name);
474 let filter_range = 7..7 + name.len();
475 let display_range = 0..filter_range.end;
476 (text, filter_range, display_range)
477 }
478 lsp::SymbolKind::ENUM => {
479 let text = format!("enum {} {{}}", name);
480 let filter_range = 5..5 + name.len();
481 let display_range = 0..filter_range.end;
482 (text, filter_range, display_range)
483 }
484 lsp::SymbolKind::INTERFACE => {
485 let text = format!("trait {} {{}}", name);
486 let filter_range = 6..6 + name.len();
487 let display_range = 0..filter_range.end;
488 (text, filter_range, display_range)
489 }
490 lsp::SymbolKind::CONSTANT => {
491 let text = format!("const {}: () = ();", name);
492 let filter_range = 6..6 + name.len();
493 let display_range = 0..filter_range.end;
494 (text, filter_range, display_range)
495 }
496 lsp::SymbolKind::MODULE => {
497 let text = format!("mod {} {{}}", name);
498 let filter_range = 4..4 + name.len();
499 let display_range = 0..filter_range.end;
500 (text, filter_range, display_range)
501 }
502 lsp::SymbolKind::TYPE_PARAMETER => {
503 let text = format!("type {} {{}}", name);
504 let filter_range = 5..5 + name.len();
505 let display_range = 0..filter_range.end;
506 (text, filter_range, display_range)
507 }
508 _ => return None,
509 };
510
511 Some(CodeLabel {
512 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
513 text: text[display_range].to_string(),
514 filter_range,
515 })
516 }
517
518 fn prepare_initialize_params(
519 &self,
520 mut original: InitializeParams,
521 cx: &App,
522 ) -> Result<InitializeParams> {
523 let enable_lsp_tasks = ProjectSettings::get_global(cx)
524 .lsp
525 .get(&SERVER_NAME)
526 .map_or(false, |s| s.enable_lsp_tasks);
527 if enable_lsp_tasks {
528 let experimental = json!({
529 "runnables": {
530 "kinds": [ "cargo", "shell" ],
531 },
532 });
533 if let Some(original_experimental) = &mut original.capabilities.experimental {
534 merge_json_value_into(experimental, original_experimental);
535 } else {
536 original.capabilities.experimental = Some(experimental);
537 }
538 }
539
540 let cargo_diagnostics_fetched_separately = ProjectSettings::get_global(cx)
541 .diagnostics
542 .fetch_cargo_diagnostics();
543 if cargo_diagnostics_fetched_separately {
544 let disable_check_on_save = json!({
545 "checkOnSave": false,
546 });
547 if let Some(initialization_options) = &mut original.initialization_options {
548 merge_json_value_into(disable_check_on_save, initialization_options);
549 } else {
550 original.initialization_options = Some(disable_check_on_save);
551 }
552 }
553
554 Ok(original)
555 }
556}
557
558pub(crate) struct RustContextProvider;
559
560const RUST_PACKAGE_TASK_VARIABLE: VariableName =
561 VariableName::Custom(Cow::Borrowed("RUST_PACKAGE"));
562
563/// The bin name corresponding to the current file in Cargo.toml
564const RUST_BIN_NAME_TASK_VARIABLE: VariableName =
565 VariableName::Custom(Cow::Borrowed("RUST_BIN_NAME"));
566
567/// The bin kind (bin/example) corresponding to the current file in Cargo.toml
568const RUST_BIN_KIND_TASK_VARIABLE: VariableName =
569 VariableName::Custom(Cow::Borrowed("RUST_BIN_KIND"));
570
571/// The flag to list required features for executing a bin, if any
572const RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE: VariableName =
573 VariableName::Custom(Cow::Borrowed("RUST_BIN_REQUIRED_FEATURES_FLAG"));
574
575/// The list of required features for executing a bin, if any
576const RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE: VariableName =
577 VariableName::Custom(Cow::Borrowed("RUST_BIN_REQUIRED_FEATURES"));
578
579const RUST_TEST_FRAGMENT_TASK_VARIABLE: VariableName =
580 VariableName::Custom(Cow::Borrowed("RUST_TEST_FRAGMENT"));
581
582const RUST_DOC_TEST_NAME_TASK_VARIABLE: VariableName =
583 VariableName::Custom(Cow::Borrowed("RUST_DOC_TEST_NAME"));
584
585const RUST_TEST_NAME_TASK_VARIABLE: VariableName =
586 VariableName::Custom(Cow::Borrowed("RUST_TEST_NAME"));
587
588const RUST_MANIFEST_DIRNAME_TASK_VARIABLE: VariableName =
589 VariableName::Custom(Cow::Borrowed("RUST_MANIFEST_DIRNAME"));
590
591impl ContextProvider for RustContextProvider {
592 fn build_context(
593 &self,
594 task_variables: &TaskVariables,
595 location: ContextLocation<'_>,
596 project_env: Option<HashMap<String, String>>,
597 _: Arc<dyn LanguageToolchainStore>,
598 cx: &mut gpui::App,
599 ) -> Task<Result<TaskVariables>> {
600 let local_abs_path = location
601 .file_location
602 .buffer
603 .read(cx)
604 .file()
605 .and_then(|file| Some(file.as_local()?.abs_path(cx)));
606
607 let mut variables = TaskVariables::default();
608
609 if let (Some(path), Some(stem)) = (&local_abs_path, task_variables.get(&VariableName::Stem))
610 {
611 let fragment = test_fragment(&variables, &path, stem);
612 variables.insert(RUST_TEST_FRAGMENT_TASK_VARIABLE, fragment);
613 };
614 if let Some(test_name) =
615 task_variables.get(&VariableName::Custom(Cow::Borrowed("_test_name")))
616 {
617 variables.insert(RUST_TEST_NAME_TASK_VARIABLE, test_name.into());
618 }
619 if let Some(doc_test_name) =
620 task_variables.get(&VariableName::Custom(Cow::Borrowed("_doc_test_name")))
621 {
622 variables.insert(RUST_DOC_TEST_NAME_TASK_VARIABLE, doc_test_name.into());
623 }
624 cx.background_spawn(async move {
625 if let Some(path) = local_abs_path
626 .as_deref()
627 .and_then(|local_abs_path| local_abs_path.parent())
628 {
629 if let Some(package_name) =
630 human_readable_package_name(path, project_env.as_ref()).await
631 {
632 variables.insert(RUST_PACKAGE_TASK_VARIABLE.clone(), package_name);
633 }
634 }
635 if let Some(path) = local_abs_path.as_ref()
636 && let Some((target, manifest_path)) =
637 target_info_from_abs_path(&path, project_env.as_ref()).await
638 {
639 if let Some(target) = target {
640 variables.extend(TaskVariables::from_iter([
641 (RUST_PACKAGE_TASK_VARIABLE.clone(), target.package_name),
642 (RUST_BIN_NAME_TASK_VARIABLE.clone(), target.target_name),
643 (
644 RUST_BIN_KIND_TASK_VARIABLE.clone(),
645 target.target_kind.to_string(),
646 ),
647 ]));
648 if target.required_features.is_empty() {
649 variables.insert(RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE, "".into());
650 variables.insert(RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE, "".into());
651 } else {
652 variables.insert(
653 RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE.clone(),
654 "--features".to_string(),
655 );
656 variables.insert(
657 RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE.clone(),
658 target.required_features.join(","),
659 );
660 }
661 }
662 variables.extend(TaskVariables::from_iter([(
663 RUST_MANIFEST_DIRNAME_TASK_VARIABLE.clone(),
664 manifest_path.to_string_lossy().into_owned(),
665 )]));
666 }
667 Ok(variables)
668 })
669 }
670
671 fn associated_tasks(
672 &self,
673 _: Arc<dyn Fs>,
674 file: Option<Arc<dyn language::File>>,
675 cx: &App,
676 ) -> Task<Option<TaskTemplates>> {
677 const DEFAULT_RUN_NAME_STR: &str = "RUST_DEFAULT_PACKAGE_RUN";
678 const CUSTOM_TARGET_DIR: &str = "RUST_TARGET_DIR";
679
680 let language_sets = language_settings(Some("Rust".into()), file.as_ref(), cx);
681 let package_to_run = language_sets
682 .tasks
683 .variables
684 .get(DEFAULT_RUN_NAME_STR)
685 .cloned();
686 let custom_target_dir = language_sets
687 .tasks
688 .variables
689 .get(CUSTOM_TARGET_DIR)
690 .cloned();
691 let run_task_args = if let Some(package_to_run) = package_to_run.clone() {
692 vec!["run".into(), "-p".into(), package_to_run]
693 } else {
694 vec!["run".into()]
695 };
696 let mut task_templates = vec![
697 TaskTemplate {
698 label: format!(
699 "Check (package: {})",
700 RUST_PACKAGE_TASK_VARIABLE.template_value(),
701 ),
702 command: "cargo".into(),
703 args: vec![
704 "check".into(),
705 "-p".into(),
706 RUST_PACKAGE_TASK_VARIABLE.template_value(),
707 ],
708 cwd: Some("$ZED_DIRNAME".to_owned()),
709 ..TaskTemplate::default()
710 },
711 TaskTemplate {
712 label: "Check all targets (workspace)".into(),
713 command: "cargo".into(),
714 args: vec!["check".into(), "--workspace".into(), "--all-targets".into()],
715 cwd: Some("$ZED_DIRNAME".to_owned()),
716 ..TaskTemplate::default()
717 },
718 TaskTemplate {
719 label: format!(
720 "Test '{}' (package: {})",
721 RUST_TEST_NAME_TASK_VARIABLE.template_value(),
722 RUST_PACKAGE_TASK_VARIABLE.template_value(),
723 ),
724 command: "cargo".into(),
725 args: vec![
726 "test".into(),
727 "-p".into(),
728 RUST_PACKAGE_TASK_VARIABLE.template_value(),
729 "--".into(),
730 "--nocapture".into(),
731 "--include-ignored".into(),
732 RUST_TEST_NAME_TASK_VARIABLE.template_value(),
733 ],
734 tags: vec!["rust-test".to_owned()],
735 cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
736 ..TaskTemplate::default()
737 },
738 TaskTemplate {
739 label: format!(
740 "Doc test '{}' (package: {})",
741 RUST_DOC_TEST_NAME_TASK_VARIABLE.template_value(),
742 RUST_PACKAGE_TASK_VARIABLE.template_value(),
743 ),
744 command: "cargo".into(),
745 args: vec![
746 "test".into(),
747 "--doc".into(),
748 "-p".into(),
749 RUST_PACKAGE_TASK_VARIABLE.template_value(),
750 "--".into(),
751 "--nocapture".into(),
752 "--include-ignored".into(),
753 RUST_DOC_TEST_NAME_TASK_VARIABLE.template_value(),
754 ],
755 tags: vec!["rust-doc-test".to_owned()],
756 cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
757 ..TaskTemplate::default()
758 },
759 TaskTemplate {
760 label: format!(
761 "Test mod '{}' (package: {})",
762 VariableName::Stem.template_value(),
763 RUST_PACKAGE_TASK_VARIABLE.template_value(),
764 ),
765 command: "cargo".into(),
766 args: vec![
767 "test".into(),
768 "-p".into(),
769 RUST_PACKAGE_TASK_VARIABLE.template_value(),
770 "--".into(),
771 RUST_TEST_FRAGMENT_TASK_VARIABLE.template_value(),
772 ],
773 tags: vec!["rust-mod-test".to_owned()],
774 cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
775 ..TaskTemplate::default()
776 },
777 TaskTemplate {
778 label: format!(
779 "Run {} {} (package: {})",
780 RUST_BIN_KIND_TASK_VARIABLE.template_value(),
781 RUST_BIN_NAME_TASK_VARIABLE.template_value(),
782 RUST_PACKAGE_TASK_VARIABLE.template_value(),
783 ),
784 command: "cargo".into(),
785 args: vec![
786 "run".into(),
787 "-p".into(),
788 RUST_PACKAGE_TASK_VARIABLE.template_value(),
789 format!("--{}", RUST_BIN_KIND_TASK_VARIABLE.template_value()),
790 RUST_BIN_NAME_TASK_VARIABLE.template_value(),
791 RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE.template_value(),
792 RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE.template_value(),
793 ],
794 cwd: Some("$ZED_DIRNAME".to_owned()),
795 tags: vec!["rust-main".to_owned()],
796 ..TaskTemplate::default()
797 },
798 TaskTemplate {
799 label: format!(
800 "Test (package: {})",
801 RUST_PACKAGE_TASK_VARIABLE.template_value()
802 ),
803 command: "cargo".into(),
804 args: vec![
805 "test".into(),
806 "-p".into(),
807 RUST_PACKAGE_TASK_VARIABLE.template_value(),
808 ],
809 cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
810 ..TaskTemplate::default()
811 },
812 TaskTemplate {
813 label: "Run".into(),
814 command: "cargo".into(),
815 args: run_task_args,
816 cwd: Some("$ZED_DIRNAME".to_owned()),
817 ..TaskTemplate::default()
818 },
819 TaskTemplate {
820 label: "Clean".into(),
821 command: "cargo".into(),
822 args: vec!["clean".into()],
823 cwd: Some("$ZED_DIRNAME".to_owned()),
824 ..TaskTemplate::default()
825 },
826 ];
827
828 if let Some(custom_target_dir) = custom_target_dir {
829 task_templates = task_templates
830 .into_iter()
831 .map(|mut task_template| {
832 let mut args = task_template.args.split_off(1);
833 task_template.args.append(&mut vec![
834 "--target-dir".to_string(),
835 custom_target_dir.clone(),
836 ]);
837 task_template.args.append(&mut args);
838
839 task_template
840 })
841 .collect();
842 }
843
844 Task::ready(Some(TaskTemplates(task_templates)))
845 }
846
847 fn lsp_task_source(&self) -> Option<LanguageServerName> {
848 Some(SERVER_NAME)
849 }
850}
851
852/// Part of the data structure of Cargo metadata
853#[derive(Debug, serde::Deserialize)]
854struct CargoMetadata {
855 packages: Vec<CargoPackage>,
856}
857
858#[derive(Debug, serde::Deserialize)]
859struct CargoPackage {
860 id: String,
861 targets: Vec<CargoTarget>,
862 manifest_path: Arc<Path>,
863}
864
865#[derive(Debug, serde::Deserialize)]
866struct CargoTarget {
867 name: String,
868 kind: Vec<String>,
869 src_path: String,
870 #[serde(rename = "required-features", default)]
871 required_features: Vec<String>,
872}
873
874#[derive(Debug, PartialEq)]
875enum TargetKind {
876 Bin,
877 Example,
878}
879
880impl Display for TargetKind {
881 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
882 match self {
883 TargetKind::Bin => write!(f, "bin"),
884 TargetKind::Example => write!(f, "example"),
885 }
886 }
887}
888
889impl TryFrom<&str> for TargetKind {
890 type Error = ();
891 fn try_from(value: &str) -> Result<Self, ()> {
892 match value {
893 "bin" => Ok(Self::Bin),
894 "example" => Ok(Self::Example),
895 _ => Err(()),
896 }
897 }
898}
899/// Which package and binary target are we in?
900#[derive(Debug, PartialEq)]
901struct TargetInfo {
902 package_name: String,
903 target_name: String,
904 target_kind: TargetKind,
905 required_features: Vec<String>,
906}
907
908async fn target_info_from_abs_path(
909 abs_path: &Path,
910 project_env: Option<&HashMap<String, String>>,
911) -> Option<(Option<TargetInfo>, Arc<Path>)> {
912 let mut command = util::command::new_smol_command("cargo");
913 if let Some(envs) = project_env {
914 command.envs(envs);
915 }
916 let output = command
917 .current_dir(abs_path.parent()?)
918 .arg("metadata")
919 .arg("--no-deps")
920 .arg("--format-version")
921 .arg("1")
922 .output()
923 .await
924 .log_err()?
925 .stdout;
926
927 let metadata: CargoMetadata = serde_json::from_slice(&output).log_err()?;
928 target_info_from_metadata(metadata, abs_path)
929}
930
931fn target_info_from_metadata(
932 metadata: CargoMetadata,
933 abs_path: &Path,
934) -> Option<(Option<TargetInfo>, Arc<Path>)> {
935 let mut manifest_path = None;
936 for package in metadata.packages {
937 let Some(manifest_dir_path) = package.manifest_path.parent() else {
938 continue;
939 };
940
941 let Some(path_from_manifest_dir) = abs_path.strip_prefix(manifest_dir_path).ok() else {
942 continue;
943 };
944 let candidate_path_length = path_from_manifest_dir.components().count();
945 // Pick the most specific manifest path
946 if let Some((path, current_length)) = &mut manifest_path {
947 if candidate_path_length > *current_length {
948 *path = Arc::from(manifest_dir_path);
949 *current_length = candidate_path_length;
950 }
951 } else {
952 manifest_path = Some((Arc::from(manifest_dir_path), candidate_path_length));
953 };
954
955 for target in package.targets {
956 let Some(bin_kind) = target
957 .kind
958 .iter()
959 .find_map(|kind| TargetKind::try_from(kind.as_ref()).ok())
960 else {
961 continue;
962 };
963 let target_path = PathBuf::from(target.src_path);
964 if target_path == abs_path {
965 return manifest_path.map(|(path, _)| {
966 (
967 package_name_from_pkgid(&package.id).map(|package_name| TargetInfo {
968 package_name: package_name.to_owned(),
969 target_name: target.name,
970 required_features: target.required_features,
971 target_kind: bin_kind,
972 }),
973 path,
974 )
975 });
976 }
977 }
978 }
979
980 manifest_path.map(|(path, _)| (None, path))
981}
982
983async fn human_readable_package_name(
984 package_directory: &Path,
985 project_env: Option<&HashMap<String, String>>,
986) -> Option<String> {
987 let mut command = util::command::new_smol_command("cargo");
988 if let Some(envs) = project_env {
989 command.envs(envs);
990 }
991 let pkgid = String::from_utf8(
992 command
993 .current_dir(package_directory)
994 .arg("pkgid")
995 .output()
996 .await
997 .log_err()?
998 .stdout,
999 )
1000 .ok()?;
1001 Some(package_name_from_pkgid(&pkgid)?.to_owned())
1002}
1003
1004// For providing local `cargo check -p $pkgid` task, we do not need most of the information we have returned.
1005// Output example in the root of Zed project:
1006// ```sh
1007// ❯ cargo pkgid zed
1008// path+file:///absolute/path/to/project/zed/crates/zed#0.131.0
1009// ```
1010// Another variant, if a project has a custom package name or hyphen in the name:
1011// ```
1012// path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0
1013// ```
1014//
1015// Extracts the package name from the output according to the spec:
1016// https://doc.rust-lang.org/cargo/reference/pkgid-spec.html#specification-grammar
1017fn package_name_from_pkgid(pkgid: &str) -> Option<&str> {
1018 fn split_off_suffix(input: &str, suffix_start: char) -> &str {
1019 match input.rsplit_once(suffix_start) {
1020 Some((without_suffix, _)) => without_suffix,
1021 None => input,
1022 }
1023 }
1024
1025 let (version_prefix, version_suffix) = pkgid.trim().rsplit_once('#')?;
1026 let package_name = match version_suffix.rsplit_once('@') {
1027 Some((custom_package_name, _version)) => custom_package_name,
1028 None => {
1029 let host_and_path = split_off_suffix(version_prefix, '?');
1030 let (_, package_name) = host_and_path.rsplit_once('/')?;
1031 package_name
1032 }
1033 };
1034 Some(package_name)
1035}
1036
1037async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
1038 maybe!(async {
1039 let mut last = None;
1040 let mut entries = fs::read_dir(&container_dir).await?;
1041 while let Some(entry) = entries.next().await {
1042 last = Some(entry?.path());
1043 }
1044
1045 anyhow::Ok(LanguageServerBinary {
1046 path: last.context("no cached binary")?,
1047 env: None,
1048 arguments: Default::default(),
1049 })
1050 })
1051 .await
1052 .log_err()
1053}
1054
1055fn test_fragment(variables: &TaskVariables, path: &Path, stem: &str) -> String {
1056 let fragment = if stem == "lib" {
1057 // This isn't quite right---it runs the tests for the entire library, rather than
1058 // just for the top-level `mod tests`. But we don't really have the means here to
1059 // filter out just that module.
1060 Some("--lib".to_owned())
1061 } else if stem == "mod" {
1062 maybe!({ Some(path.parent()?.file_name()?.to_string_lossy().to_string()) })
1063 } else if stem == "main" {
1064 if let (Some(bin_name), Some(bin_kind)) = (
1065 variables.get(&RUST_BIN_NAME_TASK_VARIABLE),
1066 variables.get(&RUST_BIN_KIND_TASK_VARIABLE),
1067 ) {
1068 Some(format!("--{bin_kind}={bin_name}"))
1069 } else {
1070 None
1071 }
1072 } else {
1073 Some(stem.to_owned())
1074 };
1075 fragment.unwrap_or_else(|| "--".to_owned())
1076}
1077
1078#[cfg(test)]
1079mod tests {
1080 use std::num::NonZeroU32;
1081
1082 use super::*;
1083 use crate::language;
1084 use gpui::{BorrowAppContext, Hsla, TestAppContext};
1085 use language::language_settings::AllLanguageSettings;
1086 use lsp::CompletionItemLabelDetails;
1087 use settings::SettingsStore;
1088 use theme::SyntaxTheme;
1089 use util::path;
1090
1091 #[gpui::test]
1092 async fn test_process_rust_diagnostics() {
1093 let mut params = lsp::PublishDiagnosticsParams {
1094 uri: lsp::Url::from_file_path(path!("/a")).unwrap(),
1095 version: None,
1096 diagnostics: vec![
1097 // no newlines
1098 lsp::Diagnostic {
1099 message: "use of moved value `a`".to_string(),
1100 ..Default::default()
1101 },
1102 // newline at the end of a code span
1103 lsp::Diagnostic {
1104 message: "consider importing this struct: `use b::c;\n`".to_string(),
1105 ..Default::default()
1106 },
1107 // code span starting right after a newline
1108 lsp::Diagnostic {
1109 message: "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
1110 .to_string(),
1111 ..Default::default()
1112 },
1113 ],
1114 };
1115 RustLspAdapter.process_diagnostics(&mut params, LanguageServerId(0), None);
1116
1117 assert_eq!(params.diagnostics[0].message, "use of moved value `a`");
1118
1119 // remove trailing newline from code span
1120 assert_eq!(
1121 params.diagnostics[1].message,
1122 "consider importing this struct: `use b::c;`"
1123 );
1124
1125 // do not remove newline before the start of code span
1126 assert_eq!(
1127 params.diagnostics[2].message,
1128 "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
1129 );
1130 }
1131
1132 #[gpui::test]
1133 async fn test_rust_label_for_completion() {
1134 let adapter = Arc::new(RustLspAdapter);
1135 let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1136 let grammar = language.grammar().unwrap();
1137 let theme = SyntaxTheme::new_test([
1138 ("type", Hsla::default()),
1139 ("keyword", Hsla::default()),
1140 ("function", Hsla::default()),
1141 ("property", Hsla::default()),
1142 ]);
1143
1144 language.set_theme(&theme);
1145
1146 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1147 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1148 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1149 let highlight_field = grammar.highlight_id_for_name("property").unwrap();
1150
1151 assert_eq!(
1152 adapter
1153 .label_for_completion(
1154 &lsp::CompletionItem {
1155 kind: Some(lsp::CompletionItemKind::FUNCTION),
1156 label: "hello(…)".to_string(),
1157 label_details: Some(CompletionItemLabelDetails {
1158 detail: Some("(use crate::foo)".into()),
1159 description: Some("fn(&mut Option<T>) -> Vec<T>".to_string())
1160 }),
1161 ..Default::default()
1162 },
1163 &language
1164 )
1165 .await,
1166 Some(CodeLabel {
1167 text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1168 filter_range: 0..5,
1169 runs: vec![
1170 (0..5, highlight_function),
1171 (7..10, highlight_keyword),
1172 (11..17, highlight_type),
1173 (18..19, highlight_type),
1174 (25..28, highlight_type),
1175 (29..30, highlight_type),
1176 ],
1177 })
1178 );
1179 assert_eq!(
1180 adapter
1181 .label_for_completion(
1182 &lsp::CompletionItem {
1183 kind: Some(lsp::CompletionItemKind::FUNCTION),
1184 label: "hello(…)".to_string(),
1185 label_details: Some(CompletionItemLabelDetails {
1186 detail: Some(" (use crate::foo)".into()),
1187 description: Some("async fn(&mut Option<T>) -> Vec<T>".to_string()),
1188 }),
1189 ..Default::default()
1190 },
1191 &language
1192 )
1193 .await,
1194 Some(CodeLabel {
1195 text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1196 filter_range: 0..5,
1197 runs: vec![
1198 (0..5, highlight_function),
1199 (7..10, highlight_keyword),
1200 (11..17, highlight_type),
1201 (18..19, highlight_type),
1202 (25..28, highlight_type),
1203 (29..30, highlight_type),
1204 ],
1205 })
1206 );
1207 assert_eq!(
1208 adapter
1209 .label_for_completion(
1210 &lsp::CompletionItem {
1211 kind: Some(lsp::CompletionItemKind::FIELD),
1212 label: "len".to_string(),
1213 detail: Some("usize".to_string()),
1214 ..Default::default()
1215 },
1216 &language
1217 )
1218 .await,
1219 Some(CodeLabel {
1220 text: "len: usize".to_string(),
1221 filter_range: 0..3,
1222 runs: vec![(0..3, highlight_field), (5..10, highlight_type),],
1223 })
1224 );
1225
1226 assert_eq!(
1227 adapter
1228 .label_for_completion(
1229 &lsp::CompletionItem {
1230 kind: Some(lsp::CompletionItemKind::FUNCTION),
1231 label: "hello(…)".to_string(),
1232 label_details: Some(CompletionItemLabelDetails {
1233 detail: Some(" (use crate::foo)".to_string()),
1234 description: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
1235 }),
1236
1237 ..Default::default()
1238 },
1239 &language
1240 )
1241 .await,
1242 Some(CodeLabel {
1243 text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1244 filter_range: 0..5,
1245 runs: vec![
1246 (0..5, highlight_function),
1247 (7..10, highlight_keyword),
1248 (11..17, highlight_type),
1249 (18..19, highlight_type),
1250 (25..28, highlight_type),
1251 (29..30, highlight_type),
1252 ],
1253 })
1254 );
1255
1256 assert_eq!(
1257 adapter
1258 .label_for_completion(
1259 &lsp::CompletionItem {
1260 kind: Some(lsp::CompletionItemKind::METHOD),
1261 label: "await.as_deref_mut()".to_string(),
1262 filter_text: Some("as_deref_mut".to_string()),
1263 label_details: Some(CompletionItemLabelDetails {
1264 detail: None,
1265 description: Some("fn(&mut self) -> IterMut<'_, T>".to_string()),
1266 }),
1267 ..Default::default()
1268 },
1269 &language
1270 )
1271 .await,
1272 Some(CodeLabel {
1273 text: "await.as_deref_mut()".to_string(),
1274 filter_range: 6..18,
1275 runs: vec![],
1276 })
1277 );
1278
1279 assert_eq!(
1280 adapter
1281 .label_for_completion(
1282 &lsp::CompletionItem {
1283 kind: Some(lsp::CompletionItemKind::FIELD),
1284 label: "inner_value".to_string(),
1285 filter_text: Some("value".to_string()),
1286 detail: Some("String".to_string()),
1287 ..Default::default()
1288 },
1289 &language,
1290 )
1291 .await,
1292 Some(CodeLabel {
1293 text: "inner_value: String".to_string(),
1294 filter_range: 6..11,
1295 runs: vec![(0..11, HighlightId(3)), (13..19, HighlightId(0))],
1296 })
1297 );
1298 }
1299
1300 #[gpui::test]
1301 async fn test_rust_label_for_symbol() {
1302 let adapter = Arc::new(RustLspAdapter);
1303 let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1304 let grammar = language.grammar().unwrap();
1305 let theme = SyntaxTheme::new_test([
1306 ("type", Hsla::default()),
1307 ("keyword", Hsla::default()),
1308 ("function", Hsla::default()),
1309 ("property", Hsla::default()),
1310 ]);
1311
1312 language.set_theme(&theme);
1313
1314 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1315 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1316 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1317
1318 assert_eq!(
1319 adapter
1320 .label_for_symbol("hello", lsp::SymbolKind::FUNCTION, &language)
1321 .await,
1322 Some(CodeLabel {
1323 text: "fn hello".to_string(),
1324 filter_range: 3..8,
1325 runs: vec![(0..2, highlight_keyword), (3..8, highlight_function)],
1326 })
1327 );
1328
1329 assert_eq!(
1330 adapter
1331 .label_for_symbol("World", lsp::SymbolKind::TYPE_PARAMETER, &language)
1332 .await,
1333 Some(CodeLabel {
1334 text: "type World".to_string(),
1335 filter_range: 5..10,
1336 runs: vec![(0..4, highlight_keyword), (5..10, highlight_type)],
1337 })
1338 );
1339 }
1340
1341 #[gpui::test]
1342 async fn test_rust_autoindent(cx: &mut TestAppContext) {
1343 // cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
1344 cx.update(|cx| {
1345 let test_settings = SettingsStore::test(cx);
1346 cx.set_global(test_settings);
1347 language::init(cx);
1348 cx.update_global::<SettingsStore, _>(|store, cx| {
1349 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1350 s.defaults.tab_size = NonZeroU32::new(2);
1351 });
1352 });
1353 });
1354
1355 let language = crate::language("rust", tree_sitter_rust::LANGUAGE.into());
1356
1357 cx.new(|cx| {
1358 let mut buffer = Buffer::local("", cx).with_language(language, cx);
1359
1360 // indent between braces
1361 buffer.set_text("fn a() {}", cx);
1362 let ix = buffer.len() - 1;
1363 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1364 assert_eq!(buffer.text(), "fn a() {\n \n}");
1365
1366 // indent between braces, even after empty lines
1367 buffer.set_text("fn a() {\n\n\n}", cx);
1368 let ix = buffer.len() - 2;
1369 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1370 assert_eq!(buffer.text(), "fn a() {\n\n\n \n}");
1371
1372 // indent a line that continues a field expression
1373 buffer.set_text("fn a() {\n \n}", cx);
1374 let ix = buffer.len() - 2;
1375 buffer.edit([(ix..ix, "b\n.c")], Some(AutoindentMode::EachLine), cx);
1376 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n}");
1377
1378 // indent further lines that continue the field expression, even after empty lines
1379 let ix = buffer.len() - 2;
1380 buffer.edit([(ix..ix, "\n\n.d")], Some(AutoindentMode::EachLine), cx);
1381 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n \n .d\n}");
1382
1383 // dedent the line after the field expression
1384 let ix = buffer.len() - 2;
1385 buffer.edit([(ix..ix, ";\ne")], Some(AutoindentMode::EachLine), cx);
1386 assert_eq!(
1387 buffer.text(),
1388 "fn a() {\n b\n .c\n \n .d;\n e\n}"
1389 );
1390
1391 // indent inside a struct within a call
1392 buffer.set_text("const a: B = c(D {});", cx);
1393 let ix = buffer.len() - 3;
1394 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1395 assert_eq!(buffer.text(), "const a: B = c(D {\n \n});");
1396
1397 // indent further inside a nested call
1398 let ix = buffer.len() - 4;
1399 buffer.edit([(ix..ix, "e: f(\n\n)")], Some(AutoindentMode::EachLine), cx);
1400 assert_eq!(buffer.text(), "const a: B = c(D {\n e: f(\n \n )\n});");
1401
1402 // keep that indent after an empty line
1403 let ix = buffer.len() - 8;
1404 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1405 assert_eq!(
1406 buffer.text(),
1407 "const a: B = c(D {\n e: f(\n \n \n )\n});"
1408 );
1409
1410 buffer
1411 });
1412 }
1413
1414 #[test]
1415 fn test_package_name_from_pkgid() {
1416 for (input, expected) in [
1417 (
1418 "path+file:///absolute/path/to/project/zed/crates/zed#0.131.0",
1419 "zed",
1420 ),
1421 (
1422 "path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0",
1423 "my-custom-package",
1424 ),
1425 ] {
1426 assert_eq!(package_name_from_pkgid(input), Some(expected));
1427 }
1428 }
1429
1430 #[test]
1431 fn test_target_info_from_metadata() {
1432 for (input, absolute_path, expected) in [
1433 (
1434 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"}]}]}"#,
1435 "/path/to/zed/src/main.rs",
1436 Some((
1437 Some(TargetInfo {
1438 package_name: "zed".into(),
1439 target_name: "zed".into(),
1440 required_features: Vec::new(),
1441 target_kind: TargetKind::Bin,
1442 }),
1443 Arc::from("/path/to/zed".as_ref()),
1444 )),
1445 ),
1446 (
1447 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"}]}]}"#,
1448 "/path/to/custom-package/src/main.rs",
1449 Some((
1450 Some(TargetInfo {
1451 package_name: "my-custom-package".into(),
1452 target_name: "my-custom-bin".into(),
1453 required_features: Vec::new(),
1454 target_kind: TargetKind::Bin,
1455 }),
1456 Arc::from("/path/to/custom-package".as_ref()),
1457 )),
1458 ),
1459 (
1460 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"}]}"#,
1461 "/path/to/custom-package/src/main.rs",
1462 Some((
1463 Some(TargetInfo {
1464 package_name: "my-custom-package".into(),
1465 target_name: "my-custom-bin".into(),
1466 required_features: Vec::new(),
1467 target_kind: TargetKind::Example,
1468 }),
1469 Arc::from("/path/to/custom-package".as_ref()),
1470 )),
1471 ),
1472 (
1473 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"]}]}]}"#,
1474 "/path/to/custom-package/src/main.rs",
1475 Some((
1476 Some(TargetInfo {
1477 package_name: "my-custom-package".into(),
1478 target_name: "my-custom-bin".into(),
1479 required_features: vec!["foo".to_owned(), "bar".to_owned()],
1480 target_kind: TargetKind::Example,
1481 }),
1482 Arc::from("/path/to/custom-package".as_ref()),
1483 )),
1484 ),
1485 (
1486 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"}]}"#,
1487 "/path/to/custom-package/src/main.rs",
1488 Some((
1489 Some(TargetInfo {
1490 package_name: "my-custom-package".into(),
1491 target_name: "my-custom-bin".into(),
1492 required_features: vec![],
1493 target_kind: TargetKind::Example,
1494 }),
1495 Arc::from("/path/to/custom-package".as_ref()),
1496 )),
1497 ),
1498 (
1499 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"}]}"#,
1500 "/path/to/custom-package/src/main.rs",
1501 Some((None, Arc::from("/path/to/custom-package".as_ref()))),
1502 ),
1503 ] {
1504 let metadata: CargoMetadata = serde_json::from_str(input).context(input).unwrap();
1505
1506 let absolute_path = Path::new(absolute_path);
1507
1508 assert_eq!(target_info_from_metadata(metadata, absolute_path), expected);
1509 }
1510 }
1511
1512 #[test]
1513 fn test_rust_test_fragment() {
1514 #[track_caller]
1515 fn check(
1516 variables: impl IntoIterator<Item = (VariableName, &'static str)>,
1517 path: &str,
1518 expected: &str,
1519 ) {
1520 let path = Path::new(path);
1521 let found = test_fragment(
1522 &TaskVariables::from_iter(variables.into_iter().map(|(k, v)| (k, v.to_owned()))),
1523 path,
1524 &path.file_stem().unwrap().to_str().unwrap(),
1525 );
1526 assert_eq!(expected, found);
1527 }
1528
1529 check([], "/project/src/lib.rs", "--lib");
1530 check([], "/project/src/foo/mod.rs", "foo");
1531 check(
1532 [
1533 (RUST_BIN_KIND_TASK_VARIABLE.clone(), "bin"),
1534 (RUST_BIN_NAME_TASK_VARIABLE, "x"),
1535 ],
1536 "/project/src/main.rs",
1537 "--bin=x",
1538 );
1539 check([], "/project/src/main.rs", "--");
1540 }
1541}