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