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