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