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