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