go.rs

  1use anyhow::{anyhow, Context, Result};
  2use async_trait::async_trait;
  3use futures::StreamExt;
  4use gpui::{AppContext, AsyncAppContext, Task};
  5use http_client::github::latest_github_release;
  6pub use language::*;
  7use lsp::LanguageServerBinary;
  8use project::{lsp_store::language_server_settings, project_settings::BinarySettings};
  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: &'static str = "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        LanguageServerName(Self::SERVER_NAME.into())
 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        cx: &AsyncAppContext,
 71    ) -> Option<LanguageServerBinary> {
 72        let configured_binary = cx.update(|cx| {
 73            language_server_settings(delegate, Self::SERVER_NAME, cx).and_then(|s| s.binary.clone())
 74        });
 75
 76        match configured_binary {
 77            Ok(Some(BinarySettings {
 78                path: Some(path),
 79                arguments,
 80                ..
 81            })) => Some(LanguageServerBinary {
 82                path: path.into(),
 83                arguments: arguments
 84                    .unwrap_or_default()
 85                    .iter()
 86                    .map(|arg| arg.into())
 87                    .collect(),
 88                env: None,
 89            }),
 90            Ok(Some(BinarySettings {
 91                path_lookup: Some(false),
 92                ..
 93            })) => None,
 94            _ => {
 95                let env = delegate.shell_env().await;
 96                let path = delegate.which(Self::SERVER_NAME.as_ref()).await?;
 97                Some(LanguageServerBinary {
 98                    path,
 99                    arguments: server_binary_arguments(),
100                    env: Some(env),
101                })
102            }
103        }
104    }
105
106    fn will_fetch_server(
107        &self,
108        delegate: &Arc<dyn LspAdapterDelegate>,
109        cx: &mut AsyncAppContext,
110    ) -> Option<Task<Result<()>>> {
111        static DID_SHOW_NOTIFICATION: AtomicBool = AtomicBool::new(false);
112
113        const NOTIFICATION_MESSAGE: &str =
114            "Could not install the Go language server `gopls`, because `go` was not found.";
115
116        let delegate = delegate.clone();
117        Some(cx.spawn(|cx| async move {
118            let install_output = process::Command::new("go").args(["version"]).output().await;
119            if install_output.is_err() {
120                if DID_SHOW_NOTIFICATION
121                    .compare_exchange(false, true, SeqCst, SeqCst)
122                    .is_ok()
123                {
124                    cx.update(|cx| {
125                        delegate.show_notification(NOTIFICATION_MESSAGE, cx);
126                    })?
127                }
128                return Err(anyhow!("cannot install gopls"));
129            }
130            Ok(())
131        }))
132    }
133
134    async fn fetch_server_binary(
135        &self,
136        version: Box<dyn 'static + Send + Any>,
137        container_dir: PathBuf,
138        delegate: &dyn LspAdapterDelegate,
139    ) -> Result<LanguageServerBinary> {
140        let version = version.downcast::<Option<String>>().unwrap();
141        let this = *self;
142
143        if let Some(version) = *version {
144            let binary_path = container_dir.join(format!("gopls_{version}"));
145            if let Ok(metadata) = fs::metadata(&binary_path).await {
146                if metadata.is_file() {
147                    remove_matching(&container_dir, |entry| {
148                        entry != binary_path && entry.file_name() != Some(OsStr::new("gobin"))
149                    })
150                    .await;
151
152                    return Ok(LanguageServerBinary {
153                        path: binary_path.to_path_buf(),
154                        arguments: server_binary_arguments(),
155                        env: None,
156                    });
157                }
158            }
159        } else if let Some(path) = this
160            .cached_server_binary(container_dir.clone(), delegate)
161            .await
162        {
163            return Ok(path);
164        }
165
166        let gobin_dir = container_dir.join("gobin");
167        fs::create_dir_all(&gobin_dir).await?;
168        let install_output = process::Command::new("go")
169            .env("GO111MODULE", "on")
170            .env("GOBIN", &gobin_dir)
171            .args(["install", "golang.org/x/tools/gopls@latest"])
172            .output()
173            .await?;
174
175        if !install_output.status.success() {
176            log::error!(
177                "failed to install gopls via `go install`. stdout: {:?}, stderr: {:?}",
178                String::from_utf8_lossy(&install_output.stdout),
179                String::from_utf8_lossy(&install_output.stderr)
180            );
181
182            return Err(anyhow!("failed to install gopls with `go install`. Is `go` installed and in the PATH? Check logs for more information."));
183        }
184
185        let installed_binary_path = gobin_dir.join("gopls");
186        let version_output = process::Command::new(&installed_binary_path)
187            .arg("version")
188            .output()
189            .await
190            .context("failed to run installed gopls binary")?;
191        let version_stdout = str::from_utf8(&version_output.stdout)
192            .context("gopls version produced invalid utf8 output")?;
193        let version = GOPLS_VERSION_REGEX
194            .find(version_stdout)
195            .with_context(|| format!("failed to parse golps version output '{version_stdout}'"))?
196            .as_str();
197        let binary_path = container_dir.join(format!("gopls_{version}"));
198        fs::rename(&installed_binary_path, &binary_path).await?;
199
200        Ok(LanguageServerBinary {
201            path: binary_path.to_path_buf(),
202            arguments: server_binary_arguments(),
203            env: None,
204        })
205    }
206
207    async fn cached_server_binary(
208        &self,
209        container_dir: PathBuf,
210        _: &dyn LspAdapterDelegate,
211    ) -> Option<LanguageServerBinary> {
212        get_cached_server_binary(container_dir).await
213    }
214
215    async fn installation_test_binary(
216        &self,
217        container_dir: PathBuf,
218    ) -> Option<LanguageServerBinary> {
219        get_cached_server_binary(container_dir)
220            .await
221            .map(|mut binary| {
222                binary.arguments = vec!["--help".into()];
223                binary
224            })
225    }
226
227    async fn initialization_options(
228        self: Arc<Self>,
229        _: &Arc<dyn LspAdapterDelegate>,
230    ) -> Result<Option<serde_json::Value>> {
231        Ok(Some(json!({
232            "usePlaceholders": true,
233            "hints": {
234                "assignVariableTypes": true,
235                "compositeLiteralFields": true,
236                "compositeLiteralTypes": true,
237                "constantValues": true,
238                "functionTypeParameters": true,
239                "parameterNames": true,
240                "rangeVariableTypes": true
241            }
242        })))
243    }
244
245    async fn label_for_completion(
246        &self,
247        completion: &lsp::CompletionItem,
248        language: &Arc<Language>,
249    ) -> Option<CodeLabel> {
250        let label = &completion.label;
251
252        // Gopls returns nested fields and methods as completions.
253        // To syntax highlight these, combine their final component
254        // with their detail.
255        let name_offset = label.rfind('.').unwrap_or(0);
256
257        match completion.kind.zip(completion.detail.as_ref()) {
258            Some((lsp::CompletionItemKind::MODULE, detail)) => {
259                let text = format!("{label} {detail}");
260                let source = Rope::from(format!("import {text}").as_str());
261                let runs = language.highlight_text(&source, 7..7 + text.len());
262                return Some(CodeLabel {
263                    text,
264                    runs,
265                    filter_range: 0..label.len(),
266                });
267            }
268            Some((
269                lsp::CompletionItemKind::CONSTANT | lsp::CompletionItemKind::VARIABLE,
270                detail,
271            )) => {
272                let text = format!("{label} {detail}");
273                let source =
274                    Rope::from(format!("var {} {}", &text[name_offset..], detail).as_str());
275                let runs = adjust_runs(
276                    name_offset,
277                    language.highlight_text(&source, 4..4 + text.len()),
278                );
279                return Some(CodeLabel {
280                    text,
281                    runs,
282                    filter_range: 0..label.len(),
283                });
284            }
285            Some((lsp::CompletionItemKind::STRUCT, _)) => {
286                let text = format!("{label} struct {{}}");
287                let source = Rope::from(format!("type {}", &text[name_offset..]).as_str());
288                let runs = adjust_runs(
289                    name_offset,
290                    language.highlight_text(&source, 5..5 + text.len()),
291                );
292                return Some(CodeLabel {
293                    text,
294                    runs,
295                    filter_range: 0..label.len(),
296                });
297            }
298            Some((lsp::CompletionItemKind::INTERFACE, _)) => {
299                let text = format!("{label} interface {{}}");
300                let source = Rope::from(format!("type {}", &text[name_offset..]).as_str());
301                let runs = adjust_runs(
302                    name_offset,
303                    language.highlight_text(&source, 5..5 + text.len()),
304                );
305                return Some(CodeLabel {
306                    text,
307                    runs,
308                    filter_range: 0..label.len(),
309                });
310            }
311            Some((lsp::CompletionItemKind::FIELD, detail)) => {
312                let text = format!("{label} {detail}");
313                let source =
314                    Rope::from(format!("type T struct {{ {} }}", &text[name_offset..]).as_str());
315                let runs = adjust_runs(
316                    name_offset,
317                    language.highlight_text(&source, 16..16 + text.len()),
318                );
319                return Some(CodeLabel {
320                    text,
321                    runs,
322                    filter_range: 0..label.len(),
323                });
324            }
325            Some((lsp::CompletionItemKind::FUNCTION | lsp::CompletionItemKind::METHOD, detail)) => {
326                if let Some(signature) = detail.strip_prefix("func") {
327                    let text = format!("{label}{signature}");
328                    let source = Rope::from(format!("func {} {{}}", &text[name_offset..]).as_str());
329                    let runs = adjust_runs(
330                        name_offset,
331                        language.highlight_text(&source, 5..5 + text.len()),
332                    );
333                    return Some(CodeLabel {
334                        filter_range: 0..label.len(),
335                        text,
336                        runs,
337                    });
338                }
339            }
340            _ => {}
341        }
342        None
343    }
344
345    async fn label_for_symbol(
346        &self,
347        name: &str,
348        kind: lsp::SymbolKind,
349        language: &Arc<Language>,
350    ) -> Option<CodeLabel> {
351        let (text, filter_range, display_range) = match kind {
352            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
353                let text = format!("func {} () {{}}", name);
354                let filter_range = 5..5 + name.len();
355                let display_range = 0..filter_range.end;
356                (text, filter_range, display_range)
357            }
358            lsp::SymbolKind::STRUCT => {
359                let text = format!("type {} struct {{}}", name);
360                let filter_range = 5..5 + name.len();
361                let display_range = 0..text.len();
362                (text, filter_range, display_range)
363            }
364            lsp::SymbolKind::INTERFACE => {
365                let text = format!("type {} interface {{}}", name);
366                let filter_range = 5..5 + name.len();
367                let display_range = 0..text.len();
368                (text, filter_range, display_range)
369            }
370            lsp::SymbolKind::CLASS => {
371                let text = format!("type {} T", name);
372                let filter_range = 5..5 + name.len();
373                let display_range = 0..filter_range.end;
374                (text, filter_range, display_range)
375            }
376            lsp::SymbolKind::CONSTANT => {
377                let text = format!("const {} = nil", name);
378                let filter_range = 6..6 + name.len();
379                let display_range = 0..filter_range.end;
380                (text, filter_range, display_range)
381            }
382            lsp::SymbolKind::VARIABLE => {
383                let text = format!("var {} = nil", name);
384                let filter_range = 4..4 + name.len();
385                let display_range = 0..filter_range.end;
386                (text, filter_range, display_range)
387            }
388            lsp::SymbolKind::MODULE => {
389                let text = format!("package {}", name);
390                let filter_range = 8..8 + name.len();
391                let display_range = 0..filter_range.end;
392                (text, filter_range, display_range)
393            }
394            _ => return None,
395        };
396
397        Some(CodeLabel {
398            runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
399            text: text[display_range].to_string(),
400            filter_range,
401        })
402    }
403}
404
405async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
406    maybe!(async {
407        let mut last_binary_path = None;
408        let mut entries = fs::read_dir(&container_dir).await?;
409        while let Some(entry) = entries.next().await {
410            let entry = entry?;
411            if entry.file_type().await?.is_file()
412                && entry
413                    .file_name()
414                    .to_str()
415                    .map_or(false, |name| name.starts_with("gopls_"))
416            {
417                last_binary_path = Some(entry.path());
418            }
419        }
420
421        if let Some(path) = last_binary_path {
422            Ok(LanguageServerBinary {
423                path,
424                arguments: server_binary_arguments(),
425                env: None,
426            })
427        } else {
428            Err(anyhow!("no cached binary"))
429        }
430    })
431    .await
432    .log_err()
433}
434
435fn adjust_runs(
436    delta: usize,
437    mut runs: Vec<(Range<usize>, HighlightId)>,
438) -> Vec<(Range<usize>, HighlightId)> {
439    for (range, _) in &mut runs {
440        range.start += delta;
441        range.end += delta;
442    }
443    runs
444}
445
446pub(crate) struct GoContextProvider;
447
448const GO_PACKAGE_TASK_VARIABLE: VariableName = VariableName::Custom(Cow::Borrowed("GO_PACKAGE"));
449const GO_SUBTEST_NAME_TASK_VARIABLE: VariableName =
450    VariableName::Custom(Cow::Borrowed("GO_SUBTEST_NAME"));
451
452impl ContextProvider for GoContextProvider {
453    fn build_context(
454        &self,
455        variables: &TaskVariables,
456        location: &Location,
457        cx: &mut gpui::AppContext,
458    ) -> Result<TaskVariables> {
459        let local_abs_path = location
460            .buffer
461            .read(cx)
462            .file()
463            .and_then(|file| Some(file.as_local()?.abs_path(cx)));
464
465        let go_package_variable = local_abs_path
466            .as_deref()
467            .and_then(|local_abs_path| local_abs_path.parent())
468            .map(|buffer_dir| {
469                // Prefer the relative form `./my-nested-package/is-here` over
470                // absolute path, because it's more readable in the modal, but
471                // the absolute path also works.
472                let package_name = variables
473                    .get(&VariableName::WorktreeRoot)
474                    .and_then(|worktree_abs_path| buffer_dir.strip_prefix(worktree_abs_path).ok())
475                    .map(|relative_pkg_dir| {
476                        if relative_pkg_dir.as_os_str().is_empty() {
477                            ".".into()
478                        } else {
479                            format!("./{}", relative_pkg_dir.to_string_lossy())
480                        }
481                    })
482                    .unwrap_or_else(|| format!("{}", buffer_dir.to_string_lossy()));
483
484                (GO_PACKAGE_TASK_VARIABLE.clone(), package_name.to_string())
485            });
486
487        let _subtest_name = variables.get(&VariableName::Custom(Cow::Borrowed("_subtest_name")));
488
489        let go_subtest_variable = extract_subtest_name(_subtest_name.unwrap_or(""))
490            .map(|subtest_name| (GO_SUBTEST_NAME_TASK_VARIABLE.clone(), subtest_name));
491
492        Ok(TaskVariables::from_iter(
493            [go_package_variable, go_subtest_variable]
494                .into_iter()
495                .flatten(),
496        ))
497    }
498
499    fn associated_tasks(
500        &self,
501        _: Option<Arc<dyn language::File>>,
502        _: &AppContext,
503    ) -> Option<TaskTemplates> {
504        let package_cwd = if GO_PACKAGE_TASK_VARIABLE.template_value() == "." {
505            None
506        } else {
507            Some("$ZED_DIRNAME".to_string())
508        };
509
510        Some(TaskTemplates(vec![
511            TaskTemplate {
512                label: format!(
513                    "go test {} -run {}",
514                    GO_PACKAGE_TASK_VARIABLE.template_value(),
515                    VariableName::Symbol.template_value(),
516                ),
517                command: "go".into(),
518                args: vec![
519                    "test".into(),
520                    GO_PACKAGE_TASK_VARIABLE.template_value(),
521                    "-run".into(),
522                    format!("^{}\\$", VariableName::Symbol.template_value(),),
523                ],
524                tags: vec!["go-test".to_owned()],
525                cwd: package_cwd.clone(),
526                ..TaskTemplate::default()
527            },
528            TaskTemplate {
529                label: format!("go test {}", GO_PACKAGE_TASK_VARIABLE.template_value()),
530                command: "go".into(),
531                args: vec!["test".into(), GO_PACKAGE_TASK_VARIABLE.template_value()],
532                cwd: package_cwd.clone(),
533                ..TaskTemplate::default()
534            },
535            TaskTemplate {
536                label: "go test ./...".into(),
537                command: "go".into(),
538                args: vec!["test".into(), "./...".into()],
539                cwd: package_cwd.clone(),
540                ..TaskTemplate::default()
541            },
542            TaskTemplate {
543                label: format!(
544                    "go test {} -v -run {}/{}",
545                    GO_PACKAGE_TASK_VARIABLE.template_value(),
546                    VariableName::Symbol.template_value(),
547                    GO_SUBTEST_NAME_TASK_VARIABLE.template_value(),
548                ),
549                command: "go".into(),
550                args: vec![
551                    "test".into(),
552                    "-v".into(),
553                    "-run".into(),
554                    format!(
555                        "^{}\\$/^{}\\$",
556                        VariableName::Symbol.template_value(),
557                        GO_SUBTEST_NAME_TASK_VARIABLE.template_value(),
558                    ),
559                ],
560                cwd: package_cwd.clone(),
561                tags: vec!["go-subtest".to_owned()],
562                ..TaskTemplate::default()
563            },
564            TaskTemplate {
565                label: format!(
566                    "go test {} -bench {}",
567                    GO_PACKAGE_TASK_VARIABLE.template_value(),
568                    VariableName::Symbol.template_value()
569                ),
570                command: "go".into(),
571                args: vec![
572                    "test".into(),
573                    GO_PACKAGE_TASK_VARIABLE.template_value(),
574                    "-benchmem".into(),
575                    "-run=^$".into(),
576                    "-bench".into(),
577                    format!("^{}\\$", VariableName::Symbol.template_value()),
578                ],
579                cwd: package_cwd.clone(),
580                tags: vec!["go-benchmark".to_owned()],
581                ..TaskTemplate::default()
582            },
583            TaskTemplate {
584                label: format!("go run {}", GO_PACKAGE_TASK_VARIABLE.template_value(),),
585                command: "go".into(),
586                args: vec!["run".into(), ".".into()],
587                cwd: package_cwd.clone(),
588                tags: vec!["go-main".to_owned()],
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());
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}