1use anyhow::{anyhow, bail, Context, Result};
2use async_compression::futures::bufread::GzipDecoder;
3use async_trait::async_trait;
4use futures::{io::BufReader, StreamExt};
5use gpui::{AppContext, AsyncAppContext};
6use http_client::github::{latest_github_release, GitHubLspBinaryVersion};
7pub use language::*;
8use language_settings::all_language_settings;
9use lsp::LanguageServerBinary;
10use project::project_settings::{BinarySettings, ProjectSettings};
11use regex::Regex;
12use settings::Settings;
13use smol::fs::{self, File};
14use std::{
15 any::Any,
16 borrow::Cow,
17 env::consts,
18 path::{Path, PathBuf},
19 sync::Arc,
20 sync::LazyLock,
21};
22use task::{TaskTemplate, TaskTemplates, TaskVariables, VariableName};
23use util::{fs::remove_matching, maybe, ResultExt};
24
25pub struct RustLspAdapter;
26
27impl RustLspAdapter {
28 const SERVER_NAME: &'static str = "rust-analyzer";
29}
30
31#[async_trait(?Send)]
32impl LspAdapter for RustLspAdapter {
33 fn name(&self) -> LanguageServerName {
34 LanguageServerName(Self::SERVER_NAME.into())
35 }
36
37 async fn check_if_user_installed(
38 &self,
39 delegate: &dyn LspAdapterDelegate,
40 cx: &AsyncAppContext,
41 ) -> Option<LanguageServerBinary> {
42 let configured_binary = cx.update(|cx| {
43 ProjectSettings::get_global(cx)
44 .lsp
45 .get(Self::SERVER_NAME)
46 .and_then(|s| s.binary.clone())
47 });
48
49 match configured_binary {
50 Ok(Some(BinarySettings {
51 path,
52 arguments,
53 path_lookup,
54 })) => {
55 let (path, env) = match (path, path_lookup) {
56 (Some(path), lookup) => {
57 if lookup.is_some() {
58 log::warn!(
59 "Both `path` and `path_lookup` are set, ignoring `path_lookup`"
60 );
61 }
62 (Some(path.into()), None)
63 }
64 (None, Some(true)) => {
65 let path = delegate.which(Self::SERVER_NAME.as_ref()).await?;
66 let env = delegate.shell_env().await;
67 (Some(path), Some(env))
68 }
69 (None, Some(false)) | (None, None) => (None, None),
70 };
71 path.map(|path| LanguageServerBinary {
72 path,
73 arguments: arguments
74 .unwrap_or_default()
75 .iter()
76 .map(|arg| arg.into())
77 .collect(),
78 env,
79 })
80 }
81 _ => None,
82 }
83 }
84
85 async fn fetch_latest_server_version(
86 &self,
87 delegate: &dyn LspAdapterDelegate,
88 ) -> Result<Box<dyn 'static + Send + Any>> {
89 let release = latest_github_release(
90 "rust-lang/rust-analyzer",
91 true,
92 false,
93 delegate.http_client(),
94 )
95 .await?;
96 let os = match consts::OS {
97 "macos" => "apple-darwin",
98 "linux" => "unknown-linux-gnu",
99 "windows" => "pc-windows-msvc",
100 other => bail!("Running on unsupported os: {other}"),
101 };
102 let asset_name = format!("rust-analyzer-{}-{os}.gz", consts::ARCH);
103 let asset = release
104 .assets
105 .iter()
106 .find(|asset| asset.name == asset_name)
107 .with_context(|| format!("no asset found matching `{asset_name:?}`"))?;
108 Ok(Box::new(GitHubLspBinaryVersion {
109 name: release.tag_name,
110 url: asset.browser_download_url.clone(),
111 }))
112 }
113
114 async fn fetch_server_binary(
115 &self,
116 version: Box<dyn 'static + Send + Any>,
117 container_dir: PathBuf,
118 delegate: &dyn LspAdapterDelegate,
119 ) -> Result<LanguageServerBinary> {
120 let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
121 let destination_path = container_dir.join(format!("rust-analyzer-{}", version.name));
122
123 if fs::metadata(&destination_path).await.is_err() {
124 let mut response = delegate
125 .http_client()
126 .get(&version.url, Default::default(), true)
127 .await
128 .map_err(|err| anyhow!("error downloading release: {}", err))?;
129 let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
130 let mut file = File::create(&destination_path).await?;
131 futures::io::copy(decompressed_bytes, &mut file).await?;
132 // todo("windows")
133 #[cfg(not(windows))]
134 {
135 fs::set_permissions(
136 &destination_path,
137 <fs::Permissions as fs::unix::PermissionsExt>::from_mode(0o755),
138 )
139 .await?;
140 }
141
142 remove_matching(&container_dir, |entry| entry != destination_path).await;
143 }
144
145 Ok(LanguageServerBinary {
146 path: destination_path,
147 env: None,
148 arguments: Default::default(),
149 })
150 }
151
152 async fn cached_server_binary(
153 &self,
154 container_dir: PathBuf,
155 _: &dyn LspAdapterDelegate,
156 ) -> Option<LanguageServerBinary> {
157 get_cached_server_binary(container_dir).await
158 }
159
160 async fn installation_test_binary(
161 &self,
162 container_dir: PathBuf,
163 ) -> Option<LanguageServerBinary> {
164 get_cached_server_binary(container_dir)
165 .await
166 .map(|mut binary| {
167 binary.arguments = vec!["--help".into()];
168 binary
169 })
170 }
171
172 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
173 vec!["rustc".into()]
174 }
175
176 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
177 Some("rust-analyzer/flycheck".into())
178 }
179
180 fn process_diagnostics(&self, params: &mut lsp::PublishDiagnosticsParams) {
181 static REGEX: LazyLock<Regex> =
182 LazyLock::new(|| Regex::new(r"(?m)`([^`]+)\n`$").expect("Failed to create REGEX"));
183
184 for diagnostic in &mut params.diagnostics {
185 for message in diagnostic
186 .related_information
187 .iter_mut()
188 .flatten()
189 .map(|info| &mut info.message)
190 .chain([&mut diagnostic.message])
191 {
192 if let Cow::Owned(sanitized) = REGEX.replace_all(message, "`$1`") {
193 *message = sanitized;
194 }
195 }
196 }
197 }
198
199 async fn label_for_completion(
200 &self,
201 completion: &lsp::CompletionItem,
202 language: &Arc<Language>,
203 ) -> Option<CodeLabel> {
204 let detail = completion
205 .label_details
206 .as_ref()
207 .and_then(|detail| detail.detail.as_ref())
208 .or(completion.detail.as_ref())
209 .map(ToOwned::to_owned);
210 let function_signature = completion
211 .label_details
212 .as_ref()
213 .and_then(|detail| detail.description.as_ref())
214 .or(completion.detail.as_ref())
215 .map(ToOwned::to_owned);
216 match completion.kind {
217 Some(lsp::CompletionItemKind::FIELD) if detail.is_some() => {
218 let name = &completion.label;
219 let text = format!("{}: {}", name, detail.unwrap());
220 let source = Rope::from(format!("struct S {{ {} }}", text).as_str());
221 let runs = language.highlight_text(&source, 11..11 + text.len());
222 return Some(CodeLabel {
223 text,
224 runs,
225 filter_range: 0..name.len(),
226 });
227 }
228 Some(lsp::CompletionItemKind::CONSTANT | lsp::CompletionItemKind::VARIABLE)
229 if detail.is_some()
230 && completion.insert_text_format != Some(lsp::InsertTextFormat::SNIPPET) =>
231 {
232 let name = &completion.label;
233 let text = format!("{}: {}", name, detail.unwrap());
234 let source = Rope::from(format!("let {} = ();", text).as_str());
235 let runs = language.highlight_text(&source, 4..4 + text.len());
236 return Some(CodeLabel {
237 text,
238 runs,
239 filter_range: 0..name.len(),
240 });
241 }
242 Some(lsp::CompletionItemKind::FUNCTION | lsp::CompletionItemKind::METHOD)
243 if detail.is_some() =>
244 {
245 static REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new("\\(…?\\)").unwrap());
246
247 let detail = detail.unwrap();
248 const FUNCTION_PREFIXES: [&'static str; 6] = [
249 "async fn",
250 "async unsafe fn",
251 "const fn",
252 "const unsafe fn",
253 "unsafe fn",
254 "fn",
255 ];
256 // Is it function `async`?
257 let fn_keyword = FUNCTION_PREFIXES.iter().find_map(|prefix| {
258 function_signature.as_ref().and_then(|signature| {
259 signature
260 .strip_prefix(*prefix)
261 .map(|suffix| (*prefix, suffix))
262 })
263 });
264 // fn keyword should be followed by opening parenthesis.
265 if let Some((prefix, suffix)) = fn_keyword {
266 if detail.starts_with(" (") {
267 let mut text = REGEX.replace(&completion.label, suffix).to_string();
268 let source = Rope::from(format!("{prefix} {} {{}}", text).as_str());
269 let run_start = prefix.len() + 1;
270 let runs =
271 language.highlight_text(&source, run_start..run_start + text.len());
272 text.push_str(&detail);
273 return Some(CodeLabel {
274 filter_range: 0..completion.label.find('(').unwrap_or(text.len()),
275 text,
276 runs,
277 });
278 }
279 }
280 }
281 Some(kind) => {
282 let highlight_name = match kind {
283 lsp::CompletionItemKind::STRUCT
284 | lsp::CompletionItemKind::INTERFACE
285 | lsp::CompletionItemKind::ENUM => Some("type"),
286 lsp::CompletionItemKind::ENUM_MEMBER => Some("variant"),
287 lsp::CompletionItemKind::KEYWORD => Some("keyword"),
288 lsp::CompletionItemKind::VALUE | lsp::CompletionItemKind::CONSTANT => {
289 Some("constant")
290 }
291 _ => None,
292 };
293
294 let mut label = completion.label.clone();
295 if let Some(detail) = detail.filter(|detail| detail.starts_with(" (")) {
296 use std::fmt::Write;
297 write!(label, "{detail}").ok()?;
298 }
299 let mut label = CodeLabel::plain(label, None);
300 if let Some(highlight_name) = highlight_name {
301 let highlight_id = language.grammar()?.highlight_id_for_name(highlight_name)?;
302 label.runs.push((
303 0..label.text.rfind('(').unwrap_or(completion.label.len()),
304 highlight_id,
305 ));
306 }
307
308 return Some(label);
309 }
310 _ => {}
311 }
312 None
313 }
314
315 async fn label_for_symbol(
316 &self,
317 name: &str,
318 kind: lsp::SymbolKind,
319 language: &Arc<Language>,
320 ) -> Option<CodeLabel> {
321 let (text, filter_range, display_range) = match kind {
322 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
323 let text = format!("fn {} () {{}}", name);
324 let filter_range = 3..3 + name.len();
325 let display_range = 0..filter_range.end;
326 (text, filter_range, display_range)
327 }
328 lsp::SymbolKind::STRUCT => {
329 let text = format!("struct {} {{}}", name);
330 let filter_range = 7..7 + name.len();
331 let display_range = 0..filter_range.end;
332 (text, filter_range, display_range)
333 }
334 lsp::SymbolKind::ENUM => {
335 let text = format!("enum {} {{}}", name);
336 let filter_range = 5..5 + name.len();
337 let display_range = 0..filter_range.end;
338 (text, filter_range, display_range)
339 }
340 lsp::SymbolKind::INTERFACE => {
341 let text = format!("trait {} {{}}", name);
342 let filter_range = 6..6 + name.len();
343 let display_range = 0..filter_range.end;
344 (text, filter_range, display_range)
345 }
346 lsp::SymbolKind::CONSTANT => {
347 let text = format!("const {}: () = ();", name);
348 let filter_range = 6..6 + name.len();
349 let display_range = 0..filter_range.end;
350 (text, filter_range, display_range)
351 }
352 lsp::SymbolKind::MODULE => {
353 let text = format!("mod {} {{}}", name);
354 let filter_range = 4..4 + name.len();
355 let display_range = 0..filter_range.end;
356 (text, filter_range, display_range)
357 }
358 lsp::SymbolKind::TYPE_PARAMETER => {
359 let text = format!("type {} {{}}", name);
360 let filter_range = 5..5 + name.len();
361 let display_range = 0..filter_range.end;
362 (text, filter_range, display_range)
363 }
364 _ => return None,
365 };
366
367 Some(CodeLabel {
368 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
369 text: text[display_range].to_string(),
370 filter_range,
371 })
372 }
373}
374
375pub(crate) struct RustContextProvider;
376
377const RUST_PACKAGE_TASK_VARIABLE: VariableName =
378 VariableName::Custom(Cow::Borrowed("RUST_PACKAGE"));
379
380/// The bin name corresponding to the current file in Cargo.toml
381const RUST_BIN_NAME_TASK_VARIABLE: VariableName =
382 VariableName::Custom(Cow::Borrowed("RUST_BIN_NAME"));
383
384const RUST_MAIN_FUNCTION_TASK_VARIABLE: VariableName =
385 VariableName::Custom(Cow::Borrowed("_rust_main_function_end"));
386
387impl ContextProvider for RustContextProvider {
388 fn build_context(
389 &self,
390 task_variables: &TaskVariables,
391 location: &Location,
392 cx: &mut gpui::AppContext,
393 ) -> Result<TaskVariables> {
394 let local_abs_path = location
395 .buffer
396 .read(cx)
397 .file()
398 .and_then(|file| Some(file.as_local()?.abs_path(cx)));
399
400 let local_abs_path = local_abs_path.as_deref();
401
402 let is_main_function = task_variables
403 .get(&RUST_MAIN_FUNCTION_TASK_VARIABLE)
404 .is_some();
405
406 if is_main_function {
407 if let Some((package_name, bin_name)) = local_abs_path
408 .and_then(|local_abs_path| package_name_and_bin_name_from_abs_path(local_abs_path))
409 {
410 return Ok(TaskVariables::from_iter([
411 (RUST_PACKAGE_TASK_VARIABLE.clone(), package_name),
412 (RUST_BIN_NAME_TASK_VARIABLE.clone(), bin_name),
413 ]));
414 }
415 }
416
417 if let Some(package_name) = local_abs_path
418 .and_then(|local_abs_path| local_abs_path.parent())
419 .and_then(human_readable_package_name)
420 {
421 return Ok(TaskVariables::from_iter([(
422 RUST_PACKAGE_TASK_VARIABLE.clone(),
423 package_name,
424 )]));
425 }
426
427 Ok(TaskVariables::default())
428 }
429
430 fn associated_tasks(
431 &self,
432 file: Option<Arc<dyn language::File>>,
433 cx: &AppContext,
434 ) -> Option<TaskTemplates> {
435 const DEFAULT_RUN_NAME_STR: &'static str = "RUST_DEFAULT_PACKAGE_RUN";
436 let package_to_run = all_language_settings(file.as_ref(), cx)
437 .language(Some("Rust"))
438 .tasks
439 .variables
440 .get(DEFAULT_RUN_NAME_STR);
441 let run_task_args = if let Some(package_to_run) = package_to_run {
442 vec!["run".into(), "-p".into(), package_to_run.clone()]
443 } else {
444 vec!["run".into()]
445 };
446 Some(TaskTemplates(vec![
447 TaskTemplate {
448 label: format!(
449 "cargo check -p {}",
450 RUST_PACKAGE_TASK_VARIABLE.template_value(),
451 ),
452 command: "cargo".into(),
453 args: vec![
454 "check".into(),
455 "-p".into(),
456 RUST_PACKAGE_TASK_VARIABLE.template_value(),
457 ],
458 cwd: Some("$ZED_DIRNAME".to_owned()),
459 ..TaskTemplate::default()
460 },
461 TaskTemplate {
462 label: "cargo check --workspace --all-targets".into(),
463 command: "cargo".into(),
464 args: vec!["check".into(), "--workspace".into(), "--all-targets".into()],
465 cwd: Some("$ZED_DIRNAME".to_owned()),
466 ..TaskTemplate::default()
467 },
468 TaskTemplate {
469 label: format!(
470 "cargo test -p {} {} -- --nocapture",
471 RUST_PACKAGE_TASK_VARIABLE.template_value(),
472 VariableName::Symbol.template_value(),
473 ),
474 command: "cargo".into(),
475 args: vec![
476 "test".into(),
477 "-p".into(),
478 RUST_PACKAGE_TASK_VARIABLE.template_value(),
479 VariableName::Symbol.template_value(),
480 "--".into(),
481 "--nocapture".into(),
482 ],
483 tags: vec!["rust-test".to_owned()],
484 cwd: Some("$ZED_DIRNAME".to_owned()),
485 ..TaskTemplate::default()
486 },
487 TaskTemplate {
488 label: format!(
489 "cargo test -p {} {}",
490 RUST_PACKAGE_TASK_VARIABLE.template_value(),
491 VariableName::Stem.template_value(),
492 ),
493 command: "cargo".into(),
494 args: vec![
495 "test".into(),
496 "-p".into(),
497 RUST_PACKAGE_TASK_VARIABLE.template_value(),
498 VariableName::Stem.template_value(),
499 ],
500 tags: vec!["rust-mod-test".to_owned()],
501 cwd: Some("$ZED_DIRNAME".to_owned()),
502 ..TaskTemplate::default()
503 },
504 TaskTemplate {
505 label: format!(
506 "cargo run -p {} --bin {}",
507 RUST_PACKAGE_TASK_VARIABLE.template_value(),
508 RUST_BIN_NAME_TASK_VARIABLE.template_value(),
509 ),
510 command: "cargo".into(),
511 args: vec![
512 "run".into(),
513 "-p".into(),
514 RUST_PACKAGE_TASK_VARIABLE.template_value(),
515 "--bin".into(),
516 RUST_BIN_NAME_TASK_VARIABLE.template_value(),
517 ],
518 cwd: Some("$ZED_DIRNAME".to_owned()),
519 tags: vec!["rust-main".to_owned()],
520 ..TaskTemplate::default()
521 },
522 TaskTemplate {
523 label: format!(
524 "cargo test -p {}",
525 RUST_PACKAGE_TASK_VARIABLE.template_value()
526 ),
527 command: "cargo".into(),
528 args: vec![
529 "test".into(),
530 "-p".into(),
531 RUST_PACKAGE_TASK_VARIABLE.template_value(),
532 ],
533 cwd: Some("$ZED_DIRNAME".to_owned()),
534 ..TaskTemplate::default()
535 },
536 TaskTemplate {
537 label: "cargo run".into(),
538 command: "cargo".into(),
539 args: run_task_args,
540 cwd: Some("$ZED_DIRNAME".to_owned()),
541 ..TaskTemplate::default()
542 },
543 TaskTemplate {
544 label: "cargo clean".into(),
545 command: "cargo".into(),
546 args: vec!["clean".into()],
547 cwd: Some("$ZED_DIRNAME".to_owned()),
548 ..TaskTemplate::default()
549 },
550 ]))
551 }
552}
553
554/// Part of the data structure of Cargo metadata
555#[derive(serde::Deserialize)]
556struct CargoMetadata {
557 packages: Vec<CargoPackage>,
558}
559
560#[derive(serde::Deserialize)]
561struct CargoPackage {
562 id: String,
563 targets: Vec<CargoTarget>,
564}
565
566#[derive(serde::Deserialize)]
567struct CargoTarget {
568 name: String,
569 kind: Vec<String>,
570 src_path: String,
571}
572
573fn package_name_and_bin_name_from_abs_path(abs_path: &Path) -> Option<(String, String)> {
574 let output = std::process::Command::new("cargo")
575 .current_dir(abs_path.parent()?)
576 .arg("metadata")
577 .arg("--no-deps")
578 .arg("--format-version")
579 .arg("1")
580 .output()
581 .log_err()?
582 .stdout;
583
584 let metadata: CargoMetadata = serde_json::from_slice(&output).log_err()?;
585
586 retrieve_package_id_and_bin_name_from_metadata(metadata, abs_path).and_then(
587 |(package_id, bin_name)| {
588 let package_name = package_name_from_pkgid(&package_id);
589
590 package_name.map(|package_name| (package_name.to_owned(), bin_name))
591 },
592 )
593}
594
595fn retrieve_package_id_and_bin_name_from_metadata(
596 metadata: CargoMetadata,
597 abs_path: &Path,
598) -> Option<(String, String)> {
599 for package in metadata.packages {
600 for target in package.targets {
601 let is_bin = target.kind.iter().any(|kind| kind == "bin");
602 let target_path = PathBuf::from(target.src_path);
603 if target_path == abs_path && is_bin {
604 return Some((package.id, target.name));
605 }
606 }
607 }
608
609 None
610}
611
612fn human_readable_package_name(package_directory: &Path) -> Option<String> {
613 let pkgid = String::from_utf8(
614 std::process::Command::new("cargo")
615 .current_dir(package_directory)
616 .arg("pkgid")
617 .output()
618 .log_err()?
619 .stdout,
620 )
621 .ok()?;
622 Some(package_name_from_pkgid(&pkgid)?.to_owned())
623}
624
625// For providing local `cargo check -p $pkgid` task, we do not need most of the information we have returned.
626// Output example in the root of Zed project:
627// ```sh
628// ❯ cargo pkgid zed
629// path+file:///absolute/path/to/project/zed/crates/zed#0.131.0
630// ```
631// Another variant, if a project has a custom package name or hyphen in the name:
632// ```
633// path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0
634// ```
635//
636// Extracts the package name from the output according to the spec:
637// https://doc.rust-lang.org/cargo/reference/pkgid-spec.html#specification-grammar
638fn package_name_from_pkgid(pkgid: &str) -> Option<&str> {
639 fn split_off_suffix(input: &str, suffix_start: char) -> &str {
640 match input.rsplit_once(suffix_start) {
641 Some((without_suffix, _)) => without_suffix,
642 None => input,
643 }
644 }
645
646 let (version_prefix, version_suffix) = pkgid.trim().rsplit_once('#')?;
647 let package_name = match version_suffix.rsplit_once('@') {
648 Some((custom_package_name, _version)) => custom_package_name,
649 None => {
650 let host_and_path = split_off_suffix(version_prefix, '?');
651 let (_, package_name) = host_and_path.rsplit_once('/')?;
652 package_name
653 }
654 };
655 Some(package_name)
656}
657
658async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
659 maybe!(async {
660 let mut last = None;
661 let mut entries = fs::read_dir(&container_dir).await?;
662 while let Some(entry) = entries.next().await {
663 last = Some(entry?.path());
664 }
665
666 anyhow::Ok(LanguageServerBinary {
667 path: last.ok_or_else(|| anyhow!("no cached binary"))?,
668 env: None,
669 arguments: Default::default(),
670 })
671 })
672 .await
673 .log_err()
674}
675
676#[cfg(test)]
677mod tests {
678 use std::num::NonZeroU32;
679
680 use super::*;
681 use crate::language;
682 use gpui::{BorrowAppContext, Context, Hsla, TestAppContext};
683 use language::language_settings::AllLanguageSettings;
684 use lsp::CompletionItemLabelDetails;
685 use settings::SettingsStore;
686 use theme::SyntaxTheme;
687
688 #[gpui::test]
689 async fn test_process_rust_diagnostics() {
690 let mut params = lsp::PublishDiagnosticsParams {
691 uri: lsp::Url::from_file_path("/a").unwrap(),
692 version: None,
693 diagnostics: vec![
694 // no newlines
695 lsp::Diagnostic {
696 message: "use of moved value `a`".to_string(),
697 ..Default::default()
698 },
699 // newline at the end of a code span
700 lsp::Diagnostic {
701 message: "consider importing this struct: `use b::c;\n`".to_string(),
702 ..Default::default()
703 },
704 // code span starting right after a newline
705 lsp::Diagnostic {
706 message: "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
707 .to_string(),
708 ..Default::default()
709 },
710 ],
711 };
712 RustLspAdapter.process_diagnostics(&mut params);
713
714 assert_eq!(params.diagnostics[0].message, "use of moved value `a`");
715
716 // remove trailing newline from code span
717 assert_eq!(
718 params.diagnostics[1].message,
719 "consider importing this struct: `use b::c;`"
720 );
721
722 // do not remove newline before the start of code span
723 assert_eq!(
724 params.diagnostics[2].message,
725 "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
726 );
727 }
728
729 #[gpui::test]
730 async fn test_rust_label_for_completion() {
731 let adapter = Arc::new(RustLspAdapter);
732 let language = language("rust", tree_sitter_rust::language());
733 let grammar = language.grammar().unwrap();
734 let theme = SyntaxTheme::new_test([
735 ("type", Hsla::default()),
736 ("keyword", Hsla::default()),
737 ("function", Hsla::default()),
738 ("property", Hsla::default()),
739 ]);
740
741 language.set_theme(&theme);
742
743 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
744 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
745 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
746 let highlight_field = grammar.highlight_id_for_name("property").unwrap();
747
748 assert_eq!(
749 adapter
750 .label_for_completion(
751 &lsp::CompletionItem {
752 kind: Some(lsp::CompletionItemKind::FUNCTION),
753 label: "hello(…)".to_string(),
754 label_details: Some(CompletionItemLabelDetails {
755 detail: Some(" (use crate::foo)".into()),
756 description: Some("fn(&mut Option<T>) -> Vec<T>".to_string())
757 }),
758 ..Default::default()
759 },
760 &language
761 )
762 .await,
763 Some(CodeLabel {
764 text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
765 filter_range: 0..5,
766 runs: vec![
767 (0..5, highlight_function),
768 (7..10, highlight_keyword),
769 (11..17, highlight_type),
770 (18..19, highlight_type),
771 (25..28, highlight_type),
772 (29..30, highlight_type),
773 ],
774 })
775 );
776 assert_eq!(
777 adapter
778 .label_for_completion(
779 &lsp::CompletionItem {
780 kind: Some(lsp::CompletionItemKind::FUNCTION),
781 label: "hello(…)".to_string(),
782 label_details: Some(CompletionItemLabelDetails {
783 detail: Some(" (use crate::foo)".into()),
784 description: Some("async fn(&mut Option<T>) -> Vec<T>".to_string()),
785 }),
786 ..Default::default()
787 },
788 &language
789 )
790 .await,
791 Some(CodeLabel {
792 text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
793 filter_range: 0..5,
794 runs: vec![
795 (0..5, highlight_function),
796 (7..10, highlight_keyword),
797 (11..17, highlight_type),
798 (18..19, highlight_type),
799 (25..28, highlight_type),
800 (29..30, highlight_type),
801 ],
802 })
803 );
804 assert_eq!(
805 adapter
806 .label_for_completion(
807 &lsp::CompletionItem {
808 kind: Some(lsp::CompletionItemKind::FIELD),
809 label: "len".to_string(),
810 detail: Some("usize".to_string()),
811 ..Default::default()
812 },
813 &language
814 )
815 .await,
816 Some(CodeLabel {
817 text: "len: usize".to_string(),
818 filter_range: 0..3,
819 runs: vec![(0..3, highlight_field), (5..10, highlight_type),],
820 })
821 );
822
823 assert_eq!(
824 adapter
825 .label_for_completion(
826 &lsp::CompletionItem {
827 kind: Some(lsp::CompletionItemKind::FUNCTION),
828 label: "hello(…)".to_string(),
829 label_details: Some(CompletionItemLabelDetails {
830 detail: Some(" (use crate::foo)".to_string()),
831 description: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
832 }),
833
834 ..Default::default()
835 },
836 &language
837 )
838 .await,
839 Some(CodeLabel {
840 text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
841 filter_range: 0..5,
842 runs: vec![
843 (0..5, highlight_function),
844 (7..10, highlight_keyword),
845 (11..17, highlight_type),
846 (18..19, highlight_type),
847 (25..28, highlight_type),
848 (29..30, highlight_type),
849 ],
850 })
851 );
852 }
853
854 #[gpui::test]
855 async fn test_rust_label_for_symbol() {
856 let adapter = Arc::new(RustLspAdapter);
857 let language = language("rust", tree_sitter_rust::language());
858 let grammar = language.grammar().unwrap();
859 let theme = SyntaxTheme::new_test([
860 ("type", Hsla::default()),
861 ("keyword", Hsla::default()),
862 ("function", Hsla::default()),
863 ("property", Hsla::default()),
864 ]);
865
866 language.set_theme(&theme);
867
868 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
869 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
870 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
871
872 assert_eq!(
873 adapter
874 .label_for_symbol("hello", lsp::SymbolKind::FUNCTION, &language)
875 .await,
876 Some(CodeLabel {
877 text: "fn hello".to_string(),
878 filter_range: 3..8,
879 runs: vec![(0..2, highlight_keyword), (3..8, highlight_function)],
880 })
881 );
882
883 assert_eq!(
884 adapter
885 .label_for_symbol("World", lsp::SymbolKind::TYPE_PARAMETER, &language)
886 .await,
887 Some(CodeLabel {
888 text: "type World".to_string(),
889 filter_range: 5..10,
890 runs: vec![(0..4, highlight_keyword), (5..10, highlight_type)],
891 })
892 );
893 }
894
895 #[gpui::test]
896 async fn test_rust_autoindent(cx: &mut TestAppContext) {
897 // cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
898 cx.update(|cx| {
899 let test_settings = SettingsStore::test(cx);
900 cx.set_global(test_settings);
901 language::init(cx);
902 cx.update_global::<SettingsStore, _>(|store, cx| {
903 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
904 s.defaults.tab_size = NonZeroU32::new(2);
905 });
906 });
907 });
908
909 let language = crate::language("rust", tree_sitter_rust::language());
910
911 cx.new_model(|cx| {
912 let mut buffer = Buffer::local("", cx).with_language(language, cx);
913
914 // indent between braces
915 buffer.set_text("fn a() {}", cx);
916 let ix = buffer.len() - 1;
917 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
918 assert_eq!(buffer.text(), "fn a() {\n \n}");
919
920 // indent between braces, even after empty lines
921 buffer.set_text("fn a() {\n\n\n}", cx);
922 let ix = buffer.len() - 2;
923 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
924 assert_eq!(buffer.text(), "fn a() {\n\n\n \n}");
925
926 // indent a line that continues a field expression
927 buffer.set_text("fn a() {\n \n}", cx);
928 let ix = buffer.len() - 2;
929 buffer.edit([(ix..ix, "b\n.c")], Some(AutoindentMode::EachLine), cx);
930 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n}");
931
932 // indent further lines that continue the field expression, even after empty lines
933 let ix = buffer.len() - 2;
934 buffer.edit([(ix..ix, "\n\n.d")], Some(AutoindentMode::EachLine), cx);
935 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n \n .d\n}");
936
937 // dedent the line after the field expression
938 let ix = buffer.len() - 2;
939 buffer.edit([(ix..ix, ";\ne")], Some(AutoindentMode::EachLine), cx);
940 assert_eq!(
941 buffer.text(),
942 "fn a() {\n b\n .c\n \n .d;\n e\n}"
943 );
944
945 // indent inside a struct within a call
946 buffer.set_text("const a: B = c(D {});", cx);
947 let ix = buffer.len() - 3;
948 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
949 assert_eq!(buffer.text(), "const a: B = c(D {\n \n});");
950
951 // indent further inside a nested call
952 let ix = buffer.len() - 4;
953 buffer.edit([(ix..ix, "e: f(\n\n)")], Some(AutoindentMode::EachLine), cx);
954 assert_eq!(buffer.text(), "const a: B = c(D {\n e: f(\n \n )\n});");
955
956 // keep that indent after an empty line
957 let ix = buffer.len() - 8;
958 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
959 assert_eq!(
960 buffer.text(),
961 "const a: B = c(D {\n e: f(\n \n \n )\n});"
962 );
963
964 buffer
965 });
966 }
967
968 #[test]
969 fn test_package_name_from_pkgid() {
970 for (input, expected) in [
971 (
972 "path+file:///absolute/path/to/project/zed/crates/zed#0.131.0",
973 "zed",
974 ),
975 (
976 "path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0",
977 "my-custom-package",
978 ),
979 ] {
980 assert_eq!(package_name_from_pkgid(input), Some(expected));
981 }
982 }
983
984 #[test]
985 fn test_retrieve_package_id_and_bin_name_from_metadata() {
986 for (input, absolute_path, expected) in [
987 (
988 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"}]}]}"#,
989 "/path/to/zed/src/main.rs",
990 Some(("path+file:///path/to/zed/crates/zed#0.131.0", "zed")),
991 ),
992 (
993 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"}]}]}"#,
994 "/path/to/custom-package/src/main.rs",
995 Some((
996 "path+file:///path/to/custom-package#my-custom-package@0.1.0",
997 "my-custom-bin",
998 )),
999 ),
1000 (
1001 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"}]}]}"#,
1002 "/path/to/custom-package/src/main.rs",
1003 None,
1004 ),
1005 ] {
1006 let metadata: CargoMetadata = serde_json::from_str(input).unwrap();
1007
1008 let absolute_path = Path::new(absolute_path);
1009
1010 assert_eq!(
1011 retrieve_package_id_and_bin_name_from_metadata(metadata, absolute_path),
1012 expected.map(|(pkgid, bin)| (pkgid.to_owned(), bin.to_owned()))
1013 );
1014 }
1015 }
1016}