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