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