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;
  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_SUBTEST_NAME_TASK_VARIABLE: VariableName =
412    VariableName::Custom(Cow::Borrowed("GO_SUBTEST_NAME"));
413
414impl ContextProvider for GoContextProvider {
415    fn build_context(
416        &self,
417        variables: &TaskVariables,
418        location: &Location,
419        _: Option<&HashMap<String, String>>,
420        cx: &mut gpui::AppContext,
421    ) -> Result<TaskVariables> {
422        let local_abs_path = location
423            .buffer
424            .read(cx)
425            .file()
426            .and_then(|file| Some(file.as_local()?.abs_path(cx)));
427
428        let go_package_variable = local_abs_path
429            .as_deref()
430            .and_then(|local_abs_path| local_abs_path.parent())
431            .map(|buffer_dir| {
432                // Prefer the relative form `./my-nested-package/is-here` over
433                // absolute path, because it's more readable in the modal, but
434                // the absolute path also works.
435                let package_name = variables
436                    .get(&VariableName::WorktreeRoot)
437                    .and_then(|worktree_abs_path| buffer_dir.strip_prefix(worktree_abs_path).ok())
438                    .map(|relative_pkg_dir| {
439                        if relative_pkg_dir.as_os_str().is_empty() {
440                            ".".into()
441                        } else {
442                            format!("./{}", relative_pkg_dir.to_string_lossy())
443                        }
444                    })
445                    .unwrap_or_else(|| format!("{}", buffer_dir.to_string_lossy()));
446
447                (GO_PACKAGE_TASK_VARIABLE.clone(), package_name.to_string())
448            });
449
450        let _subtest_name = variables.get(&VariableName::Custom(Cow::Borrowed("_subtest_name")));
451
452        let go_subtest_variable = extract_subtest_name(_subtest_name.unwrap_or(""))
453            .map(|subtest_name| (GO_SUBTEST_NAME_TASK_VARIABLE.clone(), subtest_name));
454
455        Ok(TaskVariables::from_iter(
456            [go_package_variable, go_subtest_variable]
457                .into_iter()
458                .flatten(),
459        ))
460    }
461
462    fn associated_tasks(
463        &self,
464        _: Option<Arc<dyn language::File>>,
465        _: &AppContext,
466    ) -> Option<TaskTemplates> {
467        let package_cwd = if GO_PACKAGE_TASK_VARIABLE.template_value() == "." {
468            None
469        } else {
470            Some("$ZED_DIRNAME".to_string())
471        };
472
473        Some(TaskTemplates(vec![
474            TaskTemplate {
475                label: format!(
476                    "go test {} -run {}",
477                    GO_PACKAGE_TASK_VARIABLE.template_value(),
478                    VariableName::Symbol.template_value(),
479                ),
480                command: "go".into(),
481                args: vec![
482                    "test".into(),
483                    "-run".into(),
484                    format!("^{}\\$", VariableName::Symbol.template_value(),),
485                ],
486                tags: vec!["go-test".to_owned()],
487                cwd: package_cwd.clone(),
488                ..TaskTemplate::default()
489            },
490            TaskTemplate {
491                label: format!("go test {}", GO_PACKAGE_TASK_VARIABLE.template_value()),
492                command: "go".into(),
493                args: vec!["test".into()],
494                cwd: package_cwd.clone(),
495                ..TaskTemplate::default()
496            },
497            TaskTemplate {
498                label: "go test ./...".into(),
499                command: "go".into(),
500                args: vec!["test".into(), "./...".into()],
501                cwd: package_cwd.clone(),
502                ..TaskTemplate::default()
503            },
504            TaskTemplate {
505                label: format!(
506                    "go test {} -v -run {}/{}",
507                    GO_PACKAGE_TASK_VARIABLE.template_value(),
508                    VariableName::Symbol.template_value(),
509                    GO_SUBTEST_NAME_TASK_VARIABLE.template_value(),
510                ),
511                command: "go".into(),
512                args: vec![
513                    "test".into(),
514                    "-v".into(),
515                    "-run".into(),
516                    format!(
517                        "^{}\\$/^{}\\$",
518                        VariableName::Symbol.template_value(),
519                        GO_SUBTEST_NAME_TASK_VARIABLE.template_value(),
520                    ),
521                ],
522                cwd: package_cwd.clone(),
523                tags: vec!["go-subtest".to_owned()],
524                ..TaskTemplate::default()
525            },
526            TaskTemplate {
527                label: format!(
528                    "go test {} -bench {}",
529                    GO_PACKAGE_TASK_VARIABLE.template_value(),
530                    VariableName::Symbol.template_value()
531                ),
532                command: "go".into(),
533                args: vec![
534                    "test".into(),
535                    "-benchmem".into(),
536                    "-run=^$".into(),
537                    "-bench".into(),
538                    format!("^{}\\$", VariableName::Symbol.template_value()),
539                ],
540                cwd: package_cwd.clone(),
541                tags: vec!["go-benchmark".to_owned()],
542                ..TaskTemplate::default()
543            },
544            TaskTemplate {
545                label: format!("go run {}", GO_PACKAGE_TASK_VARIABLE.template_value(),),
546                command: "go".into(),
547                args: vec!["run".into(), ".".into()],
548                cwd: package_cwd.clone(),
549                tags: vec!["go-main".to_owned()],
550                ..TaskTemplate::default()
551            },
552        ]))
553    }
554}
555
556fn extract_subtest_name(input: &str) -> Option<String> {
557    let replaced_spaces = input.trim_matches('"').replace(' ', "_");
558
559    Some(
560        GO_ESCAPE_SUBTEST_NAME_REGEX
561            .replace_all(&replaced_spaces, |caps: &regex::Captures| {
562                format!("\\{}", &caps[0])
563            })
564            .to_string(),
565    )
566}
567
568#[cfg(test)]
569mod tests {
570    use super::*;
571    use crate::language;
572    use gpui::Hsla;
573    use theme::SyntaxTheme;
574
575    #[gpui::test]
576    async fn test_go_label_for_completion() {
577        let adapter = Arc::new(GoLspAdapter);
578        let language = language("go", tree_sitter_go::LANGUAGE.into());
579
580        let theme = SyntaxTheme::new_test([
581            ("type", Hsla::default()),
582            ("keyword", Hsla::default()),
583            ("function", Hsla::default()),
584            ("number", Hsla::default()),
585            ("property", Hsla::default()),
586        ]);
587        language.set_theme(&theme);
588
589        let grammar = language.grammar().unwrap();
590        let highlight_function = grammar.highlight_id_for_name("function").unwrap();
591        let highlight_type = grammar.highlight_id_for_name("type").unwrap();
592        let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
593        let highlight_number = grammar.highlight_id_for_name("number").unwrap();
594
595        assert_eq!(
596            adapter
597                .label_for_completion(
598                    &lsp::CompletionItem {
599                        kind: Some(lsp::CompletionItemKind::FUNCTION),
600                        label: "Hello".to_string(),
601                        detail: Some("func(a B) c.D".to_string()),
602                        ..Default::default()
603                    },
604                    &language
605                )
606                .await,
607            Some(CodeLabel {
608                text: "Hello(a B) c.D".to_string(),
609                filter_range: 0..5,
610                runs: vec![
611                    (0..5, highlight_function),
612                    (8..9, highlight_type),
613                    (13..14, highlight_type),
614                ],
615            })
616        );
617
618        // Nested methods
619        assert_eq!(
620            adapter
621                .label_for_completion(
622                    &lsp::CompletionItem {
623                        kind: Some(lsp::CompletionItemKind::METHOD),
624                        label: "one.two.Three".to_string(),
625                        detail: Some("func() [3]interface{}".to_string()),
626                        ..Default::default()
627                    },
628                    &language
629                )
630                .await,
631            Some(CodeLabel {
632                text: "one.two.Three() [3]interface{}".to_string(),
633                filter_range: 0..13,
634                runs: vec![
635                    (8..13, highlight_function),
636                    (17..18, highlight_number),
637                    (19..28, highlight_keyword),
638                ],
639            })
640        );
641
642        // Nested fields
643        assert_eq!(
644            adapter
645                .label_for_completion(
646                    &lsp::CompletionItem {
647                        kind: Some(lsp::CompletionItemKind::FIELD),
648                        label: "two.Three".to_string(),
649                        detail: Some("a.Bcd".to_string()),
650                        ..Default::default()
651                    },
652                    &language
653                )
654                .await,
655            Some(CodeLabel {
656                text: "two.Three a.Bcd".to_string(),
657                filter_range: 0..9,
658                runs: vec![(12..15, highlight_type)],
659            })
660        );
661    }
662}