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 let install_output = process::Command::new("go").args(["version"]).output().await;
93 if install_output.is_err() {
94 if DID_SHOW_NOTIFICATION
95 .compare_exchange(false, true, SeqCst, SeqCst)
96 .is_ok()
97 {
98 cx.update(|cx| {
99 delegate.show_notification(NOTIFICATION_MESSAGE, cx);
100 })?
101 }
102 return Err(anyhow!("cannot install gopls"));
103 }
104 Ok(())
105 }))
106 }
107
108 async fn fetch_server_binary(
109 &self,
110 version: Box<dyn 'static + Send + Any>,
111 container_dir: PathBuf,
112 delegate: &dyn LspAdapterDelegate,
113 ) -> Result<LanguageServerBinary> {
114 let version = version.downcast::<Option<String>>().unwrap();
115 let this = *self;
116
117 if let Some(version) = *version {
118 let binary_path = container_dir.join(format!("gopls_{version}"));
119 if let Ok(metadata) = fs::metadata(&binary_path).await {
120 if metadata.is_file() {
121 remove_matching(&container_dir, |entry| {
122 entry != binary_path && entry.file_name() != Some(OsStr::new("gobin"))
123 })
124 .await;
125
126 return Ok(LanguageServerBinary {
127 path: binary_path.to_path_buf(),
128 arguments: server_binary_arguments(),
129 env: None,
130 });
131 }
132 }
133 } else if let Some(path) = this
134 .cached_server_binary(container_dir.clone(), delegate)
135 .await
136 {
137 return Ok(path);
138 }
139
140 let gobin_dir = container_dir.join("gobin");
141 fs::create_dir_all(&gobin_dir).await?;
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 cx: &mut gpui::AppContext,
423 ) -> Result<TaskVariables> {
424 let local_abs_path = location
425 .buffer
426 .read(cx)
427 .file()
428 .and_then(|file| Some(file.as_local()?.abs_path(cx)));
429
430 let go_package_variable = local_abs_path
431 .as_deref()
432 .and_then(|local_abs_path| local_abs_path.parent())
433 .map(|buffer_dir| {
434 // Prefer the relative form `./my-nested-package/is-here` over
435 // absolute path, because it's more readable in the modal, but
436 // the absolute path also works.
437 let package_name = variables
438 .get(&VariableName::WorktreeRoot)
439 .and_then(|worktree_abs_path| buffer_dir.strip_prefix(worktree_abs_path).ok())
440 .map(|relative_pkg_dir| {
441 if relative_pkg_dir.as_os_str().is_empty() {
442 ".".into()
443 } else {
444 format!("./{}", relative_pkg_dir.to_string_lossy())
445 }
446 })
447 .unwrap_or_else(|| format!("{}", buffer_dir.to_string_lossy()));
448
449 (GO_PACKAGE_TASK_VARIABLE.clone(), package_name.to_string())
450 });
451
452 let go_module_root_variable = local_abs_path
453 .as_deref()
454 .and_then(|local_abs_path| local_abs_path.parent())
455 .map(|buffer_dir| {
456 // Walk dirtree up until getting the first go.mod file
457 let module_dir = buffer_dir
458 .ancestors()
459 .find(|dir| dir.join("go.mod").is_file())
460 .map(|dir| dir.to_string_lossy().to_string())
461 .unwrap_or_else(|| ".".to_string());
462
463 (GO_MODULE_ROOT_TASK_VARIABLE.clone(), module_dir)
464 });
465
466 let _subtest_name = variables.get(&VariableName::Custom(Cow::Borrowed("_subtest_name")));
467
468 let go_subtest_variable = extract_subtest_name(_subtest_name.unwrap_or(""))
469 .map(|subtest_name| (GO_SUBTEST_NAME_TASK_VARIABLE.clone(), subtest_name));
470
471 Ok(TaskVariables::from_iter(
472 [
473 go_package_variable,
474 go_subtest_variable,
475 go_module_root_variable,
476 ]
477 .into_iter()
478 .flatten(),
479 ))
480 }
481
482 fn associated_tasks(
483 &self,
484 _: Option<Arc<dyn language::File>>,
485 _: &AppContext,
486 ) -> Option<TaskTemplates> {
487 let package_cwd = if GO_PACKAGE_TASK_VARIABLE.template_value() == "." {
488 None
489 } else {
490 Some("$ZED_DIRNAME".to_string())
491 };
492 let module_cwd = Some(GO_MODULE_ROOT_TASK_VARIABLE.template_value());
493
494 Some(TaskTemplates(vec![
495 TaskTemplate {
496 label: format!(
497 "go test {} -run {}",
498 GO_PACKAGE_TASK_VARIABLE.template_value(),
499 VariableName::Symbol.template_value(),
500 ),
501 command: "go".into(),
502 args: vec![
503 "test".into(),
504 "-run".into(),
505 format!("^{}\\$", VariableName::Symbol.template_value(),),
506 ],
507 tags: vec!["go-test".to_owned()],
508 cwd: package_cwd.clone(),
509 ..TaskTemplate::default()
510 },
511 TaskTemplate {
512 label: format!("go test {}", GO_PACKAGE_TASK_VARIABLE.template_value()),
513 command: "go".into(),
514 args: vec!["test".into()],
515 cwd: package_cwd.clone(),
516 ..TaskTemplate::default()
517 },
518 TaskTemplate {
519 label: "go test ./...".into(),
520 command: "go".into(),
521 args: vec!["test".into(), "./...".into()],
522 cwd: module_cwd.clone(),
523 ..TaskTemplate::default()
524 },
525 TaskTemplate {
526 label: format!(
527 "go test {} -v -run {}/{}",
528 GO_PACKAGE_TASK_VARIABLE.template_value(),
529 VariableName::Symbol.template_value(),
530 GO_SUBTEST_NAME_TASK_VARIABLE.template_value(),
531 ),
532 command: "go".into(),
533 args: vec![
534 "test".into(),
535 "-v".into(),
536 "-run".into(),
537 format!(
538 "^{}\\$/^{}\\$",
539 VariableName::Symbol.template_value(),
540 GO_SUBTEST_NAME_TASK_VARIABLE.template_value(),
541 ),
542 ],
543 cwd: package_cwd.clone(),
544 tags: vec!["go-subtest".to_owned()],
545 ..TaskTemplate::default()
546 },
547 TaskTemplate {
548 label: format!(
549 "go test {} -bench {}",
550 GO_PACKAGE_TASK_VARIABLE.template_value(),
551 VariableName::Symbol.template_value()
552 ),
553 command: "go".into(),
554 args: vec![
555 "test".into(),
556 "-benchmem".into(),
557 "-run=^$".into(),
558 "-bench".into(),
559 format!("^{}\\$", VariableName::Symbol.template_value()),
560 ],
561 cwd: package_cwd.clone(),
562 tags: vec!["go-benchmark".to_owned()],
563 ..TaskTemplate::default()
564 },
565 TaskTemplate {
566 label: format!("go run {}", GO_PACKAGE_TASK_VARIABLE.template_value(),),
567 command: "go".into(),
568 args: vec!["run".into(), ".".into()],
569 cwd: package_cwd.clone(),
570 tags: vec!["go-main".to_owned()],
571 ..TaskTemplate::default()
572 },
573 TaskTemplate {
574 label: format!("go generate {}", GO_PACKAGE_TASK_VARIABLE.template_value()),
575 command: "go".into(),
576 args: vec!["generate".into()],
577 cwd: package_cwd.clone(),
578 tags: vec!["go-generate".to_owned()],
579 ..TaskTemplate::default()
580 },
581 TaskTemplate {
582 label: "go generate ./...".into(),
583 command: "go".into(),
584 args: vec!["generate".into(), "./...".into()],
585 cwd: module_cwd.clone(),
586 ..TaskTemplate::default()
587 },
588 ]))
589 }
590}
591
592fn extract_subtest_name(input: &str) -> Option<String> {
593 let replaced_spaces = input.trim_matches('"').replace(' ', "_");
594
595 Some(
596 GO_ESCAPE_SUBTEST_NAME_REGEX
597 .replace_all(&replaced_spaces, |caps: ®ex::Captures| {
598 format!("\\{}", &caps[0])
599 })
600 .to_string(),
601 )
602}
603
604#[cfg(test)]
605mod tests {
606 use super::*;
607 use crate::language;
608 use gpui::Hsla;
609 use theme::SyntaxTheme;
610
611 #[gpui::test]
612 async fn test_go_label_for_completion() {
613 let adapter = Arc::new(GoLspAdapter);
614 let language = language("go", tree_sitter_go::LANGUAGE.into());
615
616 let theme = SyntaxTheme::new_test([
617 ("type", Hsla::default()),
618 ("keyword", Hsla::default()),
619 ("function", Hsla::default()),
620 ("number", Hsla::default()),
621 ("property", Hsla::default()),
622 ]);
623 language.set_theme(&theme);
624
625 let grammar = language.grammar().unwrap();
626 let highlight_function = grammar.highlight_id_for_name("function").unwrap();
627 let highlight_type = grammar.highlight_id_for_name("type").unwrap();
628 let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
629 let highlight_number = grammar.highlight_id_for_name("number").unwrap();
630
631 assert_eq!(
632 adapter
633 .label_for_completion(
634 &lsp::CompletionItem {
635 kind: Some(lsp::CompletionItemKind::FUNCTION),
636 label: "Hello".to_string(),
637 detail: Some("func(a B) c.D".to_string()),
638 ..Default::default()
639 },
640 &language
641 )
642 .await,
643 Some(CodeLabel {
644 text: "Hello(a B) c.D".to_string(),
645 filter_range: 0..5,
646 runs: vec![
647 (0..5, highlight_function),
648 (8..9, highlight_type),
649 (13..14, highlight_type),
650 ],
651 })
652 );
653
654 // Nested methods
655 assert_eq!(
656 adapter
657 .label_for_completion(
658 &lsp::CompletionItem {
659 kind: Some(lsp::CompletionItemKind::METHOD),
660 label: "one.two.Three".to_string(),
661 detail: Some("func() [3]interface{}".to_string()),
662 ..Default::default()
663 },
664 &language
665 )
666 .await,
667 Some(CodeLabel {
668 text: "one.two.Three() [3]interface{}".to_string(),
669 filter_range: 0..13,
670 runs: vec![
671 (8..13, highlight_function),
672 (17..18, highlight_number),
673 (19..28, highlight_keyword),
674 ],
675 })
676 );
677
678 // Nested fields
679 assert_eq!(
680 adapter
681 .label_for_completion(
682 &lsp::CompletionItem {
683 kind: Some(lsp::CompletionItemKind::FIELD),
684 label: "two.Three".to_string(),
685 detail: Some("a.Bcd".to_string()),
686 ..Default::default()
687 },
688 &language
689 )
690 .await,
691 Some(CodeLabel {
692 text: "two.Three a.Bcd".to_string(),
693 filter_range: 0..9,
694 runs: vec![(12..15, highlight_type)],
695 })
696 );
697 }
698}