go.rs

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