go.rs

   1use anyhow::{Context as _, Result};
   2use async_trait::async_trait;
   3use collections::HashMap;
   4use futures::StreamExt;
   5use gpui::{App, AsyncApp, Entity, Task};
   6use http_client::github::latest_github_release;
   7pub use language::*;
   8use language::{
   9    LanguageName, LanguageToolchainStore, LspAdapterDelegate, LspInstaller,
  10    language_settings::LanguageSettings,
  11};
  12use lsp::{LanguageServerBinary, LanguageServerName};
  13
  14use project::lsp_store::language_server_settings;
  15use regex::Regex;
  16use serde_json::{Value, json};
  17use settings::SemanticTokenRules;
  18use smol::fs;
  19use std::{
  20    borrow::Cow,
  21    ffi::{OsStr, OsString},
  22    ops::Range,
  23    path::{Path, PathBuf},
  24    process::Output,
  25    str,
  26    sync::{
  27        Arc, LazyLock,
  28        atomic::{AtomicBool, Ordering::SeqCst},
  29    },
  30};
  31use task::{TaskTemplate, TaskTemplates, TaskVariables, VariableName};
  32use util::{ResultExt, fs::remove_matching, maybe, merge_json_value_into};
  33
  34pub(crate) fn semantic_token_rules() -> SemanticTokenRules {
  35    let content = grammars::get_file("go/semantic_token_rules.json")
  36        .expect("missing go/semantic_token_rules.json");
  37    let json = std::str::from_utf8(&content.data).expect("invalid utf-8 in semantic_token_rules");
  38    settings::parse_json_with_comments::<SemanticTokenRules>(json)
  39        .expect("failed to parse go semantic_token_rules.json")
  40}
  41
  42fn server_binary_arguments() -> Vec<OsString> {
  43    vec!["-mode=stdio".into()]
  44}
  45
  46#[derive(Copy, Clone)]
  47pub struct GoLspAdapter;
  48
  49impl GoLspAdapter {
  50    const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("gopls");
  51}
  52
  53static VERSION_REGEX: LazyLock<Regex> =
  54    LazyLock::new(|| Regex::new(r"\d+\.\d+\.\d+").expect("Failed to create VERSION_REGEX"));
  55
  56static GO_ESCAPE_SUBTEST_NAME_REGEX: LazyLock<Regex> = LazyLock::new(|| {
  57    Regex::new(r#"[.*+?^${}()|\[\]\\"']"#).expect("Failed to create GO_ESCAPE_SUBTEST_NAME_REGEX")
  58});
  59
  60const BINARY: &str = if cfg!(target_os = "windows") {
  61    "gopls.exe"
  62} else {
  63    "gopls"
  64};
  65
  66impl LspInstaller for GoLspAdapter {
  67    type BinaryVersion = Option<String>;
  68
  69    async fn fetch_latest_server_version(
  70        &self,
  71        delegate: &dyn LspAdapterDelegate,
  72        _: bool,
  73        cx: &mut AsyncApp,
  74    ) -> Result<Option<String>> {
  75        static DID_SHOW_NOTIFICATION: AtomicBool = AtomicBool::new(false);
  76
  77        const NOTIFICATION_MESSAGE: &str =
  78            "Could not install the Go language server `gopls`, because `go` was not found.";
  79
  80        if delegate.which("go".as_ref()).await.is_none() {
  81            if DID_SHOW_NOTIFICATION
  82                .compare_exchange(false, true, SeqCst, SeqCst)
  83                .is_ok()
  84            {
  85                cx.update(|cx| {
  86                    delegate.show_notification(NOTIFICATION_MESSAGE, cx);
  87                });
  88            }
  89            anyhow::bail!(
  90                "Could not install the Go language server `gopls`, because `go` was not found."
  91            );
  92        }
  93
  94        let release =
  95            latest_github_release("golang/tools", false, false, delegate.http_client()).await?;
  96        let version: Option<String> = release.tag_name.strip_prefix("gopls/v").map(str::to_string);
  97        if version.is_none() {
  98            log::warn!(
  99                "couldn't infer gopls version from GitHub release tag name '{}'",
 100                release.tag_name
 101            );
 102        }
 103        Ok(version)
 104    }
 105
 106    async fn check_if_user_installed(
 107        &self,
 108        delegate: &dyn LspAdapterDelegate,
 109        _: Option<Toolchain>,
 110        _: &AsyncApp,
 111    ) -> Option<LanguageServerBinary> {
 112        let path = delegate.which(Self::SERVER_NAME.as_ref()).await?;
 113        Some(LanguageServerBinary {
 114            path,
 115            arguments: server_binary_arguments(),
 116            env: None,
 117        })
 118    }
 119
 120    async fn fetch_server_binary(
 121        &self,
 122        version: Option<String>,
 123        container_dir: PathBuf,
 124        delegate: &dyn LspAdapterDelegate,
 125    ) -> Result<LanguageServerBinary> {
 126        let go = delegate.which("go".as_ref()).await.unwrap_or("go".into());
 127        let go_version_output = util::command::new_command(&go)
 128            .args(["version"])
 129            .output()
 130            .await
 131            .context("failed to get go version via `go version` command`")?;
 132        let go_version = parse_version_output(&go_version_output)?;
 133
 134        if let Some(version) = version {
 135            let binary_path = container_dir.join(format!("gopls_{version}_go_{go_version}"));
 136            if let Ok(metadata) = fs::metadata(&binary_path).await
 137                && metadata.is_file()
 138            {
 139                remove_matching(&container_dir, |entry| {
 140                    entry != binary_path && entry.file_name() != Some(OsStr::new("gobin"))
 141                })
 142                .await;
 143
 144                return Ok(LanguageServerBinary {
 145                    path: binary_path.to_path_buf(),
 146                    arguments: server_binary_arguments(),
 147                    env: None,
 148                });
 149            }
 150        } else if let Some(path) = get_cached_server_binary(&container_dir).await {
 151            return Ok(path);
 152        }
 153
 154        let gobin_dir = container_dir.join("gobin");
 155        fs::create_dir_all(&gobin_dir).await?;
 156        let install_output = util::command::new_command(go)
 157            .env("GO111MODULE", "on")
 158            .env("GOBIN", &gobin_dir)
 159            .args(["install", "golang.org/x/tools/gopls@latest"])
 160            .output()
 161            .await?;
 162
 163        if !install_output.status.success() {
 164            log::error!(
 165                "failed to install gopls via `go install`. stdout: {:?}, stderr: {:?}",
 166                String::from_utf8_lossy(&install_output.stdout),
 167                String::from_utf8_lossy(&install_output.stderr)
 168            );
 169            anyhow::bail!(
 170                "failed to install gopls with `go install`. Is `go` installed and in the PATH? Check logs for more information."
 171            );
 172        }
 173
 174        let installed_binary_path = gobin_dir.join(BINARY);
 175        let version_output = util::command::new_command(&installed_binary_path)
 176            .arg("version")
 177            .output()
 178            .await
 179            .context("failed to run installed gopls binary")?;
 180        let gopls_version = parse_version_output(&version_output)?;
 181        let binary_path = container_dir.join(format!("gopls_{gopls_version}_go_{go_version}"));
 182        fs::rename(&installed_binary_path, &binary_path).await?;
 183
 184        Ok(LanguageServerBinary {
 185            path: binary_path.to_path_buf(),
 186            arguments: server_binary_arguments(),
 187            env: None,
 188        })
 189    }
 190
 191    async fn cached_server_binary(
 192        &self,
 193        container_dir: PathBuf,
 194        _: &dyn LspAdapterDelegate,
 195    ) -> Option<LanguageServerBinary> {
 196        get_cached_server_binary(&container_dir).await
 197    }
 198}
 199
 200#[async_trait(?Send)]
 201impl LspAdapter for GoLspAdapter {
 202    fn name(&self) -> LanguageServerName {
 203        Self::SERVER_NAME
 204    }
 205
 206    async fn initialization_options(
 207        self: Arc<Self>,
 208        delegate: &Arc<dyn LspAdapterDelegate>,
 209        cx: &mut AsyncApp,
 210    ) -> Result<Option<serde_json::Value>> {
 211        let semantic_tokens_enabled = cx.update(|cx| {
 212            LanguageSettings::resolve(None, Some(&LanguageName::new("Go")), cx)
 213                .semantic_tokens
 214                .enabled()
 215        });
 216
 217        let mut default_config = json!({
 218            "usePlaceholders": false,
 219            "hints": {
 220                "assignVariableTypes": true,
 221                "compositeLiteralFields": true,
 222                "compositeLiteralTypes": true,
 223                "constantValues": true,
 224                "functionTypeParameters": true,
 225                "parameterNames": true,
 226                "rangeVariableTypes": true
 227            },
 228            "codelenses": {
 229                "test": true
 230            },
 231            "semanticTokens": semantic_tokens_enabled
 232        });
 233
 234        let project_initialization_options = cx.update(|cx| {
 235            language_server_settings(delegate.as_ref(), &self.name(), cx)
 236                .and_then(|s| s.initialization_options.clone())
 237        });
 238
 239        if let Some(override_options) = project_initialization_options {
 240            merge_json_value_into(override_options, &mut default_config);
 241        }
 242
 243        Ok(Some(default_config))
 244    }
 245
 246    async fn workspace_configuration(
 247        self: Arc<Self>,
 248        delegate: &Arc<dyn LspAdapterDelegate>,
 249        _: Option<Toolchain>,
 250        _: Option<lsp::Uri>,
 251        cx: &mut AsyncApp,
 252    ) -> Result<Value> {
 253        Ok(cx
 254            .update(|cx| {
 255                language_server_settings(delegate.as_ref(), &self.name(), cx)
 256                    .and_then(|settings| settings.settings.clone())
 257            })
 258            .unwrap_or_default())
 259    }
 260
 261    async fn label_for_completion(
 262        &self,
 263        completion: &lsp::CompletionItem,
 264        language: &Arc<Language>,
 265    ) -> Option<CodeLabel> {
 266        let label = &completion.label;
 267
 268        // Gopls returns nested fields and methods as completions.
 269        // To syntax highlight these, combine their final component
 270        // with their detail.
 271        let name_offset = label.rfind('.').unwrap_or(0);
 272
 273        match completion.kind.zip(completion.detail.as_ref()) {
 274            Some((lsp::CompletionItemKind::MODULE, detail)) => {
 275                let text = format!("{label} {detail}");
 276                let source = Rope::from(format!("import {text}").as_str());
 277                let runs = language.highlight_text(&source, 7..7 + text[name_offset..].len());
 278                let filter_range = completion
 279                    .filter_text
 280                    .as_deref()
 281                    .and_then(|filter_text| {
 282                        text.find(filter_text)
 283                            .map(|start| start..start + filter_text.len())
 284                    })
 285                    .unwrap_or(0..label.len());
 286                return Some(CodeLabel::new(text, filter_range, runs));
 287            }
 288            Some((
 289                lsp::CompletionItemKind::CONSTANT | lsp::CompletionItemKind::VARIABLE,
 290                detail,
 291            )) => {
 292                let text = format!("{label} {detail}");
 293                let source =
 294                    Rope::from(format!("var {} {}", &text[name_offset..], detail).as_str());
 295                let runs = adjust_runs(
 296                    name_offset,
 297                    language.highlight_text(&source, 4..4 + text[name_offset..].len()),
 298                );
 299                let filter_range = completion
 300                    .filter_text
 301                    .as_deref()
 302                    .and_then(|filter_text| {
 303                        text.find(filter_text)
 304                            .map(|start| start..start + filter_text.len())
 305                    })
 306                    .unwrap_or(0..label.len());
 307                return Some(CodeLabel::new(text, filter_range, runs));
 308            }
 309            Some((lsp::CompletionItemKind::STRUCT, _)) => {
 310                let text = format!("{label} struct {{}}");
 311                let source = Rope::from(format!("type {}", &text[name_offset..]).as_str());
 312                let runs = adjust_runs(
 313                    name_offset,
 314                    language.highlight_text(&source, 5..5 + text[name_offset..].len()),
 315                );
 316                let filter_range = completion
 317                    .filter_text
 318                    .as_deref()
 319                    .and_then(|filter_text| {
 320                        text.find(filter_text)
 321                            .map(|start| start..start + filter_text.len())
 322                    })
 323                    .unwrap_or(0..label.len());
 324                return Some(CodeLabel::new(text, filter_range, runs));
 325            }
 326            Some((lsp::CompletionItemKind::INTERFACE, _)) => {
 327                let text = format!("{label} interface {{}}");
 328                let source = Rope::from(format!("type {}", &text[name_offset..]).as_str());
 329                let runs = adjust_runs(
 330                    name_offset,
 331                    language.highlight_text(&source, 5..5 + text[name_offset..].len()),
 332                );
 333                let filter_range = completion
 334                    .filter_text
 335                    .as_deref()
 336                    .and_then(|filter_text| {
 337                        text.find(filter_text)
 338                            .map(|start| start..start + filter_text.len())
 339                    })
 340                    .unwrap_or(0..label.len());
 341                return Some(CodeLabel::new(text, filter_range, runs));
 342            }
 343            Some((lsp::CompletionItemKind::FIELD, detail)) => {
 344                let text = format!("{label} {detail}");
 345                let source =
 346                    Rope::from(format!("type T struct {{ {} }}", &text[name_offset..]).as_str());
 347                let runs = adjust_runs(
 348                    name_offset,
 349                    language.highlight_text(&source, 16..16 + text[name_offset..].len()),
 350                );
 351                let filter_range = completion
 352                    .filter_text
 353                    .as_deref()
 354                    .and_then(|filter_text| {
 355                        text.find(filter_text)
 356                            .map(|start| start..start + filter_text.len())
 357                    })
 358                    .unwrap_or(0..label.len());
 359                return Some(CodeLabel::new(text, filter_range, runs));
 360            }
 361            Some((lsp::CompletionItemKind::FUNCTION | lsp::CompletionItemKind::METHOD, detail)) => {
 362                if let Some(signature) = detail.strip_prefix("func") {
 363                    let text = format!("{label}{signature}");
 364                    let source = Rope::from(format!("func {} {{}}", &text[name_offset..]).as_str());
 365                    let runs = adjust_runs(
 366                        name_offset,
 367                        language.highlight_text(&source, 5..5 + text[name_offset..].len()),
 368                    );
 369                    let filter_range = completion
 370                        .filter_text
 371                        .as_deref()
 372                        .and_then(|filter_text| {
 373                            text.find(filter_text)
 374                                .map(|start| start..start + filter_text.len())
 375                        })
 376                        .unwrap_or(0..label.len());
 377                    return Some(CodeLabel::new(text, filter_range, runs));
 378                }
 379            }
 380            _ => {}
 381        }
 382        None
 383    }
 384
 385    async fn label_for_symbol(
 386        &self,
 387        symbol: &language::Symbol,
 388        language: &Arc<Language>,
 389    ) -> Option<CodeLabel> {
 390        let name = &symbol.name;
 391        let (text, filter_range, display_range) = match symbol.kind {
 392            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
 393                let text = format!("func {} () {{}}", 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::STRUCT => {
 399                let text = format!("type {} struct {{}}", name);
 400                let filter_range = 5..5 + name.len();
 401                let display_range = 0..text.len();
 402                (text, filter_range, display_range)
 403            }
 404            lsp::SymbolKind::INTERFACE => {
 405                let text = format!("type {} interface {{}}", name);
 406                let filter_range = 5..5 + name.len();
 407                let display_range = 0..text.len();
 408                (text, filter_range, display_range)
 409            }
 410            lsp::SymbolKind::CLASS => {
 411                let text = format!("type {} T", name);
 412                let filter_range = 5..5 + name.len();
 413                let display_range = 0..filter_range.end;
 414                (text, filter_range, display_range)
 415            }
 416            lsp::SymbolKind::CONSTANT => {
 417                let text = format!("const {} = nil", name);
 418                let filter_range = 6..6 + name.len();
 419                let display_range = 0..filter_range.end;
 420                (text, filter_range, display_range)
 421            }
 422            lsp::SymbolKind::VARIABLE => {
 423                let text = format!("var {} = nil", name);
 424                let filter_range = 4..4 + name.len();
 425                let display_range = 0..filter_range.end;
 426                (text, filter_range, display_range)
 427            }
 428            lsp::SymbolKind::MODULE => {
 429                let text = format!("package {}", name);
 430                let filter_range = 8..8 + name.len();
 431                let display_range = 0..filter_range.end;
 432                (text, filter_range, display_range)
 433            }
 434            _ => return None,
 435        };
 436
 437        Some(CodeLabel::new(
 438            text[display_range.clone()].to_string(),
 439            filter_range,
 440            language.highlight_text(&text.as_str().into(), display_range),
 441        ))
 442    }
 443
 444    fn client_command(
 445        &self,
 446        command_name: &str,
 447        arguments: &[serde_json::Value],
 448    ) -> Option<ClientCommand> {
 449        if let "gopls.run_tests" = command_name {
 450            let template = go_test_task_template(arguments.first()?)?;
 451            Some(ClientCommand::ScheduleTask(template))
 452        } else {
 453            None
 454        }
 455    }
 456
 457    fn diagnostic_message_to_markdown(&self, message: &str) -> Option<String> {
 458        static REGEX: LazyLock<Regex> =
 459            LazyLock::new(|| Regex::new(r"(?m)\n\s*").expect("Failed to create REGEX"));
 460        Some(REGEX.replace_all(message, "\n\n").to_string())
 461    }
 462}
 463
 464fn json_string_array(value: &serde_json::Value, key: &str) -> Vec<String> {
 465    value
 466        .get(key)
 467        .and_then(|v| v.as_array())
 468        .map(|arr| {
 469            arr.iter()
 470                .filter_map(|v| v.as_str().map(String::from))
 471                .collect()
 472        })
 473        .unwrap_or_default()
 474}
 475
 476fn go_test_task_template(arg: &serde_json::Value) -> Option<task::TaskTemplate> {
 477    let tests = json_string_array(arg, "Tests");
 478    let benchmarks = json_string_array(arg, "Benchmarks");
 479    if tests.is_empty() && benchmarks.is_empty() {
 480        return None;
 481    }
 482
 483    let mut go_args = vec!["test".to_string(), "-test.fullpath=true".to_string()];
 484
 485    if tests.is_empty() {
 486        go_args.push("-benchmem".to_string());
 487        go_args.push("-run=^$".to_string());
 488    } else {
 489        go_args.push("-timeout".to_string());
 490        go_args.push("30s".to_string());
 491        go_args.push("-run".to_string());
 492        if tests.len() == 1 {
 493            go_args.push(format!("^{}$", tests[0]));
 494        } else {
 495            go_args.push(format!("^({})$", tests.join("|")));
 496        }
 497    }
 498
 499    if !benchmarks.is_empty() {
 500        go_args.push("-bench".to_string());
 501        if benchmarks.len() == 1 {
 502            go_args.push(format!("^{}$", benchmarks[0]));
 503        } else {
 504            go_args.push(format!("^({})$", benchmarks.join("|")));
 505        }
 506    }
 507
 508    go_args.push(".".to_string());
 509
 510    let label = if !tests.is_empty() {
 511        format!("go test {}", tests.join(", "))
 512    } else {
 513        format!("go bench {}", benchmarks.join(", "))
 514    };
 515
 516    let cwd = arg
 517        .get("URI")
 518        .and_then(|v| v.as_str())
 519        .and_then(|uri| uri.strip_prefix("file://"))
 520        .and_then(|path| std::path::Path::new(path).parent())
 521        .map(|p| p.to_string_lossy().into_owned());
 522
 523    Some(task::TaskTemplate {
 524        label,
 525        command: "go".to_string(),
 526        args: go_args,
 527        cwd,
 528        ..task::TaskTemplate::default()
 529    })
 530}
 531
 532fn parse_version_output(output: &Output) -> Result<&str> {
 533    let version_stdout =
 534        str::from_utf8(&output.stdout).context("version command produced invalid utf8 output")?;
 535
 536    let version = VERSION_REGEX
 537        .find(version_stdout)
 538        .with_context(|| format!("failed to parse version output '{version_stdout}'"))?
 539        .as_str();
 540
 541    Ok(version)
 542}
 543
 544async fn get_cached_server_binary(container_dir: &Path) -> Option<LanguageServerBinary> {
 545    maybe!(async {
 546        let mut last_binary_path = None;
 547        let mut entries = fs::read_dir(container_dir).await?;
 548        while let Some(entry) = entries.next().await {
 549            let entry = entry?;
 550            if entry.file_type().await?.is_file()
 551                && entry
 552                    .file_name()
 553                    .to_str()
 554                    .is_some_and(|name| name.starts_with("gopls_"))
 555            {
 556                last_binary_path = Some(entry.path());
 557            }
 558        }
 559
 560        let path = last_binary_path.context("no cached binary")?;
 561        anyhow::Ok(LanguageServerBinary {
 562            path,
 563            arguments: server_binary_arguments(),
 564            env: None,
 565        })
 566    })
 567    .await
 568    .log_err()
 569}
 570
 571fn adjust_runs(
 572    delta: usize,
 573    mut runs: Vec<(Range<usize>, HighlightId)>,
 574) -> Vec<(Range<usize>, HighlightId)> {
 575    for (range, _) in &mut runs {
 576        range.start += delta;
 577        range.end += delta;
 578    }
 579    runs
 580}
 581
 582pub(crate) struct GoContextProvider;
 583
 584const GO_PACKAGE_TASK_VARIABLE: VariableName = VariableName::Custom(Cow::Borrowed("GO_PACKAGE"));
 585const GO_MODULE_ROOT_TASK_VARIABLE: VariableName =
 586    VariableName::Custom(Cow::Borrowed("GO_MODULE_ROOT"));
 587const GO_SUBTEST_NAME_TASK_VARIABLE: VariableName =
 588    VariableName::Custom(Cow::Borrowed("GO_SUBTEST_NAME"));
 589const GO_TABLE_TEST_CASE_NAME_TASK_VARIABLE: VariableName =
 590    VariableName::Custom(Cow::Borrowed("GO_TABLE_TEST_CASE_NAME"));
 591const GO_SUITE_NAME_TASK_VARIABLE: VariableName =
 592    VariableName::Custom(Cow::Borrowed("GO_SUITE_NAME"));
 593
 594impl ContextProvider for GoContextProvider {
 595    fn build_context(
 596        &self,
 597        variables: &TaskVariables,
 598        location: ContextLocation<'_>,
 599        _: Option<HashMap<String, String>>,
 600        _: Arc<dyn LanguageToolchainStore>,
 601        cx: &mut gpui::App,
 602    ) -> Task<Result<TaskVariables>> {
 603        let local_abs_path = location
 604            .file_location
 605            .buffer
 606            .read(cx)
 607            .file()
 608            .and_then(|file| Some(file.as_local()?.abs_path(cx)));
 609
 610        let go_package_variable = local_abs_path
 611            .as_deref()
 612            .and_then(|local_abs_path| local_abs_path.parent())
 613            .map(|buffer_dir| {
 614                // Prefer the relative form `./my-nested-package/is-here` over
 615                // absolute path, because it's more readable in the modal, but
 616                // the absolute path also works.
 617                let package_name = variables
 618                    .get(&VariableName::WorktreeRoot)
 619                    .and_then(|worktree_abs_path| buffer_dir.strip_prefix(worktree_abs_path).ok())
 620                    .map(|relative_pkg_dir| {
 621                        if relative_pkg_dir.as_os_str().is_empty() {
 622                            ".".into()
 623                        } else {
 624                            format!("./{}", relative_pkg_dir.to_string_lossy())
 625                        }
 626                    })
 627                    .unwrap_or_else(|| format!("{}", buffer_dir.to_string_lossy()));
 628
 629                (GO_PACKAGE_TASK_VARIABLE.clone(), package_name)
 630            });
 631
 632        let go_module_root_variable = local_abs_path
 633            .as_deref()
 634            .and_then(|local_abs_path| local_abs_path.parent())
 635            .map(|buffer_dir| {
 636                // Walk dirtree up until getting the first go.mod file
 637                let module_dir = buffer_dir
 638                    .ancestors()
 639                    .find(|dir| dir.join("go.mod").is_file())
 640                    .map(|dir| dir.to_string_lossy().into_owned())
 641                    .unwrap_or_else(|| ".".to_string());
 642
 643                (GO_MODULE_ROOT_TASK_VARIABLE.clone(), module_dir)
 644            });
 645
 646        let _subtest_name = variables.get(&VariableName::Custom(Cow::Borrowed("_subtest_name")));
 647
 648        let go_subtest_variable = extract_subtest_name(_subtest_name.unwrap_or(""))
 649            .map(|subtest_name| (GO_SUBTEST_NAME_TASK_VARIABLE.clone(), subtest_name));
 650
 651        let _table_test_case_name = variables.get(&VariableName::Custom(Cow::Borrowed(
 652            "_table_test_case_name",
 653        )));
 654
 655        let go_table_test_case_variable = _table_test_case_name
 656            .and_then(extract_subtest_name)
 657            .map(|case_name| (GO_TABLE_TEST_CASE_NAME_TASK_VARIABLE.clone(), case_name));
 658
 659        let _suite_name = variables.get(&VariableName::Custom(Cow::Borrowed("_suite_name")));
 660
 661        let go_suite_variable = _suite_name
 662            .and_then(extract_subtest_name)
 663            .map(|suite_name| (GO_SUITE_NAME_TASK_VARIABLE.clone(), suite_name));
 664
 665        Task::ready(Ok(TaskVariables::from_iter(
 666            [
 667                go_package_variable,
 668                go_subtest_variable,
 669                go_table_test_case_variable,
 670                go_suite_variable,
 671                go_module_root_variable,
 672            ]
 673            .into_iter()
 674            .flatten(),
 675        )))
 676    }
 677
 678    fn associated_tasks(&self, _: Option<Entity<Buffer>>, _: &App) -> Task<Option<TaskTemplates>> {
 679        let package_cwd = if GO_PACKAGE_TASK_VARIABLE.template_value() == "." {
 680            None
 681        } else {
 682            Some("$ZED_DIRNAME".to_string())
 683        };
 684        let module_cwd = Some(GO_MODULE_ROOT_TASK_VARIABLE.template_value());
 685
 686        Task::ready(Some(TaskTemplates(vec![
 687            TaskTemplate {
 688                label: format!(
 689                    "go test {} -v -run Test{}/{}",
 690                    GO_PACKAGE_TASK_VARIABLE.template_value(),
 691                    GO_SUITE_NAME_TASK_VARIABLE.template_value(),
 692                    VariableName::Symbol.template_value(),
 693                ),
 694                command: "go".into(),
 695                args: vec![
 696                    "test".into(),
 697                    "-v".into(),
 698                    "-run".into(),
 699                    format!(
 700                        "\\^Test{}\\$/\\^{}\\$",
 701                        GO_SUITE_NAME_TASK_VARIABLE.template_value(),
 702                        VariableName::Symbol.template_value(),
 703                    ),
 704                ],
 705                cwd: package_cwd.clone(),
 706                tags: vec!["go-testify-suite".to_owned()],
 707                ..TaskTemplate::default()
 708            },
 709            TaskTemplate {
 710                label: format!(
 711                    "go test {} -v -run {}/{}",
 712                    GO_PACKAGE_TASK_VARIABLE.template_value(),
 713                    VariableName::Symbol.template_value(),
 714                    GO_TABLE_TEST_CASE_NAME_TASK_VARIABLE.template_value(),
 715                ),
 716                command: "go".into(),
 717                args: vec![
 718                    "test".into(),
 719                    "-v".into(),
 720                    "-run".into(),
 721                    format!(
 722                        "\\^{}\\$/\\^{}\\$",
 723                        VariableName::Symbol.template_value(),
 724                        GO_TABLE_TEST_CASE_NAME_TASK_VARIABLE.template_value(),
 725                    ),
 726                ],
 727                cwd: package_cwd.clone(),
 728                tags: vec![
 729                    "go-table-test-case".to_owned(),
 730                    "go-table-test-case-without-explicit-variable".to_owned(),
 731                ],
 732                ..TaskTemplate::default()
 733            },
 734            TaskTemplate {
 735                label: format!(
 736                    "go test {} -run {}",
 737                    GO_PACKAGE_TASK_VARIABLE.template_value(),
 738                    VariableName::Symbol.template_value(),
 739                ),
 740                command: "go".into(),
 741                args: vec![
 742                    "test".into(),
 743                    "-run".into(),
 744                    format!("\\^{}\\$", VariableName::Symbol.template_value(),),
 745                ],
 746                tags: vec!["go-test".to_owned()],
 747                cwd: package_cwd.clone(),
 748                ..TaskTemplate::default()
 749            },
 750            TaskTemplate {
 751                label: format!(
 752                    "go test {} -run {}",
 753                    GO_PACKAGE_TASK_VARIABLE.template_value(),
 754                    VariableName::Symbol.template_value(),
 755                ),
 756                command: "go".into(),
 757                args: vec![
 758                    "test".into(),
 759                    "-run".into(),
 760                    format!("\\^{}\\$", VariableName::Symbol.template_value(),),
 761                ],
 762                tags: vec!["go-example".to_owned()],
 763                cwd: package_cwd.clone(),
 764                ..TaskTemplate::default()
 765            },
 766            TaskTemplate {
 767                label: format!("go test {}", GO_PACKAGE_TASK_VARIABLE.template_value()),
 768                command: "go".into(),
 769                args: vec!["test".into()],
 770                cwd: package_cwd.clone(),
 771                ..TaskTemplate::default()
 772            },
 773            TaskTemplate {
 774                label: "go test ./...".into(),
 775                command: "go".into(),
 776                args: vec!["test".into(), "./...".into()],
 777                cwd: module_cwd.clone(),
 778                ..TaskTemplate::default()
 779            },
 780            TaskTemplate {
 781                label: format!(
 782                    "go test {} -v -run {}/{}",
 783                    GO_PACKAGE_TASK_VARIABLE.template_value(),
 784                    VariableName::Symbol.template_value(),
 785                    GO_SUBTEST_NAME_TASK_VARIABLE.template_value(),
 786                ),
 787                command: "go".into(),
 788                args: vec![
 789                    "test".into(),
 790                    "-v".into(),
 791                    "-run".into(),
 792                    format!(
 793                        "'^{}$/^{}$'",
 794                        VariableName::Symbol.template_value(),
 795                        GO_SUBTEST_NAME_TASK_VARIABLE.template_value(),
 796                    ),
 797                ],
 798                cwd: package_cwd.clone(),
 799                tags: vec!["go-subtest".to_owned()],
 800                ..TaskTemplate::default()
 801            },
 802            TaskTemplate {
 803                label: format!(
 804                    "go test {} -bench {}",
 805                    GO_PACKAGE_TASK_VARIABLE.template_value(),
 806                    VariableName::Symbol.template_value()
 807                ),
 808                command: "go".into(),
 809                args: vec![
 810                    "test".into(),
 811                    "-benchmem".into(),
 812                    "-run='^$'".into(),
 813                    "-bench".into(),
 814                    format!("\\^{}\\$", VariableName::Symbol.template_value()),
 815                ],
 816                cwd: package_cwd.clone(),
 817                tags: vec!["go-benchmark".to_owned()],
 818                ..TaskTemplate::default()
 819            },
 820            TaskTemplate {
 821                label: format!(
 822                    "go test {} -fuzz=Fuzz -run {}",
 823                    GO_PACKAGE_TASK_VARIABLE.template_value(),
 824                    VariableName::Symbol.template_value(),
 825                ),
 826                command: "go".into(),
 827                args: vec![
 828                    "test".into(),
 829                    "-fuzz=Fuzz".into(),
 830                    "-run".into(),
 831                    format!("\\^{}\\$", VariableName::Symbol.template_value(),),
 832                ],
 833                tags: vec!["go-fuzz".to_owned()],
 834                cwd: package_cwd.clone(),
 835                ..TaskTemplate::default()
 836            },
 837            TaskTemplate {
 838                label: format!("go run {}", GO_PACKAGE_TASK_VARIABLE.template_value(),),
 839                command: "go".into(),
 840                args: vec!["run".into(), ".".into()],
 841                cwd: package_cwd.clone(),
 842                tags: vec!["go-main".to_owned()],
 843                ..TaskTemplate::default()
 844            },
 845            TaskTemplate {
 846                label: format!("go generate {}", GO_PACKAGE_TASK_VARIABLE.template_value()),
 847                command: "go".into(),
 848                args: vec!["generate".into()],
 849                cwd: package_cwd,
 850                tags: vec!["go-generate".to_owned()],
 851                ..TaskTemplate::default()
 852            },
 853            TaskTemplate {
 854                label: "go generate ./...".into(),
 855                command: "go".into(),
 856                args: vec!["generate".into(), "./...".into()],
 857                cwd: module_cwd,
 858                ..TaskTemplate::default()
 859            },
 860        ])))
 861    }
 862}
 863
 864fn extract_subtest_name(input: &str) -> Option<String> {
 865    let content = if input.starts_with('`') && input.ends_with('`') {
 866        input.trim_matches('`')
 867    } else {
 868        input.trim_matches('"')
 869    };
 870
 871    let processed = content
 872        .chars()
 873        .map(|c| if c.is_whitespace() { '_' } else { c })
 874        .collect::<String>();
 875
 876    Some(
 877        GO_ESCAPE_SUBTEST_NAME_REGEX
 878            .replace_all(&processed, |caps: &regex::Captures| {
 879                format!("\\{}", &caps[0])
 880            })
 881            .to_string(),
 882    )
 883}
 884
 885#[cfg(test)]
 886mod tests {
 887    use super::*;
 888    use crate::language;
 889    use gpui::{AppContext, Hsla, TestAppContext};
 890    use theme::SyntaxTheme;
 891
 892    #[gpui::test]
 893    async fn test_go_label_for_completion() {
 894        let adapter = Arc::new(GoLspAdapter);
 895        let language = language("go", tree_sitter_go::LANGUAGE.into());
 896
 897        let theme = SyntaxTheme::new_test([
 898            ("type", Hsla::default()),
 899            ("keyword", Hsla::default()),
 900            ("function", Hsla::default()),
 901            ("number", Hsla::default()),
 902            ("property", Hsla::default()),
 903        ]);
 904        language.set_theme(&theme);
 905
 906        let grammar = language.grammar().unwrap();
 907        let highlight_function = grammar.highlight_id_for_name("function").unwrap();
 908        let highlight_type = grammar.highlight_id_for_name("type").unwrap();
 909        let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
 910        let highlight_number = grammar.highlight_id_for_name("number").unwrap();
 911        let highlight_field = grammar.highlight_id_for_name("property").unwrap();
 912
 913        assert_eq!(
 914            adapter
 915                .label_for_completion(
 916                    &lsp::CompletionItem {
 917                        kind: Some(lsp::CompletionItemKind::FUNCTION),
 918                        label: "Hello".to_string(),
 919                        detail: Some("func(a B) c.D".to_string()),
 920                        ..Default::default()
 921                    },
 922                    &language
 923                )
 924                .await,
 925            Some(CodeLabel::new(
 926                "Hello(a B) c.D".to_string(),
 927                0..5,
 928                vec![
 929                    (0..5, highlight_function),
 930                    (8..9, highlight_type),
 931                    (13..14, highlight_type),
 932                ]
 933            ))
 934        );
 935
 936        // Nested methods
 937        assert_eq!(
 938            adapter
 939                .label_for_completion(
 940                    &lsp::CompletionItem {
 941                        kind: Some(lsp::CompletionItemKind::METHOD),
 942                        label: "one.two.Three".to_string(),
 943                        detail: Some("func() [3]interface{}".to_string()),
 944                        ..Default::default()
 945                    },
 946                    &language
 947                )
 948                .await,
 949            Some(CodeLabel::new(
 950                "one.two.Three() [3]interface{}".to_string(),
 951                0..13,
 952                vec![
 953                    (8..13, highlight_function),
 954                    (17..18, highlight_number),
 955                    (19..28, highlight_keyword),
 956                ],
 957            ))
 958        );
 959
 960        // Nested fields
 961        assert_eq!(
 962            adapter
 963                .label_for_completion(
 964                    &lsp::CompletionItem {
 965                        kind: Some(lsp::CompletionItemKind::FIELD),
 966                        label: "two.Three".to_string(),
 967                        detail: Some("a.Bcd".to_string()),
 968                        ..Default::default()
 969                    },
 970                    &language
 971                )
 972                .await,
 973            Some(CodeLabel::new(
 974                "two.Three a.Bcd".to_string(),
 975                0..9,
 976                vec![(4..9, highlight_field), (12..15, highlight_type)],
 977            ))
 978        );
 979    }
 980
 981    #[gpui::test]
 982    fn test_go_test_main_ignored(cx: &mut TestAppContext) {
 983        let language = language("go", tree_sitter_go::LANGUAGE.into());
 984
 985        let example_test = r#"
 986        package main
 987
 988        func TestMain(m *testing.M) {
 989            os.Exit(m.Run())
 990        }
 991        "#;
 992
 993        let buffer =
 994            cx.new(|cx| crate::Buffer::local(example_test, cx).with_language(language.clone(), cx));
 995        cx.executor().run_until_parked();
 996
 997        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
 998            let snapshot = buffer.snapshot();
 999            snapshot.runnable_ranges(0..example_test.len()).collect()
1000        });
1001
1002        let tag_strings: Vec<String> = runnables
1003            .iter()
1004            .flat_map(|r| &r.runnable.tags)
1005            .map(|tag| tag.0.to_string())
1006            .collect();
1007
1008        assert!(
1009            !tag_strings.contains(&"go-test".to_string()),
1010            "Should NOT find go-test tag, found: {:?}",
1011            tag_strings
1012        );
1013    }
1014
1015    #[gpui::test]
1016    fn test_testify_suite_detection(cx: &mut TestAppContext) {
1017        let language = language("go", tree_sitter_go::LANGUAGE.into());
1018
1019        let testify_suite = r#"
1020        package main
1021
1022        import (
1023            "testing"
1024
1025            "github.com/stretchr/testify/suite"
1026        )
1027
1028        type ExampleSuite struct {
1029            suite.Suite
1030        }
1031
1032        func TestExampleSuite(t *testing.T) {
1033            suite.Run(t, new(ExampleSuite))
1034        }
1035
1036        func (s *ExampleSuite) TestSomething_Success() {
1037            // test code
1038        }
1039        "#;
1040
1041        let buffer = cx
1042            .new(|cx| crate::Buffer::local(testify_suite, cx).with_language(language.clone(), cx));
1043        cx.executor().run_until_parked();
1044
1045        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1046            let snapshot = buffer.snapshot();
1047            snapshot.runnable_ranges(0..testify_suite.len()).collect()
1048        });
1049
1050        let tag_strings: Vec<String> = runnables
1051            .iter()
1052            .flat_map(|r| &r.runnable.tags)
1053            .map(|tag| tag.0.to_string())
1054            .collect();
1055
1056        assert!(
1057            tag_strings.contains(&"go-test".to_string()),
1058            "Should find go-test tag, found: {:?}",
1059            tag_strings
1060        );
1061        assert!(
1062            tag_strings.contains(&"go-testify-suite".to_string()),
1063            "Should find go-testify-suite tag, found: {:?}",
1064            tag_strings
1065        );
1066    }
1067
1068    #[gpui::test]
1069    fn test_go_runnable_detection(cx: &mut TestAppContext) {
1070        let language = language("go", tree_sitter_go::LANGUAGE.into());
1071
1072        let interpreted_string_subtest = r#"
1073        package main
1074
1075        import "testing"
1076
1077        func TestExample(t *testing.T) {
1078            t.Run("subtest with double quotes", func(t *testing.T) {
1079                // test code
1080            })
1081        }
1082        "#;
1083
1084        let raw_string_subtest = r#"
1085        package main
1086
1087        import "testing"
1088
1089        func TestExample(t *testing.T) {
1090            t.Run(`subtest with
1091            multiline
1092            backticks`, func(t *testing.T) {
1093                // test code
1094            })
1095        }
1096        "#;
1097
1098        let buffer = cx.new(|cx| {
1099            crate::Buffer::local(interpreted_string_subtest, cx).with_language(language.clone(), cx)
1100        });
1101        cx.executor().run_until_parked();
1102
1103        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1104            let snapshot = buffer.snapshot();
1105            snapshot
1106                .runnable_ranges(0..interpreted_string_subtest.len())
1107                .collect()
1108        });
1109
1110        let tag_strings: Vec<String> = runnables
1111            .iter()
1112            .flat_map(|r| &r.runnable.tags)
1113            .map(|tag| tag.0.to_string())
1114            .collect();
1115
1116        assert!(
1117            tag_strings.contains(&"go-test".to_string()),
1118            "Should find go-test tag, found: {:?}",
1119            tag_strings
1120        );
1121        assert!(
1122            tag_strings.contains(&"go-subtest".to_string()),
1123            "Should find go-subtest tag, found: {:?}",
1124            tag_strings
1125        );
1126
1127        let buffer = cx.new(|cx| {
1128            crate::Buffer::local(raw_string_subtest, cx).with_language(language.clone(), cx)
1129        });
1130        cx.executor().run_until_parked();
1131
1132        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1133            let snapshot = buffer.snapshot();
1134            snapshot
1135                .runnable_ranges(0..raw_string_subtest.len())
1136                .collect()
1137        });
1138
1139        let tag_strings: Vec<String> = runnables
1140            .iter()
1141            .flat_map(|r| &r.runnable.tags)
1142            .map(|tag| tag.0.to_string())
1143            .collect();
1144
1145        assert!(
1146            tag_strings.contains(&"go-test".to_string()),
1147            "Should find go-test tag, found: {:?}",
1148            tag_strings
1149        );
1150        assert!(
1151            tag_strings.contains(&"go-subtest".to_string()),
1152            "Should find go-subtest tag, found: {:?}",
1153            tag_strings
1154        );
1155    }
1156
1157    #[gpui::test]
1158    fn test_go_example_test_detection(cx: &mut TestAppContext) {
1159        let language = language("go", tree_sitter_go::LANGUAGE.into());
1160
1161        let example_test = r#"
1162        package main
1163
1164        import "fmt"
1165
1166        func Example() {
1167            fmt.Println("Hello, world!")
1168            // Output: Hello, world!
1169        }
1170        "#;
1171
1172        let buffer =
1173            cx.new(|cx| crate::Buffer::local(example_test, cx).with_language(language.clone(), cx));
1174        cx.executor().run_until_parked();
1175
1176        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1177            let snapshot = buffer.snapshot();
1178            snapshot.runnable_ranges(0..example_test.len()).collect()
1179        });
1180
1181        let tag_strings: Vec<String> = runnables
1182            .iter()
1183            .flat_map(|r| &r.runnable.tags)
1184            .map(|tag| tag.0.to_string())
1185            .collect();
1186
1187        assert!(
1188            tag_strings.contains(&"go-example".to_string()),
1189            "Should find go-example tag, found: {:?}",
1190            tag_strings
1191        );
1192    }
1193
1194    #[gpui::test]
1195    fn test_go_table_test_slice_detection(cx: &mut TestAppContext) {
1196        let language = language("go", tree_sitter_go::LANGUAGE.into());
1197
1198        let table_test = r#"
1199        package main
1200
1201        import "testing"
1202
1203        func TestExample(t *testing.T) {
1204            _ = "some random string"
1205
1206            testCases := []struct{
1207                name string
1208                anotherStr string
1209            }{
1210                {
1211                    name: "test case 1",
1212                    anotherStr: "foo",
1213                },
1214                {
1215                    name: "test case 2",
1216                    anotherStr: "bar",
1217                },
1218                {
1219                    name: "test case 3",
1220                    anotherStr: "baz",
1221                },
1222            }
1223
1224            notATableTest := []struct{
1225                name string
1226            }{
1227                {
1228                    name: "some string",
1229                },
1230                {
1231                    name: "some other string",
1232                },
1233            }
1234
1235            for _, tc := range testCases {
1236                t.Run(tc.name, func(t *testing.T) {
1237                    // test code here
1238                })
1239            }
1240        }
1241        "#;
1242
1243        let buffer =
1244            cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
1245        cx.executor().run_until_parked();
1246
1247        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1248            let snapshot = buffer.snapshot();
1249            snapshot.runnable_ranges(0..table_test.len()).collect()
1250        });
1251
1252        let tag_strings: Vec<String> = runnables
1253            .iter()
1254            .flat_map(|r| &r.runnable.tags)
1255            .map(|tag| tag.0.to_string())
1256            .collect();
1257
1258        assert!(
1259            tag_strings.contains(&"go-test".to_string()),
1260            "Should find go-test tag, found: {:?}",
1261            tag_strings
1262        );
1263        assert!(
1264            tag_strings.contains(&"go-table-test-case".to_string()),
1265            "Should find go-table-test-case tag, found: {:?}",
1266            tag_strings
1267        );
1268
1269        let go_test_count = tag_strings.iter().filter(|&tag| tag == "go-test").count();
1270        // This is currently broken; see #39148
1271        // let go_table_test_count = tag_strings
1272        //     .iter()
1273        //     .filter(|&tag| tag == "go-table-test-case")
1274        //     .count();
1275
1276        assert!(
1277            go_test_count == 1,
1278            "Should find exactly 1 go-test, found: {}",
1279            go_test_count
1280        );
1281        // assert!(
1282        //     go_table_test_count == 3,
1283        //     "Should find exactly 3 go-table-test-case, found: {}",
1284        //     go_table_test_count
1285        // );
1286    }
1287
1288    #[gpui::test]
1289    fn test_go_table_test_slice_without_explicit_variable_detection(cx: &mut TestAppContext) {
1290        let language = language("go", tree_sitter_go::LANGUAGE.into());
1291
1292        let table_test = r#"
1293        package main
1294
1295        import "testing"
1296
1297        func TestExample(t *testing.T) {
1298            for _, tc := range []struct{
1299                name string
1300                anotherStr string
1301            }{
1302                {
1303                    name: "test case 1",
1304                    anotherStr: "foo",
1305                },
1306                {
1307                    name: "test case 2",
1308                    anotherStr: "bar",
1309                },
1310                {
1311                    name: "test case 3",
1312                    anotherStr: "baz",
1313                },
1314            } {
1315                t.Run(tc.name, func(t *testing.T) {
1316                    // test code here
1317                })
1318            }
1319        }
1320        "#;
1321
1322        let buffer =
1323            cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
1324        cx.executor().run_until_parked();
1325
1326        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1327            let snapshot = buffer.snapshot();
1328            snapshot.runnable_ranges(0..table_test.len()).collect()
1329        });
1330
1331        let tag_strings: Vec<String> = runnables
1332            .iter()
1333            .flat_map(|r| &r.runnable.tags)
1334            .map(|tag| tag.0.to_string())
1335            .collect();
1336
1337        assert!(
1338            tag_strings.contains(&"go-test".to_string()),
1339            "Should find go-test tag, found: {:?}",
1340            tag_strings
1341        );
1342        assert!(
1343            tag_strings.contains(&"go-table-test-case-without-explicit-variable".to_string()),
1344            "Should find go-table-test-case-without-explicit-variable tag, found: {:?}",
1345            tag_strings
1346        );
1347
1348        let go_test_count = tag_strings.iter().filter(|&tag| tag == "go-test").count();
1349
1350        assert!(
1351            go_test_count == 1,
1352            "Should find exactly 1 go-test, found: {}",
1353            go_test_count
1354        );
1355    }
1356
1357    #[gpui::test]
1358    fn test_go_table_test_map_without_explicit_variable_detection(cx: &mut TestAppContext) {
1359        let language = language("go", tree_sitter_go::LANGUAGE.into());
1360
1361        let table_test = r#"
1362        package main
1363
1364        import "testing"
1365
1366        func TestExample(t *testing.T) {
1367            for name, tc := range map[string]struct {
1368          		someStr string
1369          		fail    bool
1370           	}{
1371          		"test failure": {
1372         			someStr: "foo",
1373         			fail:    true,
1374          		},
1375          		"test success": {
1376         			someStr: "bar",
1377         			fail:    false,
1378          		},
1379           	} {
1380                t.Run(name, func(t *testing.T) {
1381                    // test code here
1382                })
1383            }
1384        }
1385        "#;
1386
1387        let buffer =
1388            cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
1389        cx.executor().run_until_parked();
1390
1391        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1392            let snapshot = buffer.snapshot();
1393            snapshot.runnable_ranges(0..table_test.len()).collect()
1394        });
1395
1396        let tag_strings: Vec<String> = runnables
1397            .iter()
1398            .flat_map(|r| &r.runnable.tags)
1399            .map(|tag| tag.0.to_string())
1400            .collect();
1401
1402        assert!(
1403            tag_strings.contains(&"go-test".to_string()),
1404            "Should find go-test tag, found: {:?}",
1405            tag_strings
1406        );
1407        assert!(
1408            tag_strings.contains(&"go-table-test-case-without-explicit-variable".to_string()),
1409            "Should find go-table-test-case-without-explicit-variable tag, found: {:?}",
1410            tag_strings
1411        );
1412
1413        let go_test_count = tag_strings.iter().filter(|&tag| tag == "go-test").count();
1414        let go_table_test_count = tag_strings
1415            .iter()
1416            .filter(|&tag| tag == "go-table-test-case-without-explicit-variable")
1417            .count();
1418
1419        assert!(
1420            go_test_count == 1,
1421            "Should find exactly 1 go-test, found: {}",
1422            go_test_count
1423        );
1424        assert!(
1425            go_table_test_count == 2,
1426            "Should find exactly 2 go-table-test-case-without-explicit-variable, found: {}",
1427            go_table_test_count
1428        );
1429    }
1430
1431    #[gpui::test]
1432    fn test_go_table_test_slice_ignored(cx: &mut TestAppContext) {
1433        let language = language("go", tree_sitter_go::LANGUAGE.into());
1434
1435        let table_test = r#"
1436        package main
1437
1438        func Example() {
1439            _ = "some random string"
1440
1441            notATableTest := []struct{
1442                name string
1443            }{
1444                {
1445                    name: "some string",
1446                },
1447                {
1448                    name: "some other string",
1449                },
1450            }
1451        }
1452        "#;
1453
1454        let buffer =
1455            cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
1456        cx.executor().run_until_parked();
1457
1458        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1459            let snapshot = buffer.snapshot();
1460            snapshot.runnable_ranges(0..table_test.len()).collect()
1461        });
1462
1463        let tag_strings: Vec<String> = runnables
1464            .iter()
1465            .flat_map(|r| &r.runnable.tags)
1466            .map(|tag| tag.0.to_string())
1467            .collect();
1468
1469        assert!(
1470            !tag_strings.contains(&"go-test".to_string()),
1471            "Should find go-test tag, found: {:?}",
1472            tag_strings
1473        );
1474        assert!(
1475            !tag_strings.contains(&"go-table-test-case".to_string()),
1476            "Should find go-table-test-case tag, found: {:?}",
1477            tag_strings
1478        );
1479    }
1480
1481    #[gpui::test]
1482    fn test_go_table_test_map_detection(cx: &mut TestAppContext) {
1483        let language = language("go", tree_sitter_go::LANGUAGE.into());
1484
1485        let table_test = r#"
1486        package main
1487
1488        import "testing"
1489
1490        func TestExample(t *testing.T) {
1491            _ = "some random string"
1492
1493           	testCases := map[string]struct {
1494          		someStr string
1495          		fail    bool
1496           	}{
1497          		"test failure": {
1498         			someStr: "foo",
1499         			fail:    true,
1500          		},
1501          		"test success": {
1502         			someStr: "bar",
1503         			fail:    false,
1504          		},
1505           	}
1506
1507           	notATableTest := map[string]struct {
1508          		someStr string
1509           	}{
1510          		"some string": {
1511         			someStr: "foo",
1512          		},
1513          		"some other string": {
1514         			someStr: "bar",
1515          		},
1516           	}
1517
1518            for name, tc := range testCases {
1519                t.Run(name, func(t *testing.T) {
1520                    // test code here
1521                })
1522            }
1523        }
1524        "#;
1525
1526        let buffer =
1527            cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
1528        cx.executor().run_until_parked();
1529
1530        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1531            let snapshot = buffer.snapshot();
1532            snapshot.runnable_ranges(0..table_test.len()).collect()
1533        });
1534
1535        let tag_strings: Vec<String> = runnables
1536            .iter()
1537            .flat_map(|r| &r.runnable.tags)
1538            .map(|tag| tag.0.to_string())
1539            .collect();
1540
1541        assert!(
1542            tag_strings.contains(&"go-test".to_string()),
1543            "Should find go-test tag, found: {:?}",
1544            tag_strings
1545        );
1546        assert!(
1547            tag_strings.contains(&"go-table-test-case".to_string()),
1548            "Should find go-table-test-case tag, found: {:?}",
1549            tag_strings
1550        );
1551
1552        let go_test_count = tag_strings.iter().filter(|&tag| tag == "go-test").count();
1553        let go_table_test_count = tag_strings
1554            .iter()
1555            .filter(|&tag| tag == "go-table-test-case")
1556            .count();
1557
1558        assert!(
1559            go_test_count == 1,
1560            "Should find exactly 1 go-test, found: {}",
1561            go_test_count
1562        );
1563        assert!(
1564            go_table_test_count == 2,
1565            "Should find exactly 2 go-table-test-case, found: {}",
1566            go_table_test_count
1567        );
1568    }
1569
1570    #[gpui::test]
1571    fn test_go_table_test_map_ignored(cx: &mut TestAppContext) {
1572        let language = language("go", tree_sitter_go::LANGUAGE.into());
1573
1574        let table_test = r#"
1575        package main
1576
1577        func Example() {
1578            _ = "some random string"
1579
1580           	notATableTest := map[string]struct {
1581          		someStr string
1582           	}{
1583          		"some string": {
1584         			someStr: "foo",
1585          		},
1586          		"some other string": {
1587         			someStr: "bar",
1588          		},
1589           	}
1590        }
1591        "#;
1592
1593        let buffer =
1594            cx.new(|cx| crate::Buffer::local(table_test, cx).with_language(language.clone(), cx));
1595        cx.executor().run_until_parked();
1596
1597        let runnables: Vec<_> = buffer.update(cx, |buffer, _| {
1598            let snapshot = buffer.snapshot();
1599            snapshot.runnable_ranges(0..table_test.len()).collect()
1600        });
1601
1602        let tag_strings: Vec<String> = runnables
1603            .iter()
1604            .flat_map(|r| &r.runnable.tags)
1605            .map(|tag| tag.0.to_string())
1606            .collect();
1607
1608        assert!(
1609            !tag_strings.contains(&"go-test".to_string()),
1610            "Should find go-test tag, found: {:?}",
1611            tag_strings
1612        );
1613        assert!(
1614            !tag_strings.contains(&"go-table-test-case".to_string()),
1615            "Should find go-table-test-case tag, found: {:?}",
1616            tag_strings
1617        );
1618    }
1619
1620    #[test]
1621    fn test_extract_subtest_name() {
1622        // Interpreted string literal
1623        let input_double_quoted = r#""subtest with double quotes""#;
1624        let result = extract_subtest_name(input_double_quoted);
1625        assert_eq!(result, Some(r#"subtest_with_double_quotes"#.to_string()));
1626
1627        let input_double_quoted_with_backticks = r#""test with `backticks` inside""#;
1628        let result = extract_subtest_name(input_double_quoted_with_backticks);
1629        assert_eq!(result, Some(r#"test_with_`backticks`_inside"#.to_string()));
1630
1631        // Raw string literal
1632        let input_with_backticks = r#"`subtest with backticks`"#;
1633        let result = extract_subtest_name(input_with_backticks);
1634        assert_eq!(result, Some(r#"subtest_with_backticks"#.to_string()));
1635
1636        let input_raw_with_quotes = r#"`test with "quotes" and other chars`"#;
1637        let result = extract_subtest_name(input_raw_with_quotes);
1638        assert_eq!(
1639            result,
1640            Some(r#"test_with_\"quotes\"_and_other_chars"#.to_string())
1641        );
1642
1643        let input_multiline = r#"`subtest with
1644        multiline
1645        backticks`"#;
1646        let result = extract_subtest_name(input_multiline);
1647        assert_eq!(
1648            result,
1649            Some(r#"subtest_with_________multiline_________backticks"#.to_string())
1650        );
1651
1652        let input_with_double_quotes = r#"`test with "double quotes"`"#;
1653        let result = extract_subtest_name(input_with_double_quotes);
1654        assert_eq!(result, Some(r#"test_with_\"double_quotes\""#.to_string()));
1655    }
1656}