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