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 }),
641 command: "cargo".into(),
642 args: vec![
643 "test".into(),
644 "-p".into(),
645 RUST_PACKAGE_TASK_VARIABLE.template_value(),
646 RUST_TEST_NAME_TASK_VARIABLE.template_value(),
647 "--no-run".into(),
648 ],
649 tags: vec!["rust-test".to_owned()],
650 cwd: Some("$ZED_DIRNAME".to_owned()),
651 ..TaskTemplate::default()
652 },
653 TaskTemplate {
654 label: format!(
655 "Doc test '{}' (package: {})",
656 RUST_DOC_TEST_NAME_TASK_VARIABLE.template_value(),
657 RUST_PACKAGE_TASK_VARIABLE.template_value(),
658 ),
659 command: "cargo".into(),
660 args: vec![
661 "test".into(),
662 "--doc".into(),
663 "-p".into(),
664 RUST_PACKAGE_TASK_VARIABLE.template_value(),
665 RUST_DOC_TEST_NAME_TASK_VARIABLE.template_value(),
666 "--".into(),
667 "--nocapture".into(),
668 ],
669 tags: vec!["rust-doc-test".to_owned()],
670 cwd: Some("$ZED_DIRNAME".to_owned()),
671 ..TaskTemplate::default()
672 },
673 TaskTemplate {
674 label: format!(
675 "Test mod '{}' (package: {})",
676 VariableName::Stem.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 RUST_TEST_FRAGMENT_TASK_VARIABLE.template_value(),
685 ],
686 tags: vec!["rust-mod-test".to_owned()],
687 cwd: Some("$ZED_DIRNAME".to_owned()),
688 ..TaskTemplate::default()
689 },
690 TaskTemplate {
691 label: format!(
692 "Run {} {} (package: {})",
693 RUST_BIN_KIND_TASK_VARIABLE.template_value(),
694 RUST_BIN_NAME_TASK_VARIABLE.template_value(),
695 RUST_PACKAGE_TASK_VARIABLE.template_value(),
696 ),
697 command: "cargo".into(),
698 args: vec![
699 "run".into(),
700 "-p".into(),
701 RUST_PACKAGE_TASK_VARIABLE.template_value(),
702 format!("--{}", RUST_BIN_KIND_TASK_VARIABLE.template_value()),
703 RUST_BIN_NAME_TASK_VARIABLE.template_value(),
704 ],
705 cwd: Some("$ZED_DIRNAME".to_owned()),
706 tags: vec!["rust-main".to_owned()],
707 ..TaskTemplate::default()
708 },
709 TaskTemplate {
710 label: format!(
711 "Test (package: {})",
712 RUST_PACKAGE_TASK_VARIABLE.template_value()
713 ),
714 command: "cargo".into(),
715 args: vec![
716 "test".into(),
717 "-p".into(),
718 RUST_PACKAGE_TASK_VARIABLE.template_value(),
719 ],
720 cwd: Some("$ZED_DIRNAME".to_owned()),
721 ..TaskTemplate::default()
722 },
723 TaskTemplate {
724 label: "Run".into(),
725 command: "cargo".into(),
726 args: run_task_args,
727 cwd: Some("$ZED_DIRNAME".to_owned()),
728 ..TaskTemplate::default()
729 },
730 TaskTemplate {
731 label: "Debug".into(),
732 cwd: Some("$ZED_DIRNAME".to_owned()),
733 command: "cargo".into(),
734 task_type: TaskType::Debug(task::DebugArgs {
735 request: task::DebugArgsRequest::Launch,
736 adapter: "LLDB".to_owned(),
737 initialize_args: None,
738 locator: Some("cargo".into()),
739 tcp_connection: None,
740 }),
741 args: debug_task_args,
742 tags: vec!["rust-main".to_owned()],
743 ..TaskTemplate::default()
744 },
745 TaskTemplate {
746 label: "Clean".into(),
747 command: "cargo".into(),
748 args: vec!["clean".into()],
749 cwd: Some("$ZED_DIRNAME".to_owned()),
750 ..TaskTemplate::default()
751 },
752 ];
753
754 if let Some(custom_target_dir) = custom_target_dir {
755 task_templates = task_templates
756 .into_iter()
757 .map(|mut task_template| {
758 let mut args = task_template.args.split_off(1);
759 task_template.args.append(&mut vec![
760 "--target-dir".to_string(),
761 custom_target_dir.clone(),
762 ]);
763 task_template.args.append(&mut args);
764
765 task_template
766 })
767 .collect();
768 }
769
770 Some(TaskTemplates(task_templates))
771 }
772}
773
774/// Part of the data structure of Cargo metadata
775#[derive(serde::Deserialize)]
776struct CargoMetadata {
777 packages: Vec<CargoPackage>,
778}
779
780#[derive(serde::Deserialize)]
781struct CargoPackage {
782 id: String,
783 targets: Vec<CargoTarget>,
784}
785
786#[derive(serde::Deserialize)]
787struct CargoTarget {
788 name: String,
789 kind: Vec<String>,
790 src_path: String,
791}
792
793#[derive(Debug, PartialEq)]
794enum TargetKind {
795 Bin,
796 Example,
797}
798
799impl Display for TargetKind {
800 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
801 match self {
802 TargetKind::Bin => write!(f, "bin"),
803 TargetKind::Example => write!(f, "example"),
804 }
805 }
806}
807
808impl TryFrom<&str> for TargetKind {
809 type Error = ();
810 fn try_from(value: &str) -> Result<Self, ()> {
811 match value {
812 "bin" => Ok(Self::Bin),
813 "example" => Ok(Self::Example),
814 _ => Err(()),
815 }
816 }
817}
818/// Which package and binary target are we in?
819struct TargetInfo {
820 package_name: String,
821 target_name: String,
822 target_kind: TargetKind,
823}
824
825fn package_name_and_bin_name_from_abs_path(
826 abs_path: &Path,
827 project_env: Option<&HashMap<String, String>>,
828) -> Option<TargetInfo> {
829 let mut command = util::command::new_std_command("cargo");
830 if let Some(envs) = project_env {
831 command.envs(envs);
832 }
833 let output = command
834 .current_dir(abs_path.parent()?)
835 .arg("metadata")
836 .arg("--no-deps")
837 .arg("--format-version")
838 .arg("1")
839 .output()
840 .log_err()?
841 .stdout;
842
843 let metadata: CargoMetadata = serde_json::from_slice(&output).log_err()?;
844
845 retrieve_package_id_and_bin_name_from_metadata(metadata, abs_path).and_then(
846 |(package_id, bin_name, target_kind)| {
847 let package_name = package_name_from_pkgid(&package_id);
848
849 package_name.map(|package_name| TargetInfo {
850 package_name: package_name.to_owned(),
851 target_name: bin_name,
852 target_kind,
853 })
854 },
855 )
856}
857
858fn retrieve_package_id_and_bin_name_from_metadata(
859 metadata: CargoMetadata,
860 abs_path: &Path,
861) -> Option<(String, String, TargetKind)> {
862 for package in metadata.packages {
863 for target in package.targets {
864 let Some(bin_kind) = target
865 .kind
866 .iter()
867 .find_map(|kind| TargetKind::try_from(kind.as_ref()).ok())
868 else {
869 continue;
870 };
871 let target_path = PathBuf::from(target.src_path);
872 if target_path == abs_path {
873 return Some((package.id, target.name, bin_kind));
874 }
875 }
876 }
877
878 None
879}
880
881fn human_readable_package_name(
882 package_directory: &Path,
883 project_env: Option<&HashMap<String, String>>,
884) -> Option<String> {
885 let mut command = util::command::new_std_command("cargo");
886 if let Some(envs) = project_env {
887 command.envs(envs);
888 }
889 let pkgid = String::from_utf8(
890 command
891 .current_dir(package_directory)
892 .arg("pkgid")
893 .output()
894 .log_err()?
895 .stdout,
896 )
897 .ok()?;
898 Some(package_name_from_pkgid(&pkgid)?.to_owned())
899}
900
901// For providing local `cargo check -p $pkgid` task, we do not need most of the information we have returned.
902// Output example in the root of Zed project:
903// ```sh
904// ❯ cargo pkgid zed
905// path+file:///absolute/path/to/project/zed/crates/zed#0.131.0
906// ```
907// Another variant, if a project has a custom package name or hyphen in the name:
908// ```
909// path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0
910// ```
911//
912// Extracts the package name from the output according to the spec:
913// https://doc.rust-lang.org/cargo/reference/pkgid-spec.html#specification-grammar
914fn package_name_from_pkgid(pkgid: &str) -> Option<&str> {
915 fn split_off_suffix(input: &str, suffix_start: char) -> &str {
916 match input.rsplit_once(suffix_start) {
917 Some((without_suffix, _)) => without_suffix,
918 None => input,
919 }
920 }
921
922 let (version_prefix, version_suffix) = pkgid.trim().rsplit_once('#')?;
923 let package_name = match version_suffix.rsplit_once('@') {
924 Some((custom_package_name, _version)) => custom_package_name,
925 None => {
926 let host_and_path = split_off_suffix(version_prefix, '?');
927 let (_, package_name) = host_and_path.rsplit_once('/')?;
928 package_name
929 }
930 };
931 Some(package_name)
932}
933
934async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
935 maybe!(async {
936 let mut last = None;
937 let mut entries = fs::read_dir(&container_dir).await?;
938 while let Some(entry) = entries.next().await {
939 last = Some(entry?.path());
940 }
941
942 anyhow::Ok(LanguageServerBinary {
943 path: last.ok_or_else(|| anyhow!("no cached binary"))?,
944 env: None,
945 arguments: Default::default(),
946 })
947 })
948 .await
949 .log_err()
950}
951
952fn test_fragment(variables: &TaskVariables, path: &Path, stem: &str) -> String {
953 let fragment = if stem == "lib" {
954 // This isn't quite right---it runs the tests for the entire library, rather than
955 // just for the top-level `mod tests`. But we don't really have the means here to
956 // filter out just that module.
957 Some("--lib".to_owned())
958 } else if stem == "mod" {
959 maybe!({ Some(path.parent()?.file_name()?.to_string_lossy().to_string()) })
960 } else if stem == "main" {
961 if let (Some(bin_name), Some(bin_kind)) = (
962 variables.get(&RUST_BIN_NAME_TASK_VARIABLE),
963 variables.get(&RUST_BIN_KIND_TASK_VARIABLE),
964 ) {
965 Some(format!("--{bin_kind}={bin_name}"))
966 } else {
967 None
968 }
969 } else {
970 Some(stem.to_owned())
971 };
972 fragment.unwrap_or_else(|| "--".to_owned())
973}
974
975#[cfg(test)]
976mod tests {
977 use std::num::NonZeroU32;
978
979 use super::*;
980 use crate::language;
981 use gpui::{AppContext as _, BorrowAppContext, Hsla, TestAppContext};
982 use language::language_settings::AllLanguageSettings;
983 use lsp::CompletionItemLabelDetails;
984 use settings::SettingsStore;
985 use theme::SyntaxTheme;
986 use util::path;
987
988 #[gpui::test]
989 async fn test_process_rust_diagnostics() {
990 let mut params = lsp::PublishDiagnosticsParams {
991 uri: lsp::Url::from_file_path(path!("/a")).unwrap(),
992 version: None,
993 diagnostics: vec![
994 // no newlines
995 lsp::Diagnostic {
996 message: "use of moved value `a`".to_string(),
997 ..Default::default()
998 },
999 // newline at the end of a code span
1000 lsp::Diagnostic {
1001 message: "consider importing this struct: `use b::c;\n`".to_string(),
1002 ..Default::default()
1003 },
1004 // code span starting right after a newline
1005 lsp::Diagnostic {
1006 message: "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
1007 .to_string(),
1008 ..Default::default()
1009 },
1010 ],
1011 };
1012 RustLspAdapter.process_diagnostics(&mut params, LanguageServerId(0), None);
1013
1014 assert_eq!(params.diagnostics[0].message, "use of moved value `a`");
1015
1016 // remove trailing newline from code span
1017 assert_eq!(
1018 params.diagnostics[1].message,
1019 "consider importing this struct: `use b::c;`"
1020 );
1021
1022 // do not remove newline before the start of code span
1023 assert_eq!(
1024 params.diagnostics[2].message,
1025 "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
1026 );
1027 }
1028
1029 #[gpui::test]
1030 async fn test_rust_label_for_completion() {
1031 let adapter = Arc::new(RustLspAdapter);
1032 let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1033 let grammar = language.grammar().unwrap();
1034 let theme = SyntaxTheme::new_test([
1035 ("type", Hsla::default()),
1036 ("keyword", Hsla::default()),
1037 ("function", Hsla::default()),
1038 ("property", Hsla::default()),
1039 ]);
1040
1041 language.set_theme(&theme);
1042
1043 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1044 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1045 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1046 let highlight_field = grammar.highlight_id_for_name("property").unwrap();
1047
1048 assert_eq!(
1049 adapter
1050 .label_for_completion(
1051 &lsp::CompletionItem {
1052 kind: Some(lsp::CompletionItemKind::FUNCTION),
1053 label: "hello(…)".to_string(),
1054 label_details: Some(CompletionItemLabelDetails {
1055 detail: Some("(use crate::foo)".into()),
1056 description: Some("fn(&mut Option<T>) -> Vec<T>".to_string())
1057 }),
1058 ..Default::default()
1059 },
1060 &language
1061 )
1062 .await,
1063 Some(CodeLabel {
1064 text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1065 filter_range: 0..5,
1066 runs: vec![
1067 (0..5, highlight_function),
1068 (7..10, highlight_keyword),
1069 (11..17, highlight_type),
1070 (18..19, highlight_type),
1071 (25..28, highlight_type),
1072 (29..30, highlight_type),
1073 ],
1074 })
1075 );
1076 assert_eq!(
1077 adapter
1078 .label_for_completion(
1079 &lsp::CompletionItem {
1080 kind: Some(lsp::CompletionItemKind::FUNCTION),
1081 label: "hello(…)".to_string(),
1082 label_details: Some(CompletionItemLabelDetails {
1083 detail: Some(" (use crate::foo)".into()),
1084 description: Some("async fn(&mut Option<T>) -> Vec<T>".to_string()),
1085 }),
1086 ..Default::default()
1087 },
1088 &language
1089 )
1090 .await,
1091 Some(CodeLabel {
1092 text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1093 filter_range: 0..5,
1094 runs: vec![
1095 (0..5, highlight_function),
1096 (7..10, highlight_keyword),
1097 (11..17, highlight_type),
1098 (18..19, highlight_type),
1099 (25..28, highlight_type),
1100 (29..30, highlight_type),
1101 ],
1102 })
1103 );
1104 assert_eq!(
1105 adapter
1106 .label_for_completion(
1107 &lsp::CompletionItem {
1108 kind: Some(lsp::CompletionItemKind::FIELD),
1109 label: "len".to_string(),
1110 detail: Some("usize".to_string()),
1111 ..Default::default()
1112 },
1113 &language
1114 )
1115 .await,
1116 Some(CodeLabel {
1117 text: "len: usize".to_string(),
1118 filter_range: 0..3,
1119 runs: vec![(0..3, highlight_field), (5..10, highlight_type),],
1120 })
1121 );
1122
1123 assert_eq!(
1124 adapter
1125 .label_for_completion(
1126 &lsp::CompletionItem {
1127 kind: Some(lsp::CompletionItemKind::FUNCTION),
1128 label: "hello(…)".to_string(),
1129 label_details: Some(CompletionItemLabelDetails {
1130 detail: Some(" (use crate::foo)".to_string()),
1131 description: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
1132 }),
1133
1134 ..Default::default()
1135 },
1136 &language
1137 )
1138 .await,
1139 Some(CodeLabel {
1140 text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1141 filter_range: 0..5,
1142 runs: vec![
1143 (0..5, highlight_function),
1144 (7..10, highlight_keyword),
1145 (11..17, highlight_type),
1146 (18..19, highlight_type),
1147 (25..28, highlight_type),
1148 (29..30, highlight_type),
1149 ],
1150 })
1151 );
1152 }
1153
1154 #[gpui::test]
1155 async fn test_rust_label_for_symbol() {
1156 let adapter = Arc::new(RustLspAdapter);
1157 let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1158 let grammar = language.grammar().unwrap();
1159 let theme = SyntaxTheme::new_test([
1160 ("type", Hsla::default()),
1161 ("keyword", Hsla::default()),
1162 ("function", Hsla::default()),
1163 ("property", Hsla::default()),
1164 ]);
1165
1166 language.set_theme(&theme);
1167
1168 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1169 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1170 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1171
1172 assert_eq!(
1173 adapter
1174 .label_for_symbol("hello", lsp::SymbolKind::FUNCTION, &language)
1175 .await,
1176 Some(CodeLabel {
1177 text: "fn hello".to_string(),
1178 filter_range: 3..8,
1179 runs: vec![(0..2, highlight_keyword), (3..8, highlight_function)],
1180 })
1181 );
1182
1183 assert_eq!(
1184 adapter
1185 .label_for_symbol("World", lsp::SymbolKind::TYPE_PARAMETER, &language)
1186 .await,
1187 Some(CodeLabel {
1188 text: "type World".to_string(),
1189 filter_range: 5..10,
1190 runs: vec![(0..4, highlight_keyword), (5..10, highlight_type)],
1191 })
1192 );
1193 }
1194
1195 #[gpui::test]
1196 async fn test_rust_autoindent(cx: &mut TestAppContext) {
1197 // cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
1198 cx.update(|cx| {
1199 let test_settings = SettingsStore::test(cx);
1200 cx.set_global(test_settings);
1201 language::init(cx);
1202 cx.update_global::<SettingsStore, _>(|store, cx| {
1203 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1204 s.defaults.tab_size = NonZeroU32::new(2);
1205 });
1206 });
1207 });
1208
1209 let language = crate::language("rust", tree_sitter_rust::LANGUAGE.into());
1210
1211 cx.new(|cx| {
1212 let mut buffer = Buffer::local("", cx).with_language(language, cx);
1213
1214 // indent between braces
1215 buffer.set_text("fn a() {}", cx);
1216 let ix = buffer.len() - 1;
1217 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1218 assert_eq!(buffer.text(), "fn a() {\n \n}");
1219
1220 // indent between braces, even after empty lines
1221 buffer.set_text("fn a() {\n\n\n}", cx);
1222 let ix = buffer.len() - 2;
1223 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1224 assert_eq!(buffer.text(), "fn a() {\n\n\n \n}");
1225
1226 // indent a line that continues a field expression
1227 buffer.set_text("fn a() {\n \n}", cx);
1228 let ix = buffer.len() - 2;
1229 buffer.edit([(ix..ix, "b\n.c")], Some(AutoindentMode::EachLine), cx);
1230 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n}");
1231
1232 // indent further lines that continue the field expression, even after empty lines
1233 let ix = buffer.len() - 2;
1234 buffer.edit([(ix..ix, "\n\n.d")], Some(AutoindentMode::EachLine), cx);
1235 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n \n .d\n}");
1236
1237 // dedent the line after the field expression
1238 let ix = buffer.len() - 2;
1239 buffer.edit([(ix..ix, ";\ne")], Some(AutoindentMode::EachLine), cx);
1240 assert_eq!(
1241 buffer.text(),
1242 "fn a() {\n b\n .c\n \n .d;\n e\n}"
1243 );
1244
1245 // indent inside a struct within a call
1246 buffer.set_text("const a: B = c(D {});", cx);
1247 let ix = buffer.len() - 3;
1248 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1249 assert_eq!(buffer.text(), "const a: B = c(D {\n \n});");
1250
1251 // indent further inside a nested call
1252 let ix = buffer.len() - 4;
1253 buffer.edit([(ix..ix, "e: f(\n\n)")], Some(AutoindentMode::EachLine), cx);
1254 assert_eq!(buffer.text(), "const a: B = c(D {\n e: f(\n \n )\n});");
1255
1256 // keep that indent after an empty line
1257 let ix = buffer.len() - 8;
1258 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1259 assert_eq!(
1260 buffer.text(),
1261 "const a: B = c(D {\n e: f(\n \n \n )\n});"
1262 );
1263
1264 buffer
1265 });
1266 }
1267
1268 #[test]
1269 fn test_package_name_from_pkgid() {
1270 for (input, expected) in [
1271 (
1272 "path+file:///absolute/path/to/project/zed/crates/zed#0.131.0",
1273 "zed",
1274 ),
1275 (
1276 "path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0",
1277 "my-custom-package",
1278 ),
1279 ] {
1280 assert_eq!(package_name_from_pkgid(input), Some(expected));
1281 }
1282 }
1283
1284 #[test]
1285 fn test_retrieve_package_id_and_bin_name_from_metadata() {
1286 for (input, absolute_path, expected) in [
1287 (
1288 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"}]}]}"#,
1289 "/path/to/zed/src/main.rs",
1290 Some((
1291 "path+file:///path/to/zed/crates/zed#0.131.0",
1292 "zed",
1293 TargetKind::Bin,
1294 )),
1295 ),
1296 (
1297 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"}]}]}"#,
1298 "/path/to/custom-package/src/main.rs",
1299 Some((
1300 "path+file:///path/to/custom-package#my-custom-package@0.1.0",
1301 "my-custom-bin",
1302 TargetKind::Bin,
1303 )),
1304 ),
1305 (
1306 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"}]}]}"#,
1307 "/path/to/custom-package/src/main.rs",
1308 Some((
1309 "path+file:///path/to/custom-package#my-custom-package@0.1.0",
1310 "my-custom-bin",
1311 TargetKind::Example,
1312 )),
1313 ),
1314 (
1315 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"}]}]}"#,
1316 "/path/to/custom-package/src/main.rs",
1317 None,
1318 ),
1319 ] {
1320 let metadata: CargoMetadata = serde_json::from_str(input).unwrap();
1321
1322 let absolute_path = Path::new(absolute_path);
1323
1324 assert_eq!(
1325 retrieve_package_id_and_bin_name_from_metadata(metadata, absolute_path),
1326 expected.map(|(pkgid, name, kind)| (pkgid.to_owned(), name.to_owned(), kind))
1327 );
1328 }
1329 }
1330
1331 #[test]
1332 fn test_rust_test_fragment() {
1333 #[track_caller]
1334 fn check(
1335 variables: impl IntoIterator<Item = (VariableName, &'static str)>,
1336 path: &str,
1337 expected: &str,
1338 ) {
1339 let path = Path::new(path);
1340 let found = test_fragment(
1341 &TaskVariables::from_iter(variables.into_iter().map(|(k, v)| (k, v.to_owned()))),
1342 path,
1343 &path.file_stem().unwrap().to_str().unwrap(),
1344 );
1345 assert_eq!(expected, found);
1346 }
1347
1348 check([], "/project/src/lib.rs", "--lib");
1349 check([], "/project/src/foo/mod.rs", "foo");
1350 check(
1351 [
1352 (RUST_BIN_KIND_TASK_VARIABLE.clone(), "bin"),
1353 (RUST_BIN_NAME_TASK_VARIABLE, "x"),
1354 ],
1355 "/project/src/main.rs",
1356 "--bin=x",
1357 );
1358 check([], "/project/src/main.rs", "--");
1359 }
1360}