go.rs

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