1use anyhow::{anyhow, Context, Result};
2use async_trait::async_trait;
3use futures::StreamExt;
4use gpui::{AsyncAppContext, Task};
5use http::github::latest_github_release;
6pub use language::*;
7use lazy_static::lazy_static;
8use lsp::LanguageServerBinary;
9use project::project_settings::{BinarySettings, ProjectSettings};
10use regex::Regex;
11use serde_json::json;
12use settings::Settings;
13use smol::{fs, process};
14use std::{
15 any::Any,
16 borrow::Cow,
17 ffi::{OsStr, OsString},
18 ops::Range,
19 path::PathBuf,
20 str,
21 sync::{
22 atomic::{AtomicBool, Ordering::SeqCst},
23 Arc,
24 },
25};
26use task::{TaskTemplate, TaskTemplates, TaskVariables, VariableName};
27use util::{fs::remove_matching, maybe, ResultExt};
28
29fn server_binary_arguments() -> Vec<OsString> {
30 vec!["-mode=stdio".into()]
31}
32
33#[derive(Copy, Clone)]
34pub struct GoLspAdapter;
35
36impl GoLspAdapter {
37 const SERVER_NAME: &'static str = "gopls";
38}
39
40lazy_static! {
41 static ref GOPLS_VERSION_REGEX: Regex = Regex::new(r"\d+\.\d+\.\d+").unwrap();
42 static ref GO_EXTRACT_SUBTEST_NAME_REGEX: Regex =
43 Regex::new(r#".*t\.Run\("([^"]*)".*"#).unwrap();
44 static ref GO_ESCAPE_SUBTEST_NAME_REGEX: Regex = Regex::new(r#"[.*+?^${}()|\[\]\\]"#).unwrap();
45}
46
47#[async_trait(?Send)]
48impl super::LspAdapter for GoLspAdapter {
49 fn name(&self) -> LanguageServerName {
50 LanguageServerName(Self::SERVER_NAME.into())
51 }
52
53 async fn fetch_latest_server_version(
54 &self,
55 delegate: &dyn LspAdapterDelegate,
56 ) -> Result<Box<dyn 'static + Send + Any>> {
57 let release =
58 latest_github_release("golang/tools", false, false, delegate.http_client()).await?;
59 let version: Option<String> = release.tag_name.strip_prefix("gopls/v").map(str::to_string);
60 if version.is_none() {
61 log::warn!(
62 "couldn't infer gopls version from GitHub release tag name '{}'",
63 release.tag_name
64 );
65 }
66 Ok(Box::new(version) as Box<_>)
67 }
68
69 async fn check_if_user_installed(
70 &self,
71 delegate: &dyn LspAdapterDelegate,
72 cx: &AsyncAppContext,
73 ) -> Option<LanguageServerBinary> {
74 let configured_binary = cx.update(|cx| {
75 ProjectSettings::get_global(cx)
76 .lsp
77 .get(Self::SERVER_NAME)
78 .and_then(|s| s.binary.clone())
79 });
80
81 if let Ok(Some(BinarySettings {
82 path: Some(path),
83 arguments,
84 })) = configured_binary
85 {
86 Some(LanguageServerBinary {
87 path: path.into(),
88 arguments: arguments
89 .unwrap_or_default()
90 .iter()
91 .map(|arg| arg.into())
92 .collect(),
93 env: None,
94 })
95 } else {
96 let env = delegate.shell_env().await;
97 let path = delegate.which(Self::SERVER_NAME.as_ref()).await?;
98 Some(LanguageServerBinary {
99 path,
100 arguments: server_binary_arguments(),
101 env: Some(env),
102 })
103 }
104 }
105
106 fn will_fetch_server(
107 &self,
108 delegate: &Arc<dyn LspAdapterDelegate>,
109 cx: &mut AsyncAppContext,
110 ) -> Option<Task<Result<()>>> {
111 static DID_SHOW_NOTIFICATION: AtomicBool = AtomicBool::new(false);
112
113 const NOTIFICATION_MESSAGE: &str =
114 "Could not install the Go language server `gopls`, because `go` was not found.";
115
116 let delegate = delegate.clone();
117 Some(cx.spawn(|cx| async move {
118 let install_output = process::Command::new("go").args(["version"]).output().await;
119 if install_output.is_err() {
120 if DID_SHOW_NOTIFICATION
121 .compare_exchange(false, true, SeqCst, SeqCst)
122 .is_ok()
123 {
124 cx.update(|cx| {
125 delegate.show_notification(NOTIFICATION_MESSAGE, cx);
126 })?
127 }
128 return Err(anyhow!("cannot install gopls"));
129 }
130 Ok(())
131 }))
132 }
133
134 async fn fetch_server_binary(
135 &self,
136 version: Box<dyn 'static + Send + Any>,
137 container_dir: PathBuf,
138 delegate: &dyn LspAdapterDelegate,
139 ) -> Result<LanguageServerBinary> {
140 let version = version.downcast::<Option<String>>().unwrap();
141 let this = *self;
142
143 if let Some(version) = *version {
144 let binary_path = container_dir.join(&format!("gopls_{version}"));
145 if let Ok(metadata) = fs::metadata(&binary_path).await {
146 if metadata.is_file() {
147 remove_matching(&container_dir, |entry| {
148 entry != binary_path && entry.file_name() != Some(OsStr::new("gobin"))
149 })
150 .await;
151
152 return Ok(LanguageServerBinary {
153 path: binary_path.to_path_buf(),
154 arguments: server_binary_arguments(),
155 env: None,
156 });
157 }
158 }
159 } else if let Some(path) = this
160 .cached_server_binary(container_dir.clone(), delegate)
161 .await
162 {
163 return Ok(path);
164 }
165
166 let gobin_dir = container_dir.join("gobin");
167 fs::create_dir_all(&gobin_dir).await?;
168 let install_output = process::Command::new("go")
169 .env("GO111MODULE", "on")
170 .env("GOBIN", &gobin_dir)
171 .args(["install", "golang.org/x/tools/gopls@latest"])
172 .output()
173 .await?;
174
175 if !install_output.status.success() {
176 log::error!(
177 "failed to install gopls via `go install`. stdout: {:?}, stderr: {:?}",
178 String::from_utf8_lossy(&install_output.stdout),
179 String::from_utf8_lossy(&install_output.stderr)
180 );
181
182 return Err(anyhow!("failed to install gopls with `go install`. Is `go` installed and in the PATH? Check logs for more information."));
183 }
184
185 let installed_binary_path = gobin_dir.join("gopls");
186 let version_output = process::Command::new(&installed_binary_path)
187 .arg("version")
188 .output()
189 .await
190 .context("failed to run installed gopls binary")?;
191 let version_stdout = str::from_utf8(&version_output.stdout)
192 .context("gopls version produced invalid utf8 output")?;
193 let version = GOPLS_VERSION_REGEX
194 .find(version_stdout)
195 .with_context(|| format!("failed to parse golps version output '{version_stdout}'"))?
196 .as_str();
197 let binary_path = container_dir.join(&format!("gopls_{version}"));
198 fs::rename(&installed_binary_path, &binary_path).await?;
199
200 Ok(LanguageServerBinary {
201 path: binary_path.to_path_buf(),
202 arguments: server_binary_arguments(),
203 env: None,
204 })
205 }
206
207 async fn cached_server_binary(
208 &self,
209 container_dir: PathBuf,
210 _: &dyn LspAdapterDelegate,
211 ) -> Option<LanguageServerBinary> {
212 get_cached_server_binary(container_dir).await
213 }
214
215 async fn installation_test_binary(
216 &self,
217 container_dir: PathBuf,
218 ) -> Option<LanguageServerBinary> {
219 get_cached_server_binary(container_dir)
220 .await
221 .map(|mut binary| {
222 binary.arguments = vec!["--help".into()];
223 binary
224 })
225 }
226
227 async fn initialization_options(
228 self: Arc<Self>,
229 _: &Arc<dyn LspAdapterDelegate>,
230 ) -> Result<Option<serde_json::Value>> {
231 Ok(Some(json!({
232 "usePlaceholders": true,
233 "hints": {
234 "assignVariableTypes": true,
235 "compositeLiteralFields": true,
236 "compositeLiteralTypes": true,
237 "constantValues": true,
238 "functionTypeParameters": true,
239 "parameterNames": true,
240 "rangeVariableTypes": true
241 }
242 })))
243 }
244
245 async fn label_for_completion(
246 &self,
247 completion: &lsp::CompletionItem,
248 language: &Arc<Language>,
249 ) -> Option<CodeLabel> {
250 let label = &completion.label;
251
252 // Gopls returns nested fields and methods as completions.
253 // To syntax highlight these, combine their final component
254 // with their detail.
255 let name_offset = label.rfind('.').unwrap_or(0);
256
257 match completion.kind.zip(completion.detail.as_ref()) {
258 Some((lsp::CompletionItemKind::MODULE, detail)) => {
259 let text = format!("{label} {detail}");
260 let source = Rope::from(format!("import {text}").as_str());
261 let runs = language.highlight_text(&source, 7..7 + text.len());
262 return Some(CodeLabel {
263 text,
264 runs,
265 filter_range: 0..label.len(),
266 });
267 }
268 Some((
269 lsp::CompletionItemKind::CONSTANT | lsp::CompletionItemKind::VARIABLE,
270 detail,
271 )) => {
272 let text = format!("{label} {detail}");
273 let source =
274 Rope::from(format!("var {} {}", &text[name_offset..], detail).as_str());
275 let runs = adjust_runs(
276 name_offset,
277 language.highlight_text(&source, 4..4 + text.len()),
278 );
279 return Some(CodeLabel {
280 text,
281 runs,
282 filter_range: 0..label.len(),
283 });
284 }
285 Some((lsp::CompletionItemKind::STRUCT, _)) => {
286 let text = format!("{label} struct {{}}");
287 let source = Rope::from(format!("type {}", &text[name_offset..]).as_str());
288 let runs = adjust_runs(
289 name_offset,
290 language.highlight_text(&source, 5..5 + text.len()),
291 );
292 return Some(CodeLabel {
293 text,
294 runs,
295 filter_range: 0..label.len(),
296 });
297 }
298 Some((lsp::CompletionItemKind::INTERFACE, _)) => {
299 let text = format!("{label} interface {{}}");
300 let source = Rope::from(format!("type {}", &text[name_offset..]).as_str());
301 let runs = adjust_runs(
302 name_offset,
303 language.highlight_text(&source, 5..5 + text.len()),
304 );
305 return Some(CodeLabel {
306 text,
307 runs,
308 filter_range: 0..label.len(),
309 });
310 }
311 Some((lsp::CompletionItemKind::FIELD, detail)) => {
312 let text = format!("{label} {detail}");
313 let source =
314 Rope::from(format!("type T struct {{ {} }}", &text[name_offset..]).as_str());
315 let runs = adjust_runs(
316 name_offset,
317 language.highlight_text(&source, 16..16 + text.len()),
318 );
319 return Some(CodeLabel {
320 text,
321 runs,
322 filter_range: 0..label.len(),
323 });
324 }
325 Some((lsp::CompletionItemKind::FUNCTION | lsp::CompletionItemKind::METHOD, detail)) => {
326 if let Some(signature) = detail.strip_prefix("func") {
327 let text = format!("{label}{signature}");
328 let source = Rope::from(format!("func {} {{}}", &text[name_offset..]).as_str());
329 let runs = adjust_runs(
330 name_offset,
331 language.highlight_text(&source, 5..5 + text.len()),
332 );
333 return Some(CodeLabel {
334 filter_range: 0..label.len(),
335 text,
336 runs,
337 });
338 }
339 }
340 _ => {}
341 }
342 None
343 }
344
345 async fn label_for_symbol(
346 &self,
347 name: &str,
348 kind: lsp::SymbolKind,
349 language: &Arc<Language>,
350 ) -> Option<CodeLabel> {
351 let (text, filter_range, display_range) = match kind {
352 lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
353 let text = format!("func {} () {{}}", name);
354 let filter_range = 5..5 + name.len();
355 let display_range = 0..filter_range.end;
356 (text, filter_range, display_range)
357 }
358 lsp::SymbolKind::STRUCT => {
359 let text = format!("type {} struct {{}}", name);
360 let filter_range = 5..5 + name.len();
361 let display_range = 0..text.len();
362 (text, filter_range, display_range)
363 }
364 lsp::SymbolKind::INTERFACE => {
365 let text = format!("type {} interface {{}}", name);
366 let filter_range = 5..5 + name.len();
367 let display_range = 0..text.len();
368 (text, filter_range, display_range)
369 }
370 lsp::SymbolKind::CLASS => {
371 let text = format!("type {} T", name);
372 let filter_range = 5..5 + name.len();
373 let display_range = 0..filter_range.end;
374 (text, filter_range, display_range)
375 }
376 lsp::SymbolKind::CONSTANT => {
377 let text = format!("const {} = nil", name);
378 let filter_range = 6..6 + name.len();
379 let display_range = 0..filter_range.end;
380 (text, filter_range, display_range)
381 }
382 lsp::SymbolKind::VARIABLE => {
383 let text = format!("var {} = nil", name);
384 let filter_range = 4..4 + name.len();
385 let display_range = 0..filter_range.end;
386 (text, filter_range, display_range)
387 }
388 lsp::SymbolKind::MODULE => {
389 let text = format!("package {}", name);
390 let filter_range = 8..8 + name.len();
391 let display_range = 0..filter_range.end;
392 (text, filter_range, display_range)
393 }
394 _ => return None,
395 };
396
397 Some(CodeLabel {
398 runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
399 text: text[display_range].to_string(),
400 filter_range,
401 })
402 }
403}
404
405async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
406 maybe!(async {
407 let mut last_binary_path = None;
408 let mut entries = fs::read_dir(&container_dir).await?;
409 while let Some(entry) = entries.next().await {
410 let entry = entry?;
411 if entry.file_type().await?.is_file()
412 && entry
413 .file_name()
414 .to_str()
415 .map_or(false, |name| name.starts_with("gopls_"))
416 {
417 last_binary_path = Some(entry.path());
418 }
419 }
420
421 if let Some(path) = last_binary_path {
422 Ok(LanguageServerBinary {
423 path,
424 arguments: server_binary_arguments(),
425 env: None,
426 })
427 } else {
428 Err(anyhow!("no cached binary"))
429 }
430 })
431 .await
432 .log_err()
433}
434
435fn adjust_runs(
436 delta: usize,
437 mut runs: Vec<(Range<usize>, HighlightId)>,
438) -> Vec<(Range<usize>, HighlightId)> {
439 for (range, _) in &mut runs {
440 range.start += delta;
441 range.end += delta;
442 }
443 runs
444}
445
446pub(crate) struct GoContextProvider;
447
448const GO_PACKAGE_TASK_VARIABLE: VariableName = VariableName::Custom(Cow::Borrowed("GO_PACKAGE"));
449const GO_SUBTEST_NAME_TASK_VARIABLE: VariableName =
450 VariableName::Custom(Cow::Borrowed("GO_SUBTEST_NAME"));
451
452impl ContextProvider for GoContextProvider {
453 fn build_context(
454 &self,
455 variables: &TaskVariables,
456 location: &Location,
457 cx: &mut gpui::AppContext,
458 ) -> Result<TaskVariables> {
459 let local_abs_path = location
460 .buffer
461 .read(cx)
462 .file()
463 .and_then(|file| Some(file.as_local()?.abs_path(cx)));
464
465 let go_package_variable = local_abs_path
466 .as_deref()
467 .and_then(|local_abs_path| local_abs_path.parent())
468 .map(|buffer_dir| {
469 // Prefer the relative form `./my-nested-package/is-here` over
470 // absolute path, because it's more readable in the modal, but
471 // the absolute path also works.
472 let package_name = variables
473 .get(&VariableName::WorktreeRoot)
474 .and_then(|worktree_abs_path| buffer_dir.strip_prefix(worktree_abs_path).ok())
475 .map(|relative_pkg_dir| {
476 if relative_pkg_dir.as_os_str().is_empty() {
477 ".".into()
478 } else {
479 format!("./{}", relative_pkg_dir.to_string_lossy())
480 }
481 })
482 .unwrap_or_else(|| format!("{}", buffer_dir.to_string_lossy()));
483
484 (GO_PACKAGE_TASK_VARIABLE.clone(), package_name.to_string())
485 });
486
487 let _subtest_name = variables.get(&VariableName::Custom(Cow::Borrowed("_subtest_name")));
488
489 let go_subtest_variable = extract_subtest_name(_subtest_name.unwrap_or(""))
490 .map(|subtest_name| (GO_SUBTEST_NAME_TASK_VARIABLE.clone(), subtest_name));
491
492 Ok(TaskVariables::from_iter(
493 [go_package_variable, go_subtest_variable]
494 .into_iter()
495 .flatten(),
496 ))
497 }
498
499 fn associated_tasks(&self) -> Option<TaskTemplates> {
500 Some(TaskTemplates(vec![
501 TaskTemplate {
502 label: format!(
503 "go test {} -run {}",
504 GO_PACKAGE_TASK_VARIABLE.template_value(),
505 VariableName::Symbol.template_value(),
506 ),
507 command: "go".into(),
508 args: vec![
509 "test".into(),
510 GO_PACKAGE_TASK_VARIABLE.template_value(),
511 "-run".into(),
512 VariableName::Symbol.template_value(),
513 ],
514 tags: vec!["go-test".to_owned()],
515 ..TaskTemplate::default()
516 },
517 TaskTemplate {
518 label: format!("go test {}", GO_PACKAGE_TASK_VARIABLE.template_value()),
519 command: "go".into(),
520 args: vec!["test".into(), GO_PACKAGE_TASK_VARIABLE.template_value()],
521 ..TaskTemplate::default()
522 },
523 TaskTemplate {
524 label: "go test ./...".into(),
525 command: "go".into(),
526 args: vec!["test".into(), "./...".into()],
527 ..TaskTemplate::default()
528 },
529 TaskTemplate {
530 label: format!(
531 "go test {} -run {}/{}",
532 GO_PACKAGE_TASK_VARIABLE.template_value(),
533 VariableName::Symbol.template_value(),
534 GO_SUBTEST_NAME_TASK_VARIABLE.template_value(),
535 ),
536 command: "go".into(),
537 args: vec![
538 "test".into(),
539 GO_PACKAGE_TASK_VARIABLE.template_value(),
540 "-v".into(),
541 "-run".into(),
542 format!(
543 "^{}$/^{}$",
544 VariableName::Symbol.template_value(),
545 GO_SUBTEST_NAME_TASK_VARIABLE.template_value(),
546 ),
547 ],
548 tags: vec!["go-subtest".to_owned()],
549 ..TaskTemplate::default()
550 },
551 TaskTemplate {
552 label: format!(
553 "go test {} -bench {}",
554 GO_PACKAGE_TASK_VARIABLE.template_value(),
555 VariableName::Symbol.template_value()
556 ),
557 command: "go".into(),
558 args: vec![
559 "test".into(),
560 GO_PACKAGE_TASK_VARIABLE.template_value(),
561 "-benchmem".into(),
562 "-run=^$".into(),
563 "-bench".into(),
564 format!("^{}$", VariableName::Symbol.template_value()),
565 ],
566 tags: vec!["go-benchmark".to_owned()],
567 ..TaskTemplate::default()
568 },
569 TaskTemplate {
570 label: format!("go run {}", GO_PACKAGE_TASK_VARIABLE.template_value(),),
571 command: "go".into(),
572 args: vec!["run".into(), GO_PACKAGE_TASK_VARIABLE.template_value()],
573 tags: vec!["go-main".to_owned()],
574 ..TaskTemplate::default()
575 },
576 ]))
577 }
578}
579
580fn extract_subtest_name(input: &str) -> Option<String> {
581 let replaced_spaces = input.trim_matches('"').replace(' ', "_");
582
583 Some(
584 GO_ESCAPE_SUBTEST_NAME_REGEX
585 .replace_all(&replaced_spaces, |caps: ®ex::Captures| {
586 format!("\\{}", &caps[0])
587 })
588 .to_string(),
589 )
590}
591
592#[cfg(test)]
593mod tests {
594 use super::*;
595 use crate::language;
596 use gpui::Hsla;
597 use theme::SyntaxTheme;
598
599 #[gpui::test]
600 async fn test_go_label_for_completion() {
601 let adapter = Arc::new(GoLspAdapter);
602 let language = language("go", tree_sitter_go::language());
603
604 let theme = SyntaxTheme::new_test([
605 ("type", Hsla::default()),
606 ("keyword", Hsla::default()),
607 ("function", Hsla::default()),
608 ("number", Hsla::default()),
609 ("property", Hsla::default()),
610 ]);
611 language.set_theme(&theme);
612
613 let grammar = language.grammar().unwrap();
614 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
615 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
616 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
617 let highlight_number = grammar.highlight_id_for_name("number").unwrap();
618
619 assert_eq!(
620 adapter
621 .label_for_completion(
622 &lsp::CompletionItem {
623 kind: Some(lsp::CompletionItemKind::FUNCTION),
624 label: "Hello".to_string(),
625 detail: Some("func(a B) c.D".to_string()),
626 ..Default::default()
627 },
628 &language
629 )
630 .await,
631 Some(CodeLabel {
632 text: "Hello(a B) c.D".to_string(),
633 filter_range: 0..5,
634 runs: vec![
635 (0..5, highlight_function),
636 (8..9, highlight_type),
637 (13..14, highlight_type),
638 ],
639 })
640 );
641
642 // Nested methods
643 assert_eq!(
644 adapter
645 .label_for_completion(
646 &lsp::CompletionItem {
647 kind: Some(lsp::CompletionItemKind::METHOD),
648 label: "one.two.Three".to_string(),
649 detail: Some("func() [3]interface{}".to_string()),
650 ..Default::default()
651 },
652 &language
653 )
654 .await,
655 Some(CodeLabel {
656 text: "one.two.Three() [3]interface{}".to_string(),
657 filter_range: 0..13,
658 runs: vec![
659 (8..13, highlight_function),
660 (17..18, highlight_number),
661 (19..28, highlight_keyword),
662 ],
663 })
664 );
665
666 // Nested fields
667 assert_eq!(
668 adapter
669 .label_for_completion(
670 &lsp::CompletionItem {
671 kind: Some(lsp::CompletionItemKind::FIELD),
672 label: "two.Three".to_string(),
673 detail: Some("a.Bcd".to_string()),
674 ..Default::default()
675 },
676 &language
677 )
678 .await,
679 Some(CodeLabel {
680 text: "two.Three a.Bcd".to_string(),
681 filter_range: 0..9,
682 runs: vec![(12..15, highlight_type)],
683 })
684 );
685 }
686}