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