1use anyhow::{anyhow, bail, Context, Result};
2use async_compression::futures::bufread::GzipDecoder;
3use async_trait::async_trait;
4use futures::{io::BufReader, StreamExt};
5use gpui::AsyncAppContext;
6pub use language::*;
7use lazy_static::lazy_static;
8use lsp::LanguageServerBinary;
9use project::project_settings::ProjectSettings;
10use regex::Regex;
11use settings::Settings;
12use smol::fs::{self, File};
13use std::{any::Any, borrow::Cow, env::consts, path::PathBuf, sync::Arc};
14use task::{
15 static_source::{Definition, TaskDefinitions},
16 TaskVariables,
17};
18use util::{
19 fs::remove_matching,
20 github::{latest_github_release, GitHubLspBinaryVersion},
21 maybe, ResultExt,
22};
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 binary = cx
42 .update(|cx| {
43 ProjectSettings::get_global(cx)
44 .lsp
45 .get(Self::SERVER_NAME)
46 .and_then(|s| s.binary.clone())
47 })
48 .ok()??;
49
50 let path = binary.path?;
51 Some(LanguageServerBinary {
52 path: path.into(),
53 arguments: binary
54 .arguments
55 .unwrap_or_default()
56 .iter()
57 .map(|arg| arg.into())
58 .collect(),
59 env: None,
60 })
61 }
62
63 async fn fetch_latest_server_version(
64 &self,
65 delegate: &dyn LspAdapterDelegate,
66 ) -> Result<Box<dyn 'static + Send + Any>> {
67 let release = latest_github_release(
68 "rust-lang/rust-analyzer",
69 true,
70 false,
71 delegate.http_client(),
72 )
73 .await?;
74 let os = match consts::OS {
75 "macos" => "apple-darwin",
76 "linux" => "unknown-linux-gnu",
77 "windows" => "pc-windows-msvc",
78 other => bail!("Running on unsupported os: {other}"),
79 };
80 let asset_name = format!("rust-analyzer-{}-{os}.gz", consts::ARCH);
81 let asset = release
82 .assets
83 .iter()
84 .find(|asset| asset.name == asset_name)
85 .with_context(|| format!("no asset found matching `{asset_name:?}`"))?;
86 Ok(Box::new(GitHubLspBinaryVersion {
87 name: release.tag_name,
88 url: asset.browser_download_url.clone(),
89 }))
90 }
91
92 async fn fetch_server_binary(
93 &self,
94 version: Box<dyn 'static + Send + Any>,
95 container_dir: PathBuf,
96 delegate: &dyn LspAdapterDelegate,
97 ) -> Result<LanguageServerBinary> {
98 let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
99 let destination_path = container_dir.join(format!("rust-analyzer-{}", version.name));
100
101 if fs::metadata(&destination_path).await.is_err() {
102 let mut response = delegate
103 .http_client()
104 .get(&version.url, Default::default(), true)
105 .await
106 .map_err(|err| anyhow!("error downloading release: {}", err))?;
107 let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
108 let mut file = File::create(&destination_path).await?;
109 futures::io::copy(decompressed_bytes, &mut file).await?;
110 // todo("windows")
111 #[cfg(not(windows))]
112 {
113 fs::set_permissions(
114 &destination_path,
115 <fs::Permissions as fs::unix::PermissionsExt>::from_mode(0o755),
116 )
117 .await?;
118 }
119
120 remove_matching(&container_dir, |entry| entry != destination_path).await;
121 }
122
123 Ok(LanguageServerBinary {
124 path: destination_path,
125 env: None,
126 arguments: Default::default(),
127 })
128 }
129
130 async fn cached_server_binary(
131 &self,
132 container_dir: PathBuf,
133 _: &dyn LspAdapterDelegate,
134 ) -> Option<LanguageServerBinary> {
135 get_cached_server_binary(container_dir).await
136 }
137
138 async fn installation_test_binary(
139 &self,
140 container_dir: PathBuf,
141 ) -> Option<LanguageServerBinary> {
142 get_cached_server_binary(container_dir)
143 .await
144 .map(|mut binary| {
145 binary.arguments = vec!["--help".into()];
146 binary
147 })
148 }
149
150 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
151 vec!["rustc".into()]
152 }
153
154 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
155 Some("rust-analyzer/flycheck".into())
156 }
157
158 fn process_diagnostics(&self, params: &mut lsp::PublishDiagnosticsParams) {
159 lazy_static! {
160 static ref REGEX: Regex = Regex::new("(?m)`([^`]+)\n`$").unwrap();
161 }
162
163 for diagnostic in &mut params.diagnostics {
164 for message in diagnostic
165 .related_information
166 .iter_mut()
167 .flatten()
168 .map(|info| &mut info.message)
169 .chain([&mut diagnostic.message])
170 {
171 if let Cow::Owned(sanitized) = REGEX.replace_all(message, "`$1`") {
172 *message = sanitized;
173 }
174 }
175 }
176 }
177
178 async fn label_for_completion(
179 &self,
180 completion: &lsp::CompletionItem,
181 language: &Arc<Language>,
182 ) -> Option<CodeLabel> {
183 match completion.kind {
184 Some(lsp::CompletionItemKind::FIELD) if completion.detail.is_some() => {
185 let detail = completion.detail.as_ref().unwrap();
186 let name = &completion.label;
187 let text = format!("{}: {}", name, detail);
188 let source = Rope::from(format!("struct S {{ {} }}", text).as_str());
189 let runs = language.highlight_text(&source, 11..11 + text.len());
190 return Some(CodeLabel {
191 text,
192 runs,
193 filter_range: 0..name.len(),
194 });
195 }
196 Some(lsp::CompletionItemKind::CONSTANT | lsp::CompletionItemKind::VARIABLE)
197 if completion.detail.is_some()
198 && completion.insert_text_format != Some(lsp::InsertTextFormat::SNIPPET) =>
199 {
200 let detail = completion.detail.as_ref().unwrap();
201 let name = &completion.label;
202 let text = format!("{}: {}", name, detail);
203 let source = Rope::from(format!("let {} = ();", text).as_str());
204 let runs = language.highlight_text(&source, 4..4 + text.len());
205 return Some(CodeLabel {
206 text,
207 runs,
208 filter_range: 0..name.len(),
209 });
210 }
211 Some(lsp::CompletionItemKind::FUNCTION | lsp::CompletionItemKind::METHOD)
212 if completion.detail.is_some() =>
213 {
214 lazy_static! {
215 static ref REGEX: Regex = Regex::new("\\(…?\\)").unwrap();
216 }
217 let detail = completion.detail.as_ref().unwrap();
218 const FUNCTION_PREFIXES: [&'static str; 2] = ["async fn", "fn"];
219 let prefix = FUNCTION_PREFIXES
220 .iter()
221 .find_map(|prefix| detail.strip_prefix(*prefix).map(|suffix| (prefix, suffix)));
222 // fn keyword should be followed by opening parenthesis.
223 if let Some((prefix, suffix)) = prefix {
224 if suffix.starts_with('(') {
225 let text = REGEX.replace(&completion.label, suffix).to_string();
226 let source = Rope::from(format!("{prefix} {} {{}}", text).as_str());
227 let run_start = prefix.len() + 1;
228 let runs =
229 language.highlight_text(&source, run_start..run_start + text.len());
230 return Some(CodeLabel {
231 filter_range: 0..completion.label.find('(').unwrap_or(text.len()),
232 text,
233 runs,
234 });
235 }
236 }
237 }
238 Some(kind) => {
239 let highlight_name = match kind {
240 lsp::CompletionItemKind::STRUCT
241 | lsp::CompletionItemKind::INTERFACE
242 | lsp::CompletionItemKind::ENUM => Some("type"),
243 lsp::CompletionItemKind::ENUM_MEMBER => Some("variant"),
244 lsp::CompletionItemKind::KEYWORD => Some("keyword"),
245 lsp::CompletionItemKind::VALUE | lsp::CompletionItemKind::CONSTANT => {
246 Some("constant")
247 }
248 _ => None,
249 };
250 let highlight_id = language.grammar()?.highlight_id_for_name(highlight_name?)?;
251 let mut label = CodeLabel::plain(completion.label.clone(), None);
252 label.runs.push((
253 0..label.text.rfind('(').unwrap_or(label.text.len()),
254 highlight_id,
255 ));
256 return Some(label);
257 }
258 _ => {}
259 }
260 None
261 }
262
263 async fn label_for_symbol(
264 &self,
265 name: &str,
266 kind: lsp::SymbolKind,
267 language: &Arc<Language>,
268 ) -> Option<CodeLabel> {
269 let (text, filter_range, display_range) = match kind {
270 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
271 let text = format!("fn {} () {{}}", name);
272 let filter_range = 3..3 + name.len();
273 let display_range = 0..filter_range.end;
274 (text, filter_range, display_range)
275 }
276 lsp::SymbolKind::STRUCT => {
277 let text = format!("struct {} {{}}", name);
278 let filter_range = 7..7 + name.len();
279 let display_range = 0..filter_range.end;
280 (text, filter_range, display_range)
281 }
282 lsp::SymbolKind::ENUM => {
283 let text = format!("enum {} {{}}", name);
284 let filter_range = 5..5 + name.len();
285 let display_range = 0..filter_range.end;
286 (text, filter_range, display_range)
287 }
288 lsp::SymbolKind::INTERFACE => {
289 let text = format!("trait {} {{}}", name);
290 let filter_range = 6..6 + name.len();
291 let display_range = 0..filter_range.end;
292 (text, filter_range, display_range)
293 }
294 lsp::SymbolKind::CONSTANT => {
295 let text = format!("const {}: () = ();", name);
296 let filter_range = 6..6 + name.len();
297 let display_range = 0..filter_range.end;
298 (text, filter_range, display_range)
299 }
300 lsp::SymbolKind::MODULE => {
301 let text = format!("mod {} {{}}", name);
302 let filter_range = 4..4 + name.len();
303 let display_range = 0..filter_range.end;
304 (text, filter_range, display_range)
305 }
306 lsp::SymbolKind::TYPE_PARAMETER => {
307 let text = format!("type {} {{}}", name);
308 let filter_range = 5..5 + name.len();
309 let display_range = 0..filter_range.end;
310 (text, filter_range, display_range)
311 }
312 _ => return None,
313 };
314
315 Some(CodeLabel {
316 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
317 text: text[display_range].to_string(),
318 filter_range,
319 })
320 }
321}
322
323pub(crate) struct RustContextProvider;
324
325impl ContextProvider for RustContextProvider {
326 fn build_context(
327 &self,
328 location: Location,
329 cx: &mut gpui::AppContext,
330 ) -> Result<TaskVariables> {
331 let mut context = SymbolContextProvider.build_context(location.clone(), cx)?;
332
333 if let Some(path) = location.buffer.read(cx).file().and_then(|file| {
334 let local_file = file.as_local()?.abs_path(cx);
335 local_file.parent().map(PathBuf::from)
336 }) {
337 let Some(pkgid) = std::process::Command::new("cargo")
338 .current_dir(path)
339 .arg("pkgid")
340 .output()
341 .log_err()
342 else {
343 return Ok(context);
344 };
345 let package_name = String::from_utf8(pkgid.stdout)
346 .map(|name| name.trim().to_owned())
347 .ok();
348
349 if let Some(package_name) = package_name {
350 context.0.insert("ZED_PACKAGE".to_owned(), package_name);
351 }
352 }
353
354 Ok(context)
355 }
356 fn associated_tasks(&self) -> Option<TaskDefinitions> {
357 Some(TaskDefinitions(vec![
358 Definition {
359 label: "Rust: Test current crate".to_owned(),
360 command: "cargo".into(),
361 args: vec!["test".into(), "-p".into(), "$ZED_PACKAGE".into()],
362 ..Default::default()
363 },
364 Definition {
365 label: "Rust: Test current function".to_owned(),
366 command: "cargo".into(),
367 args: vec![
368 "test".into(),
369 "-p".into(),
370 "$ZED_PACKAGE".into(),
371 "--".into(),
372 "$ZED_SYMBOL".into(),
373 ],
374 ..Default::default()
375 },
376 Definition {
377 label: "Rust: cargo run".into(),
378 command: "cargo".into(),
379 args: vec!["run".into()],
380 ..Default::default()
381 },
382 Definition {
383 label: "Rust: cargo check current crate".into(),
384 command: "cargo".into(),
385 args: vec!["check".into(), "-p".into(), "$ZED_PACKAGE".into()],
386 ..Default::default()
387 },
388 Definition {
389 label: "Rust: cargo check workspace".into(),
390 command: "cargo".into(),
391 args: vec!["check".into(), "--workspace".into()],
392 ..Default::default()
393 },
394 ]))
395 }
396}
397
398async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
399 maybe!(async {
400 let mut last = None;
401 let mut entries = fs::read_dir(&container_dir).await?;
402 while let Some(entry) = entries.next().await {
403 last = Some(entry?.path());
404 }
405
406 anyhow::Ok(LanguageServerBinary {
407 path: last.ok_or_else(|| anyhow!("no cached binary"))?,
408 env: None,
409 arguments: Default::default(),
410 })
411 })
412 .await
413 .log_err()
414}
415
416#[cfg(test)]
417mod tests {
418 use std::num::NonZeroU32;
419
420 use super::*;
421 use crate::language;
422 use gpui::{BorrowAppContext, Context, Hsla, TestAppContext};
423 use language::language_settings::AllLanguageSettings;
424 use settings::SettingsStore;
425 use text::BufferId;
426 use theme::SyntaxTheme;
427
428 #[gpui::test]
429 async fn test_process_rust_diagnostics() {
430 let mut params = lsp::PublishDiagnosticsParams {
431 uri: lsp::Url::from_file_path("/a").unwrap(),
432 version: None,
433 diagnostics: vec![
434 // no newlines
435 lsp::Diagnostic {
436 message: "use of moved value `a`".to_string(),
437 ..Default::default()
438 },
439 // newline at the end of a code span
440 lsp::Diagnostic {
441 message: "consider importing this struct: `use b::c;\n`".to_string(),
442 ..Default::default()
443 },
444 // code span starting right after a newline
445 lsp::Diagnostic {
446 message: "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
447 .to_string(),
448 ..Default::default()
449 },
450 ],
451 };
452 RustLspAdapter.process_diagnostics(&mut params);
453
454 assert_eq!(params.diagnostics[0].message, "use of moved value `a`");
455
456 // remove trailing newline from code span
457 assert_eq!(
458 params.diagnostics[1].message,
459 "consider importing this struct: `use b::c;`"
460 );
461
462 // do not remove newline before the start of code span
463 assert_eq!(
464 params.diagnostics[2].message,
465 "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
466 );
467 }
468
469 #[gpui::test]
470 async fn test_rust_label_for_completion() {
471 let adapter = Arc::new(RustLspAdapter);
472 let language = language("rust", tree_sitter_rust::language());
473 let grammar = language.grammar().unwrap();
474 let theme = SyntaxTheme::new_test([
475 ("type", Hsla::default()),
476 ("keyword", Hsla::default()),
477 ("function", Hsla::default()),
478 ("property", Hsla::default()),
479 ]);
480
481 language.set_theme(&theme);
482
483 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
484 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
485 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
486 let highlight_field = grammar.highlight_id_for_name("property").unwrap();
487
488 assert_eq!(
489 adapter
490 .label_for_completion(
491 &lsp::CompletionItem {
492 kind: Some(lsp::CompletionItemKind::FUNCTION),
493 label: "hello(…)".to_string(),
494 detail: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
495 ..Default::default()
496 },
497 &language
498 )
499 .await,
500 Some(CodeLabel {
501 text: "hello(&mut Option<T>) -> Vec<T>".to_string(),
502 filter_range: 0..5,
503 runs: vec![
504 (0..5, highlight_function),
505 (7..10, highlight_keyword),
506 (11..17, highlight_type),
507 (18..19, highlight_type),
508 (25..28, highlight_type),
509 (29..30, highlight_type),
510 ],
511 })
512 );
513 assert_eq!(
514 adapter
515 .label_for_completion(
516 &lsp::CompletionItem {
517 kind: Some(lsp::CompletionItemKind::FUNCTION),
518 label: "hello(…)".to_string(),
519 detail: Some("async fn(&mut Option<T>) -> Vec<T>".to_string()),
520 ..Default::default()
521 },
522 &language
523 )
524 .await,
525 Some(CodeLabel {
526 text: "hello(&mut Option<T>) -> Vec<T>".to_string(),
527 filter_range: 0..5,
528 runs: vec![
529 (0..5, highlight_function),
530 (7..10, highlight_keyword),
531 (11..17, highlight_type),
532 (18..19, highlight_type),
533 (25..28, highlight_type),
534 (29..30, highlight_type),
535 ],
536 })
537 );
538 assert_eq!(
539 adapter
540 .label_for_completion(
541 &lsp::CompletionItem {
542 kind: Some(lsp::CompletionItemKind::FIELD),
543 label: "len".to_string(),
544 detail: Some("usize".to_string()),
545 ..Default::default()
546 },
547 &language
548 )
549 .await,
550 Some(CodeLabel {
551 text: "len: usize".to_string(),
552 filter_range: 0..3,
553 runs: vec![(0..3, highlight_field), (5..10, highlight_type),],
554 })
555 );
556
557 assert_eq!(
558 adapter
559 .label_for_completion(
560 &lsp::CompletionItem {
561 kind: Some(lsp::CompletionItemKind::FUNCTION),
562 label: "hello(…)".to_string(),
563 detail: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
564 ..Default::default()
565 },
566 &language
567 )
568 .await,
569 Some(CodeLabel {
570 text: "hello(&mut Option<T>) -> Vec<T>".to_string(),
571 filter_range: 0..5,
572 runs: vec![
573 (0..5, highlight_function),
574 (7..10, highlight_keyword),
575 (11..17, highlight_type),
576 (18..19, highlight_type),
577 (25..28, highlight_type),
578 (29..30, highlight_type),
579 ],
580 })
581 );
582 }
583
584 #[gpui::test]
585 async fn test_rust_label_for_symbol() {
586 let adapter = Arc::new(RustLspAdapter);
587 let language = language("rust", tree_sitter_rust::language());
588 let grammar = language.grammar().unwrap();
589 let theme = SyntaxTheme::new_test([
590 ("type", Hsla::default()),
591 ("keyword", Hsla::default()),
592 ("function", Hsla::default()),
593 ("property", Hsla::default()),
594 ]);
595
596 language.set_theme(&theme);
597
598 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
599 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
600 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
601
602 assert_eq!(
603 adapter
604 .label_for_symbol("hello", lsp::SymbolKind::FUNCTION, &language)
605 .await,
606 Some(CodeLabel {
607 text: "fn hello".to_string(),
608 filter_range: 3..8,
609 runs: vec![(0..2, highlight_keyword), (3..8, highlight_function)],
610 })
611 );
612
613 assert_eq!(
614 adapter
615 .label_for_symbol("World", lsp::SymbolKind::TYPE_PARAMETER, &language)
616 .await,
617 Some(CodeLabel {
618 text: "type World".to_string(),
619 filter_range: 5..10,
620 runs: vec![(0..4, highlight_keyword), (5..10, highlight_type)],
621 })
622 );
623 }
624
625 #[gpui::test]
626 async fn test_rust_autoindent(cx: &mut TestAppContext) {
627 // cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
628 cx.update(|cx| {
629 let test_settings = SettingsStore::test(cx);
630 cx.set_global(test_settings);
631 language::init(cx);
632 cx.update_global::<SettingsStore, _>(|store, cx| {
633 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
634 s.defaults.tab_size = NonZeroU32::new(2);
635 });
636 });
637 });
638
639 let language = crate::language("rust", tree_sitter_rust::language());
640
641 cx.new_model(|cx| {
642 let mut buffer = Buffer::new(0, BufferId::new(cx.entity_id().as_u64()).unwrap(), "")
643 .with_language(language, cx);
644
645 // indent between braces
646 buffer.set_text("fn a() {}", cx);
647 let ix = buffer.len() - 1;
648 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
649 assert_eq!(buffer.text(), "fn a() {\n \n}");
650
651 // indent between braces, even after empty lines
652 buffer.set_text("fn a() {\n\n\n}", cx);
653 let ix = buffer.len() - 2;
654 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
655 assert_eq!(buffer.text(), "fn a() {\n\n\n \n}");
656
657 // indent a line that continues a field expression
658 buffer.set_text("fn a() {\n \n}", cx);
659 let ix = buffer.len() - 2;
660 buffer.edit([(ix..ix, "b\n.c")], Some(AutoindentMode::EachLine), cx);
661 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n}");
662
663 // indent further lines that continue the field expression, even after empty lines
664 let ix = buffer.len() - 2;
665 buffer.edit([(ix..ix, "\n\n.d")], Some(AutoindentMode::EachLine), cx);
666 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n \n .d\n}");
667
668 // dedent the line after the field expression
669 let ix = buffer.len() - 2;
670 buffer.edit([(ix..ix, ";\ne")], Some(AutoindentMode::EachLine), cx);
671 assert_eq!(
672 buffer.text(),
673 "fn a() {\n b\n .c\n \n .d;\n e\n}"
674 );
675
676 // indent inside a struct within a call
677 buffer.set_text("const a: B = c(D {});", cx);
678 let ix = buffer.len() - 3;
679 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
680 assert_eq!(buffer.text(), "const a: B = c(D {\n \n});");
681
682 // indent further inside a nested call
683 let ix = buffer.len() - 4;
684 buffer.edit([(ix..ix, "e: f(\n\n)")], Some(AutoindentMode::EachLine), cx);
685 assert_eq!(buffer.text(), "const a: B = c(D {\n e: f(\n \n )\n});");
686
687 // keep that indent after an empty line
688 let ix = buffer.len() - 8;
689 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
690 assert_eq!(
691 buffer.text(),
692 "const a: B = c(D {\n e: f(\n \n \n )\n});"
693 );
694
695 buffer
696 });
697 }
698}