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, VariableName,
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
325const RUST_PACKAGE_TASK_VARIABLE: VariableName =
326 VariableName::Custom(Cow::Borrowed("RUST_PACKAGE"));
327
328impl ContextProvider for RustContextProvider {
329 fn build_context(
330 &self,
331 location: Location,
332 cx: &mut gpui::AppContext,
333 ) -> Result<TaskVariables> {
334 let mut context = SymbolContextProvider.build_context(location.clone(), cx)?;
335
336 if let Some(path) = location.buffer.read(cx).file().and_then(|file| {
337 let local_file = file.as_local()?.abs_path(cx);
338 local_file.parent().map(PathBuf::from)
339 }) {
340 let Some(pkgid) = std::process::Command::new("cargo")
341 .current_dir(path)
342 .arg("pkgid")
343 .output()
344 .log_err()
345 else {
346 return Ok(context);
347 };
348 let package_name = String::from_utf8(pkgid.stdout)
349 .map(|name| name.trim().to_owned())
350 .ok();
351
352 if let Some(package_name) = package_name {
353 context.insert(RUST_PACKAGE_TASK_VARIABLE.clone(), package_name);
354 }
355 }
356
357 Ok(context)
358 }
359
360 fn associated_tasks(&self) -> Option<TaskDefinitions> {
361 Some(TaskDefinitions(vec![
362 Definition {
363 label: "Rust: Test current crate".to_owned(),
364 command: "cargo".into(),
365 args: vec![
366 "test".into(),
367 "-p".into(),
368 RUST_PACKAGE_TASK_VARIABLE.template_value(),
369 ],
370 ..Definition::default()
371 },
372 Definition {
373 label: "Rust: Test current function".to_owned(),
374 command: "cargo".into(),
375 args: vec![
376 "test".into(),
377 "-p".into(),
378 RUST_PACKAGE_TASK_VARIABLE.template_value(),
379 VariableName::Symbol.template_value(),
380 "--".into(),
381 "--nocapture".into(),
382 ],
383 ..Definition::default()
384 },
385 Definition {
386 label: "Rust: cargo run".into(),
387 command: "cargo".into(),
388 args: vec!["run".into()],
389 ..Definition::default()
390 },
391 Definition {
392 label: "Rust: cargo check current crate".into(),
393 command: "cargo".into(),
394 args: vec![
395 "check".into(),
396 "-p".into(),
397 RUST_PACKAGE_TASK_VARIABLE.template_value(),
398 ],
399 ..Definition::default()
400 },
401 Definition {
402 label: "Rust: cargo check workspace".into(),
403 command: "cargo".into(),
404 args: vec!["check".into(), "--workspace".into()],
405 ..Definition::default()
406 },
407 ]))
408 }
409}
410
411async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
412 maybe!(async {
413 let mut last = None;
414 let mut entries = fs::read_dir(&container_dir).await?;
415 while let Some(entry) = entries.next().await {
416 last = Some(entry?.path());
417 }
418
419 anyhow::Ok(LanguageServerBinary {
420 path: last.ok_or_else(|| anyhow!("no cached binary"))?,
421 env: None,
422 arguments: Default::default(),
423 })
424 })
425 .await
426 .log_err()
427}
428
429#[cfg(test)]
430mod tests {
431 use std::num::NonZeroU32;
432
433 use super::*;
434 use crate::language;
435 use gpui::{BorrowAppContext, Context, Hsla, TestAppContext};
436 use language::language_settings::AllLanguageSettings;
437 use settings::SettingsStore;
438 use text::BufferId;
439 use theme::SyntaxTheme;
440
441 #[gpui::test]
442 async fn test_process_rust_diagnostics() {
443 let mut params = lsp::PublishDiagnosticsParams {
444 uri: lsp::Url::from_file_path("/a").unwrap(),
445 version: None,
446 diagnostics: vec![
447 // no newlines
448 lsp::Diagnostic {
449 message: "use of moved value `a`".to_string(),
450 ..Default::default()
451 },
452 // newline at the end of a code span
453 lsp::Diagnostic {
454 message: "consider importing this struct: `use b::c;\n`".to_string(),
455 ..Default::default()
456 },
457 // code span starting right after a newline
458 lsp::Diagnostic {
459 message: "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
460 .to_string(),
461 ..Default::default()
462 },
463 ],
464 };
465 RustLspAdapter.process_diagnostics(&mut params);
466
467 assert_eq!(params.diagnostics[0].message, "use of moved value `a`");
468
469 // remove trailing newline from code span
470 assert_eq!(
471 params.diagnostics[1].message,
472 "consider importing this struct: `use b::c;`"
473 );
474
475 // do not remove newline before the start of code span
476 assert_eq!(
477 params.diagnostics[2].message,
478 "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
479 );
480 }
481
482 #[gpui::test]
483 async fn test_rust_label_for_completion() {
484 let adapter = Arc::new(RustLspAdapter);
485 let language = language("rust", tree_sitter_rust::language());
486 let grammar = language.grammar().unwrap();
487 let theme = SyntaxTheme::new_test([
488 ("type", Hsla::default()),
489 ("keyword", Hsla::default()),
490 ("function", Hsla::default()),
491 ("property", Hsla::default()),
492 ]);
493
494 language.set_theme(&theme);
495
496 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
497 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
498 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
499 let highlight_field = grammar.highlight_id_for_name("property").unwrap();
500
501 assert_eq!(
502 adapter
503 .label_for_completion(
504 &lsp::CompletionItem {
505 kind: Some(lsp::CompletionItemKind::FUNCTION),
506 label: "hello(…)".to_string(),
507 detail: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
508 ..Default::default()
509 },
510 &language
511 )
512 .await,
513 Some(CodeLabel {
514 text: "hello(&mut Option<T>) -> Vec<T>".to_string(),
515 filter_range: 0..5,
516 runs: vec![
517 (0..5, highlight_function),
518 (7..10, highlight_keyword),
519 (11..17, highlight_type),
520 (18..19, highlight_type),
521 (25..28, highlight_type),
522 (29..30, highlight_type),
523 ],
524 })
525 );
526 assert_eq!(
527 adapter
528 .label_for_completion(
529 &lsp::CompletionItem {
530 kind: Some(lsp::CompletionItemKind::FUNCTION),
531 label: "hello(…)".to_string(),
532 detail: Some("async fn(&mut Option<T>) -> Vec<T>".to_string()),
533 ..Default::default()
534 },
535 &language
536 )
537 .await,
538 Some(CodeLabel {
539 text: "hello(&mut Option<T>) -> Vec<T>".to_string(),
540 filter_range: 0..5,
541 runs: vec![
542 (0..5, highlight_function),
543 (7..10, highlight_keyword),
544 (11..17, highlight_type),
545 (18..19, highlight_type),
546 (25..28, highlight_type),
547 (29..30, highlight_type),
548 ],
549 })
550 );
551 assert_eq!(
552 adapter
553 .label_for_completion(
554 &lsp::CompletionItem {
555 kind: Some(lsp::CompletionItemKind::FIELD),
556 label: "len".to_string(),
557 detail: Some("usize".to_string()),
558 ..Default::default()
559 },
560 &language
561 )
562 .await,
563 Some(CodeLabel {
564 text: "len: usize".to_string(),
565 filter_range: 0..3,
566 runs: vec![(0..3, highlight_field), (5..10, highlight_type),],
567 })
568 );
569
570 assert_eq!(
571 adapter
572 .label_for_completion(
573 &lsp::CompletionItem {
574 kind: Some(lsp::CompletionItemKind::FUNCTION),
575 label: "hello(…)".to_string(),
576 detail: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
577 ..Default::default()
578 },
579 &language
580 )
581 .await,
582 Some(CodeLabel {
583 text: "hello(&mut Option<T>) -> Vec<T>".to_string(),
584 filter_range: 0..5,
585 runs: vec![
586 (0..5, highlight_function),
587 (7..10, highlight_keyword),
588 (11..17, highlight_type),
589 (18..19, highlight_type),
590 (25..28, highlight_type),
591 (29..30, highlight_type),
592 ],
593 })
594 );
595 }
596
597 #[gpui::test]
598 async fn test_rust_label_for_symbol() {
599 let adapter = Arc::new(RustLspAdapter);
600 let language = language("rust", tree_sitter_rust::language());
601 let grammar = language.grammar().unwrap();
602 let theme = SyntaxTheme::new_test([
603 ("type", Hsla::default()),
604 ("keyword", Hsla::default()),
605 ("function", Hsla::default()),
606 ("property", Hsla::default()),
607 ]);
608
609 language.set_theme(&theme);
610
611 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
612 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
613 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
614
615 assert_eq!(
616 adapter
617 .label_for_symbol("hello", lsp::SymbolKind::FUNCTION, &language)
618 .await,
619 Some(CodeLabel {
620 text: "fn hello".to_string(),
621 filter_range: 3..8,
622 runs: vec![(0..2, highlight_keyword), (3..8, highlight_function)],
623 })
624 );
625
626 assert_eq!(
627 adapter
628 .label_for_symbol("World", lsp::SymbolKind::TYPE_PARAMETER, &language)
629 .await,
630 Some(CodeLabel {
631 text: "type World".to_string(),
632 filter_range: 5..10,
633 runs: vec![(0..4, highlight_keyword), (5..10, highlight_type)],
634 })
635 );
636 }
637
638 #[gpui::test]
639 async fn test_rust_autoindent(cx: &mut TestAppContext) {
640 // cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
641 cx.update(|cx| {
642 let test_settings = SettingsStore::test(cx);
643 cx.set_global(test_settings);
644 language::init(cx);
645 cx.update_global::<SettingsStore, _>(|store, cx| {
646 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
647 s.defaults.tab_size = NonZeroU32::new(2);
648 });
649 });
650 });
651
652 let language = crate::language("rust", tree_sitter_rust::language());
653
654 cx.new_model(|cx| {
655 let mut buffer = Buffer::new(0, BufferId::new(cx.entity_id().as_u64()).unwrap(), "")
656 .with_language(language, cx);
657
658 // indent between braces
659 buffer.set_text("fn a() {}", cx);
660 let ix = buffer.len() - 1;
661 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
662 assert_eq!(buffer.text(), "fn a() {\n \n}");
663
664 // indent between braces, even after empty lines
665 buffer.set_text("fn a() {\n\n\n}", cx);
666 let ix = buffer.len() - 2;
667 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
668 assert_eq!(buffer.text(), "fn a() {\n\n\n \n}");
669
670 // indent a line that continues a field expression
671 buffer.set_text("fn a() {\n \n}", cx);
672 let ix = buffer.len() - 2;
673 buffer.edit([(ix..ix, "b\n.c")], Some(AutoindentMode::EachLine), cx);
674 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n}");
675
676 // indent further lines that continue the field expression, even after empty lines
677 let ix = buffer.len() - 2;
678 buffer.edit([(ix..ix, "\n\n.d")], Some(AutoindentMode::EachLine), cx);
679 assert_eq!(buffer.text(), "fn a() {\n b\n .c\n \n .d\n}");
680
681 // dedent the line after the field expression
682 let ix = buffer.len() - 2;
683 buffer.edit([(ix..ix, ";\ne")], Some(AutoindentMode::EachLine), cx);
684 assert_eq!(
685 buffer.text(),
686 "fn a() {\n b\n .c\n \n .d;\n e\n}"
687 );
688
689 // indent inside a struct within a call
690 buffer.set_text("const a: B = c(D {});", cx);
691 let ix = buffer.len() - 3;
692 buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
693 assert_eq!(buffer.text(), "const a: B = c(D {\n \n});");
694
695 // indent further inside a nested call
696 let ix = buffer.len() - 4;
697 buffer.edit([(ix..ix, "e: f(\n\n)")], Some(AutoindentMode::EachLine), cx);
698 assert_eq!(buffer.text(), "const a: B = c(D {\n e: f(\n \n )\n});");
699
700 // keep that indent after an empty line
701 let ix = buffer.len() - 8;
702 buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
703 assert_eq!(
704 buffer.text(),
705 "const a: B = c(D {\n e: f(\n \n \n )\n});"
706 );
707
708 buffer
709 });
710 }
711}