rust.rs

   1use anyhow::{Context as _, Result};
   2use async_trait::async_trait;
   3use collections::HashMap;
   4use futures::StreamExt;
   5use gpui::{App, AppContext, AsyncApp, SharedString, Task};
   6use http_client::github::AssetKind;
   7use http_client::github::{GitHubLspBinaryVersion, latest_github_release};
   8use http_client::github_download::{GithubBinaryMetadata, download_server_binary};
   9pub use language::*;
  10use lsp::{InitializeParams, LanguageServerBinary};
  11use project::lsp_store::rust_analyzer_ext::CARGO_DIAGNOSTICS_SOURCE_NAME;
  12use project::project_settings::ProjectSettings;
  13use regex::Regex;
  14use serde_json::json;
  15use settings::Settings as _;
  16use smol::fs::{self};
  17use std::fmt::Display;
  18use std::ops::Range;
  19use std::{
  20    borrow::Cow,
  21    path::{Path, PathBuf},
  22    sync::{Arc, LazyLock},
  23};
  24use task::{TaskTemplate, TaskTemplates, TaskVariables, VariableName};
  25use util::fs::{make_file_executable, remove_matching};
  26use util::merge_json_value_into;
  27use util::rel_path::RelPath;
  28use util::{ResultExt, maybe};
  29
  30use crate::language_settings::language_settings;
  31
  32pub struct RustLspAdapter;
  33
  34#[cfg(target_os = "macos")]
  35impl RustLspAdapter {
  36    const GITHUB_ASSET_KIND: AssetKind = AssetKind::Gz;
  37    const ARCH_SERVER_NAME: &str = "apple-darwin";
  38}
  39
  40#[cfg(target_os = "linux")]
  41impl RustLspAdapter {
  42    const GITHUB_ASSET_KIND: AssetKind = AssetKind::Gz;
  43    const ARCH_SERVER_NAME: &str = "unknown-linux";
  44}
  45
  46#[cfg(target_os = "freebsd")]
  47impl RustLspAdapter {
  48    const GITHUB_ASSET_KIND: AssetKind = AssetKind::Gz;
  49    const ARCH_SERVER_NAME: &str = "unknown-freebsd";
  50}
  51
  52#[cfg(target_os = "windows")]
  53impl RustLspAdapter {
  54    const GITHUB_ASSET_KIND: AssetKind = AssetKind::Zip;
  55    const ARCH_SERVER_NAME: &str = "pc-windows-msvc";
  56}
  57
  58const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("rust-analyzer");
  59
  60impl RustLspAdapter {
  61    #[cfg(target_os = "linux")]
  62    fn build_arch_server_name_linux() -> String {
  63        enum LibcType {
  64            Gnu,
  65            Musl,
  66        }
  67
  68        let has_musl = std::fs::exists(&format!("/lib/ld-musl-{}.so.1", std::env::consts::ARCH))
  69            .unwrap_or(false);
  70        let has_gnu = std::fs::exists(&format!("/lib/ld-linux-{}.so.1", std::env::consts::ARCH))
  71            .unwrap_or(false);
  72
  73        let libc_type = match (has_musl, has_gnu) {
  74            (true, _) => LibcType::Musl,
  75            (_, true) => LibcType::Gnu,
  76            _ => {
  77                // defaulting to gnu because nix doesn't have either of those files due to not following FHS
  78                LibcType::Gnu
  79            }
  80        };
  81
  82        let libc = match libc_type {
  83            LibcType::Musl => "musl",
  84            LibcType::Gnu => "gnu",
  85        };
  86
  87        format!("{}-{}", Self::ARCH_SERVER_NAME, libc)
  88    }
  89
  90    fn build_asset_name() -> String {
  91        let extension = match Self::GITHUB_ASSET_KIND {
  92            AssetKind::TarGz => "tar.gz",
  93            AssetKind::Gz => "gz",
  94            AssetKind::Zip => "zip",
  95        };
  96
  97        #[cfg(target_os = "linux")]
  98        let arch_server_name = Self::build_arch_server_name_linux();
  99        #[cfg(not(target_os = "linux"))]
 100        let arch_server_name = Self::ARCH_SERVER_NAME.to_string();
 101
 102        format!(
 103            "{}-{}-{}.{}",
 104            SERVER_NAME,
 105            std::env::consts::ARCH,
 106            &arch_server_name,
 107            extension
 108        )
 109    }
 110}
 111
 112pub(crate) struct CargoManifestProvider;
 113
 114impl ManifestProvider for CargoManifestProvider {
 115    fn name(&self) -> ManifestName {
 116        SharedString::new_static("Cargo.toml").into()
 117    }
 118
 119    fn search(
 120        &self,
 121        ManifestQuery {
 122            path,
 123            depth,
 124            delegate,
 125        }: ManifestQuery,
 126    ) -> Option<Arc<RelPath>> {
 127        let mut outermost_cargo_toml = None;
 128        for path in path.ancestors().take(depth) {
 129            let p = path.join(RelPath::unix("Cargo.toml").unwrap());
 130            if delegate.exists(&p, Some(false)) {
 131                outermost_cargo_toml = Some(Arc::from(path));
 132            }
 133        }
 134
 135        outermost_cargo_toml
 136    }
 137}
 138
 139#[async_trait(?Send)]
 140impl LspAdapter for RustLspAdapter {
 141    fn name(&self) -> LanguageServerName {
 142        SERVER_NAME
 143    }
 144
 145    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
 146        vec![CARGO_DIAGNOSTICS_SOURCE_NAME.to_owned()]
 147    }
 148
 149    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
 150        Some("rust-analyzer/flycheck".into())
 151    }
 152
 153    fn process_diagnostics(
 154        &self,
 155        params: &mut lsp::PublishDiagnosticsParams,
 156        _: LanguageServerId,
 157        _: Option<&'_ Buffer>,
 158    ) {
 159        static REGEX: LazyLock<Regex> =
 160            LazyLock::new(|| Regex::new(r"(?m)`([^`]+)\n`$").expect("Failed to create REGEX"));
 161
 162        for diagnostic in &mut params.diagnostics {
 163            for message in diagnostic
 164                .related_information
 165                .iter_mut()
 166                .flatten()
 167                .map(|info| &mut info.message)
 168                .chain([&mut diagnostic.message])
 169            {
 170                if let Cow::Owned(sanitized) = REGEX.replace_all(message, "`$1`") {
 171                    *message = sanitized;
 172                }
 173            }
 174        }
 175    }
 176
 177    fn diagnostic_message_to_markdown(&self, message: &str) -> Option<String> {
 178        static REGEX: LazyLock<Regex> =
 179            LazyLock::new(|| Regex::new(r"(?m)\n *").expect("Failed to create REGEX"));
 180        Some(REGEX.replace_all(message, "\n\n").to_string())
 181    }
 182
 183    async fn label_for_completion(
 184        &self,
 185        completion: &lsp::CompletionItem,
 186        language: &Arc<Language>,
 187    ) -> Option<CodeLabel> {
 188        // rust-analyzer calls these detail left and detail right in terms of where it expects things to be rendered
 189        // this usually contains signatures of the thing to be completed
 190        let detail_right = completion
 191            .label_details
 192            .as_ref()
 193            .and_then(|detail| detail.description.as_ref())
 194            .or(completion.detail.as_ref())
 195            .map(|detail| detail.trim());
 196        // this tends to contain alias and import information
 197        let detail_left = completion
 198            .label_details
 199            .as_ref()
 200            .and_then(|detail| detail.detail.as_deref());
 201        let mk_label = |text: String, filter_range: &dyn Fn() -> Range<usize>, runs| {
 202            let filter_range = completion
 203                .filter_text
 204                .as_deref()
 205                .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
 206                .or_else(|| {
 207                    text.find(&completion.label)
 208                        .map(|ix| ix..ix + completion.label.len())
 209                })
 210                .unwrap_or_else(filter_range);
 211
 212            CodeLabel {
 213                text,
 214                runs,
 215                filter_range,
 216            }
 217        };
 218        let mut label = match (detail_right, completion.kind) {
 219            (Some(signature), Some(lsp::CompletionItemKind::FIELD)) => {
 220                let name = &completion.label;
 221                let text = format!("{name}: {signature}");
 222                let prefix = "struct S { ";
 223                let source = Rope::from_iter([prefix, &text, " }"]);
 224                let runs =
 225                    language.highlight_text(&source, prefix.len()..prefix.len() + text.len());
 226                mk_label(text, &|| 0..completion.label.len(), runs)
 227            }
 228            (
 229                Some(signature),
 230                Some(lsp::CompletionItemKind::CONSTANT | lsp::CompletionItemKind::VARIABLE),
 231            ) if completion.insert_text_format != Some(lsp::InsertTextFormat::SNIPPET) => {
 232                let name = &completion.label;
 233                let text = format!("{name}: {signature}",);
 234                let prefix = "let ";
 235                let source = Rope::from_iter([prefix, &text, " = ();"]);
 236                let runs =
 237                    language.highlight_text(&source, prefix.len()..prefix.len() + text.len());
 238                mk_label(text, &|| 0..completion.label.len(), runs)
 239            }
 240            (
 241                function_signature,
 242                Some(lsp::CompletionItemKind::FUNCTION | lsp::CompletionItemKind::METHOD),
 243            ) => {
 244                const FUNCTION_PREFIXES: [&str; 6] = [
 245                    "async fn",
 246                    "async unsafe fn",
 247                    "const fn",
 248                    "const unsafe fn",
 249                    "unsafe fn",
 250                    "fn",
 251                ];
 252                let fn_prefixed = FUNCTION_PREFIXES.iter().find_map(|&prefix| {
 253                    function_signature?
 254                        .strip_prefix(prefix)
 255                        .map(|suffix| (prefix, suffix))
 256                });
 257                let label = if let Some(label) = completion
 258                    .label
 259                    .strip_suffix("(…)")
 260                    .or_else(|| completion.label.strip_suffix("()"))
 261                {
 262                    label
 263                } else {
 264                    &completion.label
 265                };
 266
 267                static FULL_SIGNATURE_REGEX: LazyLock<Regex> =
 268                    LazyLock::new(|| Regex::new(r"fn (.?+)\(").expect("Failed to create REGEX"));
 269                if let Some((function_signature, match_)) = function_signature
 270                    .filter(|it| it.contains(&label))
 271                    .and_then(|it| Some((it, FULL_SIGNATURE_REGEX.find(it)?)))
 272                {
 273                    let source = Rope::from(function_signature);
 274                    let runs = language.highlight_text(&source, 0..function_signature.len());
 275                    mk_label(
 276                        function_signature.to_owned(),
 277                        &|| match_.range().start - 3..match_.range().end - 1,
 278                        runs,
 279                    )
 280                } else if let Some((prefix, suffix)) = fn_prefixed {
 281                    let text = format!("{label}{suffix}");
 282                    let source = Rope::from_iter([prefix, " ", &text, " {}"]);
 283                    let run_start = prefix.len() + 1;
 284                    let runs = language.highlight_text(&source, run_start..run_start + text.len());
 285                    mk_label(text, &|| 0..label.len(), runs)
 286                } else if completion
 287                    .detail
 288                    .as_ref()
 289                    .is_some_and(|detail| detail.starts_with("macro_rules! "))
 290                {
 291                    let text = completion.label.clone();
 292                    let len = text.len();
 293                    let source = Rope::from(text.as_str());
 294                    let runs = language.highlight_text(&source, 0..len);
 295                    mk_label(text, &|| 0..completion.label.len(), runs)
 296                } else if detail_left.is_none() {
 297                    return None;
 298                } else {
 299                    mk_label(
 300                        completion.label.clone(),
 301                        &|| 0..completion.label.len(),
 302                        vec![],
 303                    )
 304                }
 305            }
 306            (_, kind) => {
 307                let highlight_name = kind.and_then(|kind| match kind {
 308                    lsp::CompletionItemKind::STRUCT
 309                    | lsp::CompletionItemKind::INTERFACE
 310                    | lsp::CompletionItemKind::ENUM => Some("type"),
 311                    lsp::CompletionItemKind::ENUM_MEMBER => Some("variant"),
 312                    lsp::CompletionItemKind::KEYWORD => Some("keyword"),
 313                    lsp::CompletionItemKind::VALUE | lsp::CompletionItemKind::CONSTANT => {
 314                        Some("constant")
 315                    }
 316                    _ => None,
 317                });
 318
 319                let label = completion.label.clone();
 320                let mut runs = vec![];
 321                if let Some(highlight_name) = highlight_name {
 322                    let highlight_id = language.grammar()?.highlight_id_for_name(highlight_name)?;
 323                    runs.push((
 324                        0..label.rfind('(').unwrap_or(completion.label.len()),
 325                        highlight_id,
 326                    ));
 327                } else if detail_left.is_none() {
 328                    return None;
 329                }
 330
 331                mk_label(label, &|| 0..completion.label.len(), runs)
 332            }
 333        };
 334
 335        if let Some(detail_left) = detail_left {
 336            label.text.push(' ');
 337            if !detail_left.starts_with('(') {
 338                label.text.push('(');
 339            }
 340            label.text.push_str(detail_left);
 341            if !detail_left.ends_with(')') {
 342                label.text.push(')');
 343            }
 344        }
 345        Some(label)
 346    }
 347
 348    async fn label_for_symbol(
 349        &self,
 350        name: &str,
 351        kind: lsp::SymbolKind,
 352        language: &Arc<Language>,
 353    ) -> Option<CodeLabel> {
 354        let (prefix, suffix) = match kind {
 355            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => ("fn ", " () {}"),
 356            lsp::SymbolKind::STRUCT => ("struct ", " {}"),
 357            lsp::SymbolKind::ENUM => ("enum ", " {}"),
 358            lsp::SymbolKind::INTERFACE => ("trait ", " {}"),
 359            lsp::SymbolKind::CONSTANT => ("const ", ": () = ();"),
 360            lsp::SymbolKind::MODULE => ("mod ", " {}"),
 361            lsp::SymbolKind::TYPE_PARAMETER => ("type ", " {}"),
 362            _ => return None,
 363        };
 364
 365        let filter_range = prefix.len()..prefix.len() + name.len();
 366        let display_range = 0..filter_range.end;
 367        Some(CodeLabel {
 368            runs: language.highlight_text(&Rope::from_iter([prefix, name, suffix]), display_range),
 369            text: format!("{prefix}{name}"),
 370            filter_range,
 371        })
 372    }
 373
 374    fn prepare_initialize_params(
 375        &self,
 376        mut original: InitializeParams,
 377        cx: &App,
 378    ) -> Result<InitializeParams> {
 379        let enable_lsp_tasks = ProjectSettings::get_global(cx)
 380            .lsp
 381            .get(&SERVER_NAME)
 382            .is_some_and(|s| s.enable_lsp_tasks);
 383        if enable_lsp_tasks {
 384            let experimental = json!({
 385                "runnables": {
 386                    "kinds": [ "cargo", "shell" ],
 387                },
 388            });
 389            if let Some(original_experimental) = &mut original.capabilities.experimental {
 390                merge_json_value_into(experimental, original_experimental);
 391            } else {
 392                original.capabilities.experimental = Some(experimental);
 393            }
 394        }
 395
 396        Ok(original)
 397    }
 398}
 399
 400impl LspInstaller for RustLspAdapter {
 401    type BinaryVersion = GitHubLspBinaryVersion;
 402    async fn check_if_user_installed(
 403        &self,
 404        delegate: &dyn LspAdapterDelegate,
 405        _: Option<Toolchain>,
 406        _: &AsyncApp,
 407    ) -> Option<LanguageServerBinary> {
 408        let path = delegate.which("rust-analyzer".as_ref()).await?;
 409        let env = delegate.shell_env().await;
 410
 411        // It is surprisingly common for ~/.cargo/bin/rust-analyzer to be a symlink to
 412        // /usr/bin/rust-analyzer that fails when you run it; so we need to test it.
 413        log::info!("found rust-analyzer in PATH. trying to run `rust-analyzer --help`");
 414        let result = delegate
 415            .try_exec(LanguageServerBinary {
 416                path: path.clone(),
 417                arguments: vec!["--help".into()],
 418                env: Some(env.clone()),
 419            })
 420            .await;
 421        if let Err(err) = result {
 422            log::debug!(
 423                "failed to run rust-analyzer after detecting it in PATH: binary: {:?}: {}",
 424                path,
 425                err
 426            );
 427            return None;
 428        }
 429
 430        Some(LanguageServerBinary {
 431            path,
 432            env: Some(env),
 433            arguments: vec![],
 434        })
 435    }
 436
 437    async fn fetch_latest_server_version(
 438        &self,
 439        delegate: &dyn LspAdapterDelegate,
 440        pre_release: bool,
 441        _: &mut AsyncApp,
 442    ) -> Result<GitHubLspBinaryVersion> {
 443        let release = latest_github_release(
 444            "rust-lang/rust-analyzer",
 445            true,
 446            pre_release,
 447            delegate.http_client(),
 448        )
 449        .await?;
 450        let asset_name = Self::build_asset_name();
 451        let asset = release
 452            .assets
 453            .into_iter()
 454            .find(|asset| asset.name == asset_name)
 455            .with_context(|| format!("no asset found matching `{asset_name:?}`"))?;
 456        Ok(GitHubLspBinaryVersion {
 457            name: release.tag_name,
 458            url: asset.browser_download_url,
 459            digest: asset.digest,
 460        })
 461    }
 462
 463    async fn fetch_server_binary(
 464        &self,
 465        version: GitHubLspBinaryVersion,
 466        container_dir: PathBuf,
 467        delegate: &dyn LspAdapterDelegate,
 468    ) -> Result<LanguageServerBinary> {
 469        let GitHubLspBinaryVersion {
 470            name,
 471            url,
 472            digest: expected_digest,
 473        } = version;
 474        let destination_path = container_dir.join(format!("rust-analyzer-{name}"));
 475        let server_path = match Self::GITHUB_ASSET_KIND {
 476            AssetKind::TarGz | AssetKind::Gz => destination_path.clone(), // Tar and gzip extract in place.
 477            AssetKind::Zip => destination_path.clone().join("rust-analyzer.exe"), // zip contains a .exe
 478        };
 479
 480        let binary = LanguageServerBinary {
 481            path: server_path.clone(),
 482            env: None,
 483            arguments: Default::default(),
 484        };
 485
 486        let metadata_path = destination_path.with_extension("metadata");
 487        let metadata = GithubBinaryMetadata::read_from_file(&metadata_path)
 488            .await
 489            .ok();
 490        if let Some(metadata) = metadata {
 491            let validity_check = async || {
 492                delegate
 493                    .try_exec(LanguageServerBinary {
 494                        path: server_path.clone(),
 495                        arguments: vec!["--version".into()],
 496                        env: None,
 497                    })
 498                    .await
 499                    .inspect_err(|err| {
 500                        log::warn!("Unable to run {server_path:?} asset, redownloading: {err}",)
 501                    })
 502            };
 503            if let (Some(actual_digest), Some(expected_digest)) =
 504                (&metadata.digest, &expected_digest)
 505            {
 506                if actual_digest == expected_digest {
 507                    if validity_check().await.is_ok() {
 508                        return Ok(binary);
 509                    }
 510                } else {
 511                    log::info!(
 512                        "SHA-256 mismatch for {destination_path:?} asset, downloading new asset. Expected: {expected_digest}, Got: {actual_digest}"
 513                    );
 514                }
 515            } else if validity_check().await.is_ok() {
 516                return Ok(binary);
 517            }
 518        }
 519
 520        download_server_binary(
 521            &*delegate.http_client(),
 522            &url,
 523            expected_digest.as_deref(),
 524            &destination_path,
 525            Self::GITHUB_ASSET_KIND,
 526        )
 527        .await?;
 528        make_file_executable(&server_path).await?;
 529        remove_matching(&container_dir, |path| path != destination_path).await;
 530        GithubBinaryMetadata::write_to_file(
 531            &GithubBinaryMetadata {
 532                metadata_version: 1,
 533                digest: expected_digest,
 534            },
 535            &metadata_path,
 536        )
 537        .await?;
 538
 539        Ok(LanguageServerBinary {
 540            path: server_path,
 541            env: None,
 542            arguments: Default::default(),
 543        })
 544    }
 545
 546    async fn cached_server_binary(
 547        &self,
 548        container_dir: PathBuf,
 549        _: &dyn LspAdapterDelegate,
 550    ) -> Option<LanguageServerBinary> {
 551        get_cached_server_binary(container_dir).await
 552    }
 553}
 554
 555pub(crate) struct RustContextProvider;
 556
 557const RUST_PACKAGE_TASK_VARIABLE: VariableName =
 558    VariableName::Custom(Cow::Borrowed("RUST_PACKAGE"));
 559
 560/// The bin name corresponding to the current file in Cargo.toml
 561const RUST_BIN_NAME_TASK_VARIABLE: VariableName =
 562    VariableName::Custom(Cow::Borrowed("RUST_BIN_NAME"));
 563
 564/// The bin kind (bin/example) corresponding to the current file in Cargo.toml
 565const RUST_BIN_KIND_TASK_VARIABLE: VariableName =
 566    VariableName::Custom(Cow::Borrowed("RUST_BIN_KIND"));
 567
 568/// The flag to list required features for executing a bin, if any
 569const RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE: VariableName =
 570    VariableName::Custom(Cow::Borrowed("RUST_BIN_REQUIRED_FEATURES_FLAG"));
 571
 572/// The list of required features for executing a bin, if any
 573const RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE: VariableName =
 574    VariableName::Custom(Cow::Borrowed("RUST_BIN_REQUIRED_FEATURES"));
 575
 576const RUST_TEST_FRAGMENT_TASK_VARIABLE: VariableName =
 577    VariableName::Custom(Cow::Borrowed("RUST_TEST_FRAGMENT"));
 578
 579const RUST_DOC_TEST_NAME_TASK_VARIABLE: VariableName =
 580    VariableName::Custom(Cow::Borrowed("RUST_DOC_TEST_NAME"));
 581
 582const RUST_TEST_NAME_TASK_VARIABLE: VariableName =
 583    VariableName::Custom(Cow::Borrowed("RUST_TEST_NAME"));
 584
 585const RUST_MANIFEST_DIRNAME_TASK_VARIABLE: VariableName =
 586    VariableName::Custom(Cow::Borrowed("RUST_MANIFEST_DIRNAME"));
 587
 588impl ContextProvider for RustContextProvider {
 589    fn build_context(
 590        &self,
 591        task_variables: &TaskVariables,
 592        location: ContextLocation<'_>,
 593        project_env: Option<HashMap<String, String>>,
 594        _: Arc<dyn LanguageToolchainStore>,
 595        cx: &mut gpui::App,
 596    ) -> Task<Result<TaskVariables>> {
 597        let local_abs_path = location
 598            .file_location
 599            .buffer
 600            .read(cx)
 601            .file()
 602            .and_then(|file| Some(file.as_local()?.abs_path(cx)));
 603
 604        let mut variables = TaskVariables::default();
 605
 606        if let (Some(path), Some(stem)) = (&local_abs_path, task_variables.get(&VariableName::Stem))
 607        {
 608            let fragment = test_fragment(&variables, path, stem);
 609            variables.insert(RUST_TEST_FRAGMENT_TASK_VARIABLE, fragment);
 610        };
 611        if let Some(test_name) =
 612            task_variables.get(&VariableName::Custom(Cow::Borrowed("_test_name")))
 613        {
 614            variables.insert(RUST_TEST_NAME_TASK_VARIABLE, test_name.into());
 615        }
 616        if let Some(doc_test_name) =
 617            task_variables.get(&VariableName::Custom(Cow::Borrowed("_doc_test_name")))
 618        {
 619            variables.insert(RUST_DOC_TEST_NAME_TASK_VARIABLE, doc_test_name.into());
 620        }
 621        cx.background_spawn(async move {
 622            if let Some(path) = local_abs_path
 623                .as_deref()
 624                .and_then(|local_abs_path| local_abs_path.parent())
 625                && let Some(package_name) =
 626                    human_readable_package_name(path, project_env.as_ref()).await
 627            {
 628                variables.insert(RUST_PACKAGE_TASK_VARIABLE.clone(), package_name);
 629            }
 630            if let Some(path) = local_abs_path.as_ref()
 631                && let Some((target, manifest_path)) =
 632                    target_info_from_abs_path(path, project_env.as_ref()).await
 633            {
 634                if let Some(target) = target {
 635                    variables.extend(TaskVariables::from_iter([
 636                        (RUST_PACKAGE_TASK_VARIABLE.clone(), target.package_name),
 637                        (RUST_BIN_NAME_TASK_VARIABLE.clone(), target.target_name),
 638                        (
 639                            RUST_BIN_KIND_TASK_VARIABLE.clone(),
 640                            target.target_kind.to_string(),
 641                        ),
 642                    ]));
 643                    if target.required_features.is_empty() {
 644                        variables.insert(RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE, "".into());
 645                        variables.insert(RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE, "".into());
 646                    } else {
 647                        variables.insert(
 648                            RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE.clone(),
 649                            "--features".to_string(),
 650                        );
 651                        variables.insert(
 652                            RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE.clone(),
 653                            target.required_features.join(","),
 654                        );
 655                    }
 656                }
 657                variables.extend(TaskVariables::from_iter([(
 658                    RUST_MANIFEST_DIRNAME_TASK_VARIABLE.clone(),
 659                    manifest_path.to_string_lossy().into_owned(),
 660                )]));
 661            }
 662            Ok(variables)
 663        })
 664    }
 665
 666    fn associated_tasks(
 667        &self,
 668        file: Option<Arc<dyn language::File>>,
 669        cx: &App,
 670    ) -> Task<Option<TaskTemplates>> {
 671        const DEFAULT_RUN_NAME_STR: &str = "RUST_DEFAULT_PACKAGE_RUN";
 672        const CUSTOM_TARGET_DIR: &str = "RUST_TARGET_DIR";
 673
 674        let language_sets = language_settings(Some("Rust".into()), file.as_ref(), cx);
 675        let package_to_run = language_sets
 676            .tasks
 677            .variables
 678            .get(DEFAULT_RUN_NAME_STR)
 679            .cloned();
 680        let custom_target_dir = language_sets
 681            .tasks
 682            .variables
 683            .get(CUSTOM_TARGET_DIR)
 684            .cloned();
 685        let run_task_args = if let Some(package_to_run) = package_to_run {
 686            vec!["run".into(), "-p".into(), package_to_run]
 687        } else {
 688            vec!["run".into()]
 689        };
 690        let mut task_templates = vec![
 691            TaskTemplate {
 692                label: format!(
 693                    "Check (package: {})",
 694                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 695                ),
 696                command: "cargo".into(),
 697                args: vec![
 698                    "check".into(),
 699                    "-p".into(),
 700                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 701                ],
 702                cwd: Some("$ZED_DIRNAME".to_owned()),
 703                ..TaskTemplate::default()
 704            },
 705            TaskTemplate {
 706                label: "Check all targets (workspace)".into(),
 707                command: "cargo".into(),
 708                args: vec!["check".into(), "--workspace".into(), "--all-targets".into()],
 709                cwd: Some("$ZED_DIRNAME".to_owned()),
 710                ..TaskTemplate::default()
 711            },
 712            TaskTemplate {
 713                label: format!(
 714                    "Test '{}' (package: {})",
 715                    RUST_TEST_NAME_TASK_VARIABLE.template_value(),
 716                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 717                ),
 718                command: "cargo".into(),
 719                args: vec![
 720                    "test".into(),
 721                    "-p".into(),
 722                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 723                    "--".into(),
 724                    "--nocapture".into(),
 725                    "--include-ignored".into(),
 726                    RUST_TEST_NAME_TASK_VARIABLE.template_value(),
 727                ],
 728                tags: vec!["rust-test".to_owned()],
 729                cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
 730                ..TaskTemplate::default()
 731            },
 732            TaskTemplate {
 733                label: format!(
 734                    "Doc test '{}' (package: {})",
 735                    RUST_DOC_TEST_NAME_TASK_VARIABLE.template_value(),
 736                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 737                ),
 738                command: "cargo".into(),
 739                args: vec![
 740                    "test".into(),
 741                    "--doc".into(),
 742                    "-p".into(),
 743                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 744                    "--".into(),
 745                    "--nocapture".into(),
 746                    "--include-ignored".into(),
 747                    RUST_DOC_TEST_NAME_TASK_VARIABLE.template_value(),
 748                ],
 749                tags: vec!["rust-doc-test".to_owned()],
 750                cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
 751                ..TaskTemplate::default()
 752            },
 753            TaskTemplate {
 754                label: format!(
 755                    "Test mod '{}' (package: {})",
 756                    VariableName::Stem.template_value(),
 757                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 758                ),
 759                command: "cargo".into(),
 760                args: vec![
 761                    "test".into(),
 762                    "-p".into(),
 763                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 764                    "--".into(),
 765                    RUST_TEST_FRAGMENT_TASK_VARIABLE.template_value(),
 766                ],
 767                tags: vec!["rust-mod-test".to_owned()],
 768                cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
 769                ..TaskTemplate::default()
 770            },
 771            TaskTemplate {
 772                label: format!(
 773                    "Run {} {} (package: {})",
 774                    RUST_BIN_KIND_TASK_VARIABLE.template_value(),
 775                    RUST_BIN_NAME_TASK_VARIABLE.template_value(),
 776                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 777                ),
 778                command: "cargo".into(),
 779                args: vec![
 780                    "run".into(),
 781                    "-p".into(),
 782                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 783                    format!("--{}", RUST_BIN_KIND_TASK_VARIABLE.template_value()),
 784                    RUST_BIN_NAME_TASK_VARIABLE.template_value(),
 785                    RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE.template_value(),
 786                    RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE.template_value(),
 787                ],
 788                cwd: Some("$ZED_DIRNAME".to_owned()),
 789                tags: vec!["rust-main".to_owned()],
 790                ..TaskTemplate::default()
 791            },
 792            TaskTemplate {
 793                label: format!(
 794                    "Test (package: {})",
 795                    RUST_PACKAGE_TASK_VARIABLE.template_value()
 796                ),
 797                command: "cargo".into(),
 798                args: vec![
 799                    "test".into(),
 800                    "-p".into(),
 801                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 802                ],
 803                cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
 804                ..TaskTemplate::default()
 805            },
 806            TaskTemplate {
 807                label: "Run".into(),
 808                command: "cargo".into(),
 809                args: run_task_args,
 810                cwd: Some("$ZED_DIRNAME".to_owned()),
 811                ..TaskTemplate::default()
 812            },
 813            TaskTemplate {
 814                label: "Clean".into(),
 815                command: "cargo".into(),
 816                args: vec!["clean".into()],
 817                cwd: Some("$ZED_DIRNAME".to_owned()),
 818                ..TaskTemplate::default()
 819            },
 820        ];
 821
 822        if let Some(custom_target_dir) = custom_target_dir {
 823            task_templates = task_templates
 824                .into_iter()
 825                .map(|mut task_template| {
 826                    let mut args = task_template.args.split_off(1);
 827                    task_template.args.append(&mut vec![
 828                        "--target-dir".to_string(),
 829                        custom_target_dir.clone(),
 830                    ]);
 831                    task_template.args.append(&mut args);
 832
 833                    task_template
 834                })
 835                .collect();
 836        }
 837
 838        Task::ready(Some(TaskTemplates(task_templates)))
 839    }
 840
 841    fn lsp_task_source(&self) -> Option<LanguageServerName> {
 842        Some(SERVER_NAME)
 843    }
 844}
 845
 846/// Part of the data structure of Cargo metadata
 847#[derive(Debug, serde::Deserialize)]
 848struct CargoMetadata {
 849    packages: Vec<CargoPackage>,
 850}
 851
 852#[derive(Debug, serde::Deserialize)]
 853struct CargoPackage {
 854    id: String,
 855    targets: Vec<CargoTarget>,
 856    manifest_path: Arc<Path>,
 857}
 858
 859#[derive(Debug, serde::Deserialize)]
 860struct CargoTarget {
 861    name: String,
 862    kind: Vec<String>,
 863    src_path: String,
 864    #[serde(rename = "required-features", default)]
 865    required_features: Vec<String>,
 866}
 867
 868#[derive(Debug, PartialEq)]
 869enum TargetKind {
 870    Bin,
 871    Example,
 872}
 873
 874impl Display for TargetKind {
 875    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 876        match self {
 877            TargetKind::Bin => write!(f, "bin"),
 878            TargetKind::Example => write!(f, "example"),
 879        }
 880    }
 881}
 882
 883impl TryFrom<&str> for TargetKind {
 884    type Error = ();
 885    fn try_from(value: &str) -> Result<Self, ()> {
 886        match value {
 887            "bin" => Ok(Self::Bin),
 888            "example" => Ok(Self::Example),
 889            _ => Err(()),
 890        }
 891    }
 892}
 893/// Which package and binary target are we in?
 894#[derive(Debug, PartialEq)]
 895struct TargetInfo {
 896    package_name: String,
 897    target_name: String,
 898    target_kind: TargetKind,
 899    required_features: Vec<String>,
 900}
 901
 902async fn target_info_from_abs_path(
 903    abs_path: &Path,
 904    project_env: Option<&HashMap<String, String>>,
 905) -> Option<(Option<TargetInfo>, Arc<Path>)> {
 906    let mut command = util::command::new_smol_command("cargo");
 907    if let Some(envs) = project_env {
 908        command.envs(envs);
 909    }
 910    let output = command
 911        .current_dir(abs_path.parent()?)
 912        .arg("metadata")
 913        .arg("--no-deps")
 914        .arg("--format-version")
 915        .arg("1")
 916        .output()
 917        .await
 918        .log_err()?
 919        .stdout;
 920
 921    let metadata: CargoMetadata = serde_json::from_slice(&output).log_err()?;
 922    target_info_from_metadata(metadata, abs_path)
 923}
 924
 925fn target_info_from_metadata(
 926    metadata: CargoMetadata,
 927    abs_path: &Path,
 928) -> Option<(Option<TargetInfo>, Arc<Path>)> {
 929    let mut manifest_path = None;
 930    for package in metadata.packages {
 931        let Some(manifest_dir_path) = package.manifest_path.parent() else {
 932            continue;
 933        };
 934
 935        let Some(path_from_manifest_dir) = abs_path.strip_prefix(manifest_dir_path).ok() else {
 936            continue;
 937        };
 938        let candidate_path_length = path_from_manifest_dir.components().count();
 939        // Pick the most specific manifest path
 940        if let Some((path, current_length)) = &mut manifest_path {
 941            if candidate_path_length > *current_length {
 942                *path = Arc::from(manifest_dir_path);
 943                *current_length = candidate_path_length;
 944            }
 945        } else {
 946            manifest_path = Some((Arc::from(manifest_dir_path), candidate_path_length));
 947        };
 948
 949        for target in package.targets {
 950            let Some(bin_kind) = target
 951                .kind
 952                .iter()
 953                .find_map(|kind| TargetKind::try_from(kind.as_ref()).ok())
 954            else {
 955                continue;
 956            };
 957            let target_path = PathBuf::from(target.src_path);
 958            if target_path == abs_path {
 959                return manifest_path.map(|(path, _)| {
 960                    (
 961                        package_name_from_pkgid(&package.id).map(|package_name| TargetInfo {
 962                            package_name: package_name.to_owned(),
 963                            target_name: target.name,
 964                            required_features: target.required_features,
 965                            target_kind: bin_kind,
 966                        }),
 967                        path,
 968                    )
 969                });
 970            }
 971        }
 972    }
 973
 974    manifest_path.map(|(path, _)| (None, path))
 975}
 976
 977async fn human_readable_package_name(
 978    package_directory: &Path,
 979    project_env: Option<&HashMap<String, String>>,
 980) -> Option<String> {
 981    let mut command = util::command::new_smol_command("cargo");
 982    if let Some(envs) = project_env {
 983        command.envs(envs);
 984    }
 985    let pkgid = String::from_utf8(
 986        command
 987            .current_dir(package_directory)
 988            .arg("pkgid")
 989            .output()
 990            .await
 991            .log_err()?
 992            .stdout,
 993    )
 994    .ok()?;
 995    Some(package_name_from_pkgid(&pkgid)?.to_owned())
 996}
 997
 998// For providing local `cargo check -p $pkgid` task, we do not need most of the information we have returned.
 999// Output example in the root of Zed project:
1000// ```sh
1001// ❯ cargo pkgid zed
1002// path+file:///absolute/path/to/project/zed/crates/zed#0.131.0
1003// ```
1004// Another variant, if a project has a custom package name or hyphen in the name:
1005// ```
1006// path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0
1007// ```
1008//
1009// Extracts the package name from the output according to the spec:
1010// https://doc.rust-lang.org/cargo/reference/pkgid-spec.html#specification-grammar
1011fn package_name_from_pkgid(pkgid: &str) -> Option<&str> {
1012    fn split_off_suffix(input: &str, suffix_start: char) -> &str {
1013        match input.rsplit_once(suffix_start) {
1014            Some((without_suffix, _)) => without_suffix,
1015            None => input,
1016        }
1017    }
1018
1019    let (version_prefix, version_suffix) = pkgid.trim().rsplit_once('#')?;
1020    let package_name = match version_suffix.rsplit_once('@') {
1021        Some((custom_package_name, _version)) => custom_package_name,
1022        None => {
1023            let host_and_path = split_off_suffix(version_prefix, '?');
1024            let (_, package_name) = host_and_path.rsplit_once('/')?;
1025            package_name
1026        }
1027    };
1028    Some(package_name)
1029}
1030
1031async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
1032    maybe!(async {
1033        let mut last = None;
1034        let mut entries = fs::read_dir(&container_dir).await?;
1035        while let Some(entry) = entries.next().await {
1036            let path = entry?.path();
1037            if path.extension().is_some_and(|ext| ext == "metadata") {
1038                continue;
1039            }
1040            last = Some(path);
1041        }
1042
1043        let path = last.context("no cached binary")?;
1044        let path = match RustLspAdapter::GITHUB_ASSET_KIND {
1045            AssetKind::TarGz | AssetKind::Gz => path, // Tar and gzip extract in place.
1046            AssetKind::Zip => path.join("rust-analyzer.exe"), // zip contains a .exe
1047        };
1048
1049        anyhow::Ok(LanguageServerBinary {
1050            path,
1051            env: None,
1052            arguments: Default::default(),
1053        })
1054    })
1055    .await
1056    .log_err()
1057}
1058
1059fn test_fragment(variables: &TaskVariables, path: &Path, stem: &str) -> String {
1060    let fragment = if stem == "lib" {
1061        // This isn't quite right---it runs the tests for the entire library, rather than
1062        // just for the top-level `mod tests`. But we don't really have the means here to
1063        // filter out just that module.
1064        Some("--lib".to_owned())
1065    } else if stem == "mod" {
1066        maybe!({ Some(path.parent()?.file_name()?.to_string_lossy().into_owned()) })
1067    } else if stem == "main" {
1068        if let (Some(bin_name), Some(bin_kind)) = (
1069            variables.get(&RUST_BIN_NAME_TASK_VARIABLE),
1070            variables.get(&RUST_BIN_KIND_TASK_VARIABLE),
1071        ) {
1072            Some(format!("--{bin_kind}={bin_name}"))
1073        } else {
1074            None
1075        }
1076    } else {
1077        Some(stem.to_owned())
1078    };
1079    fragment.unwrap_or_else(|| "--".to_owned())
1080}
1081
1082#[cfg(test)]
1083mod tests {
1084    use std::num::NonZeroU32;
1085
1086    use super::*;
1087    use crate::language;
1088    use gpui::{BorrowAppContext, Hsla, TestAppContext};
1089    use lsp::CompletionItemLabelDetails;
1090    use settings::SettingsStore;
1091    use theme::SyntaxTheme;
1092    use util::path;
1093
1094    #[gpui::test]
1095    async fn test_process_rust_diagnostics() {
1096        let mut params = lsp::PublishDiagnosticsParams {
1097            uri: lsp::Uri::from_file_path(path!("/a")).unwrap(),
1098            version: None,
1099            diagnostics: vec![
1100                // no newlines
1101                lsp::Diagnostic {
1102                    message: "use of moved value `a`".to_string(),
1103                    ..Default::default()
1104                },
1105                // newline at the end of a code span
1106                lsp::Diagnostic {
1107                    message: "consider importing this struct: `use b::c;\n`".to_string(),
1108                    ..Default::default()
1109                },
1110                // code span starting right after a newline
1111                lsp::Diagnostic {
1112                    message: "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
1113                        .to_string(),
1114                    ..Default::default()
1115                },
1116            ],
1117        };
1118        RustLspAdapter.process_diagnostics(&mut params, LanguageServerId(0), None);
1119
1120        assert_eq!(params.diagnostics[0].message, "use of moved value `a`");
1121
1122        // remove trailing newline from code span
1123        assert_eq!(
1124            params.diagnostics[1].message,
1125            "consider importing this struct: `use b::c;`"
1126        );
1127
1128        // do not remove newline before the start of code span
1129        assert_eq!(
1130            params.diagnostics[2].message,
1131            "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
1132        );
1133    }
1134
1135    #[gpui::test]
1136    async fn test_rust_label_for_completion() {
1137        let adapter = Arc::new(RustLspAdapter);
1138        let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1139        let grammar = language.grammar().unwrap();
1140        let theme = SyntaxTheme::new_test([
1141            ("type", Hsla::default()),
1142            ("keyword", Hsla::default()),
1143            ("function", Hsla::default()),
1144            ("property", Hsla::default()),
1145        ]);
1146
1147        language.set_theme(&theme);
1148
1149        let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1150        let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1151        let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1152        let highlight_field = grammar.highlight_id_for_name("property").unwrap();
1153
1154        assert_eq!(
1155            adapter
1156                .label_for_completion(
1157                    &lsp::CompletionItem {
1158                        kind: Some(lsp::CompletionItemKind::FUNCTION),
1159                        label: "hello(…)".to_string(),
1160                        label_details: Some(CompletionItemLabelDetails {
1161                            detail: Some("(use crate::foo)".into()),
1162                            description: Some("fn(&mut Option<T>) -> Vec<T>".to_string())
1163                        }),
1164                        ..Default::default()
1165                    },
1166                    &language
1167                )
1168                .await,
1169            Some(CodeLabel {
1170                text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1171                filter_range: 0..5,
1172                runs: vec![
1173                    (0..5, highlight_function),
1174                    (7..10, highlight_keyword),
1175                    (11..17, highlight_type),
1176                    (18..19, highlight_type),
1177                    (25..28, highlight_type),
1178                    (29..30, highlight_type),
1179                ],
1180            })
1181        );
1182        assert_eq!(
1183            adapter
1184                .label_for_completion(
1185                    &lsp::CompletionItem {
1186                        kind: Some(lsp::CompletionItemKind::FUNCTION),
1187                        label: "hello(…)".to_string(),
1188                        label_details: Some(CompletionItemLabelDetails {
1189                            detail: Some("(use crate::foo)".into()),
1190                            description: Some("async fn(&mut Option<T>) -> Vec<T>".to_string()),
1191                        }),
1192                        ..Default::default()
1193                    },
1194                    &language
1195                )
1196                .await,
1197            Some(CodeLabel {
1198                text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1199                filter_range: 0..5,
1200                runs: vec![
1201                    (0..5, highlight_function),
1202                    (7..10, highlight_keyword),
1203                    (11..17, highlight_type),
1204                    (18..19, highlight_type),
1205                    (25..28, highlight_type),
1206                    (29..30, highlight_type),
1207                ],
1208            })
1209        );
1210        assert_eq!(
1211            adapter
1212                .label_for_completion(
1213                    &lsp::CompletionItem {
1214                        kind: Some(lsp::CompletionItemKind::FIELD),
1215                        label: "len".to_string(),
1216                        detail: Some("usize".to_string()),
1217                        ..Default::default()
1218                    },
1219                    &language
1220                )
1221                .await,
1222            Some(CodeLabel {
1223                text: "len: usize".to_string(),
1224                filter_range: 0..3,
1225                runs: vec![(0..3, highlight_field), (5..10, highlight_type),],
1226            })
1227        );
1228
1229        assert_eq!(
1230            adapter
1231                .label_for_completion(
1232                    &lsp::CompletionItem {
1233                        kind: Some(lsp::CompletionItemKind::FUNCTION),
1234                        label: "hello(…)".to_string(),
1235                        label_details: Some(CompletionItemLabelDetails {
1236                            detail: Some("(use crate::foo)".to_string()),
1237                            description: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
1238                        }),
1239
1240                        ..Default::default()
1241                    },
1242                    &language
1243                )
1244                .await,
1245            Some(CodeLabel {
1246                text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1247                filter_range: 0..5,
1248                runs: vec![
1249                    (0..5, highlight_function),
1250                    (7..10, highlight_keyword),
1251                    (11..17, highlight_type),
1252                    (18..19, highlight_type),
1253                    (25..28, highlight_type),
1254                    (29..30, highlight_type),
1255                ],
1256            })
1257        );
1258
1259        assert_eq!(
1260            adapter
1261                .label_for_completion(
1262                    &lsp::CompletionItem {
1263                        kind: Some(lsp::CompletionItemKind::FUNCTION),
1264                        label: "hello".to_string(),
1265                        label_details: Some(CompletionItemLabelDetails {
1266                            detail: Some("(use crate::foo)".to_string()),
1267                            description: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
1268                        }),
1269                        ..Default::default()
1270                    },
1271                    &language
1272                )
1273                .await,
1274            Some(CodeLabel {
1275                text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1276                filter_range: 0..5,
1277                runs: vec![
1278                    (0..5, highlight_function),
1279                    (7..10, highlight_keyword),
1280                    (11..17, highlight_type),
1281                    (18..19, highlight_type),
1282                    (25..28, highlight_type),
1283                    (29..30, highlight_type),
1284                ],
1285            })
1286        );
1287
1288        assert_eq!(
1289            adapter
1290                .label_for_completion(
1291                    &lsp::CompletionItem {
1292                        kind: Some(lsp::CompletionItemKind::METHOD),
1293                        label: "await.as_deref_mut()".to_string(),
1294                        filter_text: Some("as_deref_mut".to_string()),
1295                        label_details: Some(CompletionItemLabelDetails {
1296                            detail: None,
1297                            description: Some("fn(&mut self) -> IterMut<'_, T>".to_string()),
1298                        }),
1299                        ..Default::default()
1300                    },
1301                    &language
1302                )
1303                .await,
1304            Some(CodeLabel {
1305                text: "await.as_deref_mut(&mut self) -> IterMut<'_, T>".to_string(),
1306                filter_range: 6..18,
1307                runs: vec![
1308                    (6..18, HighlightId(2)),
1309                    (20..23, HighlightId(1)),
1310                    (33..40, HighlightId(0)),
1311                    (45..46, HighlightId(0))
1312                ],
1313            })
1314        );
1315
1316        assert_eq!(
1317            adapter
1318                .label_for_completion(
1319                    &lsp::CompletionItem {
1320                        kind: Some(lsp::CompletionItemKind::METHOD),
1321                        label: "as_deref_mut()".to_string(),
1322                        filter_text: Some("as_deref_mut".to_string()),
1323                        label_details: Some(CompletionItemLabelDetails {
1324                            detail: None,
1325                            description: Some(
1326                                "pub fn as_deref_mut(&mut self) -> IterMut<'_, T>".to_string()
1327                            ),
1328                        }),
1329                        ..Default::default()
1330                    },
1331                    &language
1332                )
1333                .await,
1334            Some(CodeLabel {
1335                text: "pub fn as_deref_mut(&mut self) -> IterMut<'_, T>".to_string(),
1336                filter_range: 7..19,
1337                runs: vec![
1338                    (0..3, HighlightId(1)),
1339                    (4..6, HighlightId(1)),
1340                    (7..19, HighlightId(2)),
1341                    (21..24, HighlightId(1)),
1342                    (34..41, HighlightId(0)),
1343                    (46..47, HighlightId(0))
1344                ],
1345            })
1346        );
1347
1348        assert_eq!(
1349            adapter
1350                .label_for_completion(
1351                    &lsp::CompletionItem {
1352                        kind: Some(lsp::CompletionItemKind::FIELD),
1353                        label: "inner_value".to_string(),
1354                        filter_text: Some("value".to_string()),
1355                        detail: Some("String".to_string()),
1356                        ..Default::default()
1357                    },
1358                    &language,
1359                )
1360                .await,
1361            Some(CodeLabel {
1362                text: "inner_value: String".to_string(),
1363                filter_range: 6..11,
1364                runs: vec![(0..11, HighlightId(3)), (13..19, HighlightId(0))],
1365            })
1366        );
1367    }
1368
1369    #[gpui::test]
1370    async fn test_rust_label_for_symbol() {
1371        let adapter = Arc::new(RustLspAdapter);
1372        let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1373        let grammar = language.grammar().unwrap();
1374        let theme = SyntaxTheme::new_test([
1375            ("type", Hsla::default()),
1376            ("keyword", Hsla::default()),
1377            ("function", Hsla::default()),
1378            ("property", Hsla::default()),
1379        ]);
1380
1381        language.set_theme(&theme);
1382
1383        let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1384        let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1385        let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1386
1387        assert_eq!(
1388            adapter
1389                .label_for_symbol("hello", lsp::SymbolKind::FUNCTION, &language)
1390                .await,
1391            Some(CodeLabel {
1392                text: "fn hello".to_string(),
1393                filter_range: 3..8,
1394                runs: vec![(0..2, highlight_keyword), (3..8, highlight_function)],
1395            })
1396        );
1397
1398        assert_eq!(
1399            adapter
1400                .label_for_symbol("World", lsp::SymbolKind::TYPE_PARAMETER, &language)
1401                .await,
1402            Some(CodeLabel {
1403                text: "type World".to_string(),
1404                filter_range: 5..10,
1405                runs: vec![(0..4, highlight_keyword), (5..10, highlight_type)],
1406            })
1407        );
1408    }
1409
1410    #[gpui::test]
1411    async fn test_rust_autoindent(cx: &mut TestAppContext) {
1412        // cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
1413        cx.update(|cx| {
1414            let test_settings = SettingsStore::test(cx);
1415            cx.set_global(test_settings);
1416            language::init(cx);
1417            cx.update_global::<SettingsStore, _>(|store, cx| {
1418                store.update_user_settings(cx, |s| {
1419                    s.project.all_languages.defaults.tab_size = NonZeroU32::new(2);
1420                });
1421            });
1422        });
1423
1424        let language = crate::language("rust", tree_sitter_rust::LANGUAGE.into());
1425
1426        cx.new(|cx| {
1427            let mut buffer = Buffer::local("", cx).with_language(language, cx);
1428
1429            // indent between braces
1430            buffer.set_text("fn a() {}", cx);
1431            let ix = buffer.len() - 1;
1432            buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1433            assert_eq!(buffer.text(), "fn a() {\n  \n}");
1434
1435            // indent between braces, even after empty lines
1436            buffer.set_text("fn a() {\n\n\n}", cx);
1437            let ix = buffer.len() - 2;
1438            buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1439            assert_eq!(buffer.text(), "fn a() {\n\n\n  \n}");
1440
1441            // indent a line that continues a field expression
1442            buffer.set_text("fn a() {\n  \n}", cx);
1443            let ix = buffer.len() - 2;
1444            buffer.edit([(ix..ix, "b\n.c")], Some(AutoindentMode::EachLine), cx);
1445            assert_eq!(buffer.text(), "fn a() {\n  b\n    .c\n}");
1446
1447            // indent further lines that continue the field expression, even after empty lines
1448            let ix = buffer.len() - 2;
1449            buffer.edit([(ix..ix, "\n\n.d")], Some(AutoindentMode::EachLine), cx);
1450            assert_eq!(buffer.text(), "fn a() {\n  b\n    .c\n    \n    .d\n}");
1451
1452            // dedent the line after the field expression
1453            let ix = buffer.len() - 2;
1454            buffer.edit([(ix..ix, ";\ne")], Some(AutoindentMode::EachLine), cx);
1455            assert_eq!(
1456                buffer.text(),
1457                "fn a() {\n  b\n    .c\n    \n    .d;\n  e\n}"
1458            );
1459
1460            // indent inside a struct within a call
1461            buffer.set_text("const a: B = c(D {});", cx);
1462            let ix = buffer.len() - 3;
1463            buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1464            assert_eq!(buffer.text(), "const a: B = c(D {\n  \n});");
1465
1466            // indent further inside a nested call
1467            let ix = buffer.len() - 4;
1468            buffer.edit([(ix..ix, "e: f(\n\n)")], Some(AutoindentMode::EachLine), cx);
1469            assert_eq!(buffer.text(), "const a: B = c(D {\n  e: f(\n    \n  )\n});");
1470
1471            // keep that indent after an empty line
1472            let ix = buffer.len() - 8;
1473            buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1474            assert_eq!(
1475                buffer.text(),
1476                "const a: B = c(D {\n  e: f(\n    \n    \n  )\n});"
1477            );
1478
1479            buffer
1480        });
1481    }
1482
1483    #[test]
1484    fn test_package_name_from_pkgid() {
1485        for (input, expected) in [
1486            (
1487                "path+file:///absolute/path/to/project/zed/crates/zed#0.131.0",
1488                "zed",
1489            ),
1490            (
1491                "path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0",
1492                "my-custom-package",
1493            ),
1494        ] {
1495            assert_eq!(package_name_from_pkgid(input), Some(expected));
1496        }
1497    }
1498
1499    #[test]
1500    fn test_target_info_from_metadata() {
1501        for (input, absolute_path, expected) in [
1502            (
1503                r#"{"packages":[{"id":"path+file:///absolute/path/to/project/zed/crates/zed#0.131.0","manifest_path":"/path/to/zed/Cargo.toml","targets":[{"name":"zed","kind":["bin"],"src_path":"/path/to/zed/src/main.rs"}]}]}"#,
1504                "/path/to/zed/src/main.rs",
1505                Some((
1506                    Some(TargetInfo {
1507                        package_name: "zed".into(),
1508                        target_name: "zed".into(),
1509                        required_features: Vec::new(),
1510                        target_kind: TargetKind::Bin,
1511                    }),
1512                    Arc::from("/path/to/zed".as_ref()),
1513                )),
1514            ),
1515            (
1516                r#"{"packages":[{"id":"path+file:///path/to/custom-package#my-custom-package@0.1.0","manifest_path":"/path/to/custom-package/Cargo.toml","targets":[{"name":"my-custom-bin","kind":["bin"],"src_path":"/path/to/custom-package/src/main.rs"}]}]}"#,
1517                "/path/to/custom-package/src/main.rs",
1518                Some((
1519                    Some(TargetInfo {
1520                        package_name: "my-custom-package".into(),
1521                        target_name: "my-custom-bin".into(),
1522                        required_features: Vec::new(),
1523                        target_kind: TargetKind::Bin,
1524                    }),
1525                    Arc::from("/path/to/custom-package".as_ref()),
1526                )),
1527            ),
1528            (
1529                r#"{"packages":[{"id":"path+file:///path/to/custom-package#my-custom-package@0.1.0","targets":[{"name":"my-custom-bin","kind":["example"],"src_path":"/path/to/custom-package/src/main.rs"}],"manifest_path":"/path/to/custom-package/Cargo.toml"}]}"#,
1530                "/path/to/custom-package/src/main.rs",
1531                Some((
1532                    Some(TargetInfo {
1533                        package_name: "my-custom-package".into(),
1534                        target_name: "my-custom-bin".into(),
1535                        required_features: Vec::new(),
1536                        target_kind: TargetKind::Example,
1537                    }),
1538                    Arc::from("/path/to/custom-package".as_ref()),
1539                )),
1540            ),
1541            (
1542                r#"{"packages":[{"id":"path+file:///path/to/custom-package#my-custom-package@0.1.0","manifest_path":"/path/to/custom-package/Cargo.toml","targets":[{"name":"my-custom-bin","kind":["example"],"src_path":"/path/to/custom-package/src/main.rs","required-features":["foo","bar"]}]}]}"#,
1543                "/path/to/custom-package/src/main.rs",
1544                Some((
1545                    Some(TargetInfo {
1546                        package_name: "my-custom-package".into(),
1547                        target_name: "my-custom-bin".into(),
1548                        required_features: vec!["foo".to_owned(), "bar".to_owned()],
1549                        target_kind: TargetKind::Example,
1550                    }),
1551                    Arc::from("/path/to/custom-package".as_ref()),
1552                )),
1553            ),
1554            (
1555                r#"{"packages":[{"id":"path+file:///path/to/custom-package#my-custom-package@0.1.0","targets":[{"name":"my-custom-bin","kind":["example"],"src_path":"/path/to/custom-package/src/main.rs","required-features":[]}],"manifest_path":"/path/to/custom-package/Cargo.toml"}]}"#,
1556                "/path/to/custom-package/src/main.rs",
1557                Some((
1558                    Some(TargetInfo {
1559                        package_name: "my-custom-package".into(),
1560                        target_name: "my-custom-bin".into(),
1561                        required_features: vec![],
1562                        target_kind: TargetKind::Example,
1563                    }),
1564                    Arc::from("/path/to/custom-package".as_ref()),
1565                )),
1566            ),
1567            (
1568                r#"{"packages":[{"id":"path+file:///path/to/custom-package#my-custom-package@0.1.0","targets":[{"name":"my-custom-package","kind":["lib"],"src_path":"/path/to/custom-package/src/main.rs"}],"manifest_path":"/path/to/custom-package/Cargo.toml"}]}"#,
1569                "/path/to/custom-package/src/main.rs",
1570                Some((None, Arc::from("/path/to/custom-package".as_ref()))),
1571            ),
1572        ] {
1573            let metadata: CargoMetadata = serde_json::from_str(input).context(input).unwrap();
1574
1575            let absolute_path = Path::new(absolute_path);
1576
1577            assert_eq!(target_info_from_metadata(metadata, absolute_path), expected);
1578        }
1579    }
1580
1581    #[test]
1582    fn test_rust_test_fragment() {
1583        #[track_caller]
1584        fn check(
1585            variables: impl IntoIterator<Item = (VariableName, &'static str)>,
1586            path: &str,
1587            expected: &str,
1588        ) {
1589            let path = Path::new(path);
1590            let found = test_fragment(
1591                &TaskVariables::from_iter(variables.into_iter().map(|(k, v)| (k, v.to_owned()))),
1592                path,
1593                path.file_stem().unwrap().to_str().unwrap(),
1594            );
1595            assert_eq!(expected, found);
1596        }
1597
1598        check([], "/project/src/lib.rs", "--lib");
1599        check([], "/project/src/foo/mod.rs", "foo");
1600        check(
1601            [
1602                (RUST_BIN_KIND_TASK_VARIABLE.clone(), "bin"),
1603                (RUST_BIN_NAME_TASK_VARIABLE, "x"),
1604            ],
1605            "/project/src/main.rs",
1606            "--bin=x",
1607        );
1608        check([], "/project/src/main.rs", "--");
1609    }
1610}