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