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        Ok(original)
 514    }
 515}
 516
 517pub(crate) struct RustContextProvider;
 518
 519const RUST_PACKAGE_TASK_VARIABLE: VariableName =
 520    VariableName::Custom(Cow::Borrowed("RUST_PACKAGE"));
 521
 522/// The bin name corresponding to the current file in Cargo.toml
 523const RUST_BIN_NAME_TASK_VARIABLE: VariableName =
 524    VariableName::Custom(Cow::Borrowed("RUST_BIN_NAME"));
 525
 526/// The bin kind (bin/example) corresponding to the current file in Cargo.toml
 527const RUST_BIN_KIND_TASK_VARIABLE: VariableName =
 528    VariableName::Custom(Cow::Borrowed("RUST_BIN_KIND"));
 529
 530/// The flag to list required features for executing a bin, if any
 531const RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE: VariableName =
 532    VariableName::Custom(Cow::Borrowed("RUST_BIN_REQUIRED_FEATURES_FLAG"));
 533
 534/// The list of required features for executing a bin, if any
 535const RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE: VariableName =
 536    VariableName::Custom(Cow::Borrowed("RUST_BIN_REQUIRED_FEATURES"));
 537
 538const RUST_TEST_FRAGMENT_TASK_VARIABLE: VariableName =
 539    VariableName::Custom(Cow::Borrowed("RUST_TEST_FRAGMENT"));
 540
 541const RUST_DOC_TEST_NAME_TASK_VARIABLE: VariableName =
 542    VariableName::Custom(Cow::Borrowed("RUST_DOC_TEST_NAME"));
 543
 544const RUST_TEST_NAME_TASK_VARIABLE: VariableName =
 545    VariableName::Custom(Cow::Borrowed("RUST_TEST_NAME"));
 546
 547const RUST_MANIFEST_DIRNAME_TASK_VARIABLE: VariableName =
 548    VariableName::Custom(Cow::Borrowed("RUST_MANIFEST_DIRNAME"));
 549
 550impl ContextProvider for RustContextProvider {
 551    fn build_context(
 552        &self,
 553        task_variables: &TaskVariables,
 554        location: ContextLocation<'_>,
 555        project_env: Option<HashMap<String, String>>,
 556        _: Arc<dyn LanguageToolchainStore>,
 557        cx: &mut gpui::App,
 558    ) -> Task<Result<TaskVariables>> {
 559        let local_abs_path = location
 560            .file_location
 561            .buffer
 562            .read(cx)
 563            .file()
 564            .and_then(|file| Some(file.as_local()?.abs_path(cx)));
 565
 566        let mut variables = TaskVariables::default();
 567
 568        if let (Some(path), Some(stem)) = (&local_abs_path, task_variables.get(&VariableName::Stem))
 569        {
 570            let fragment = test_fragment(&variables, path, stem);
 571            variables.insert(RUST_TEST_FRAGMENT_TASK_VARIABLE, fragment);
 572        };
 573        if let Some(test_name) =
 574            task_variables.get(&VariableName::Custom(Cow::Borrowed("_test_name")))
 575        {
 576            variables.insert(RUST_TEST_NAME_TASK_VARIABLE, test_name.into());
 577        }
 578        if let Some(doc_test_name) =
 579            task_variables.get(&VariableName::Custom(Cow::Borrowed("_doc_test_name")))
 580        {
 581            variables.insert(RUST_DOC_TEST_NAME_TASK_VARIABLE, doc_test_name.into());
 582        }
 583        cx.background_spawn(async move {
 584            if let Some(path) = local_abs_path
 585                .as_deref()
 586                .and_then(|local_abs_path| local_abs_path.parent())
 587                && let Some(package_name) =
 588                    human_readable_package_name(path, project_env.as_ref()).await
 589            {
 590                variables.insert(RUST_PACKAGE_TASK_VARIABLE.clone(), package_name);
 591            }
 592            if let Some(path) = local_abs_path.as_ref()
 593                && let Some((target, manifest_path)) =
 594                    target_info_from_abs_path(path, project_env.as_ref()).await
 595            {
 596                if let Some(target) = target {
 597                    variables.extend(TaskVariables::from_iter([
 598                        (RUST_PACKAGE_TASK_VARIABLE.clone(), target.package_name),
 599                        (RUST_BIN_NAME_TASK_VARIABLE.clone(), target.target_name),
 600                        (
 601                            RUST_BIN_KIND_TASK_VARIABLE.clone(),
 602                            target.target_kind.to_string(),
 603                        ),
 604                    ]));
 605                    if target.required_features.is_empty() {
 606                        variables.insert(RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE, "".into());
 607                        variables.insert(RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE, "".into());
 608                    } else {
 609                        variables.insert(
 610                            RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE.clone(),
 611                            "--features".to_string(),
 612                        );
 613                        variables.insert(
 614                            RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE.clone(),
 615                            target.required_features.join(","),
 616                        );
 617                    }
 618                }
 619                variables.extend(TaskVariables::from_iter([(
 620                    RUST_MANIFEST_DIRNAME_TASK_VARIABLE.clone(),
 621                    manifest_path.to_string_lossy().into_owned(),
 622                )]));
 623            }
 624            Ok(variables)
 625        })
 626    }
 627
 628    fn associated_tasks(
 629        &self,
 630        _: Arc<dyn Fs>,
 631        file: Option<Arc<dyn language::File>>,
 632        cx: &App,
 633    ) -> Task<Option<TaskTemplates>> {
 634        const DEFAULT_RUN_NAME_STR: &str = "RUST_DEFAULT_PACKAGE_RUN";
 635        const CUSTOM_TARGET_DIR: &str = "RUST_TARGET_DIR";
 636
 637        let language_sets = language_settings(Some("Rust".into()), file.as_ref(), cx);
 638        let package_to_run = language_sets
 639            .tasks
 640            .variables
 641            .get(DEFAULT_RUN_NAME_STR)
 642            .cloned();
 643        let custom_target_dir = language_sets
 644            .tasks
 645            .variables
 646            .get(CUSTOM_TARGET_DIR)
 647            .cloned();
 648        let run_task_args = if let Some(package_to_run) = package_to_run {
 649            vec!["run".into(), "-p".into(), package_to_run]
 650        } else {
 651            vec!["run".into()]
 652        };
 653        let mut task_templates = vec![
 654            TaskTemplate {
 655                label: format!(
 656                    "Check (package: {})",
 657                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 658                ),
 659                command: "cargo".into(),
 660                args: vec![
 661                    "check".into(),
 662                    "-p".into(),
 663                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 664                ],
 665                cwd: Some("$ZED_DIRNAME".to_owned()),
 666                ..TaskTemplate::default()
 667            },
 668            TaskTemplate {
 669                label: "Check all targets (workspace)".into(),
 670                command: "cargo".into(),
 671                args: vec!["check".into(), "--workspace".into(), "--all-targets".into()],
 672                cwd: Some("$ZED_DIRNAME".to_owned()),
 673                ..TaskTemplate::default()
 674            },
 675            TaskTemplate {
 676                label: format!(
 677                    "Test '{}' (package: {})",
 678                    RUST_TEST_NAME_TASK_VARIABLE.template_value(),
 679                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 680                ),
 681                command: "cargo".into(),
 682                args: vec![
 683                    "test".into(),
 684                    "-p".into(),
 685                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 686                    "--".into(),
 687                    "--nocapture".into(),
 688                    "--include-ignored".into(),
 689                    RUST_TEST_NAME_TASK_VARIABLE.template_value(),
 690                ],
 691                tags: vec!["rust-test".to_owned()],
 692                cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
 693                ..TaskTemplate::default()
 694            },
 695            TaskTemplate {
 696                label: format!(
 697                    "Doc test '{}' (package: {})",
 698                    RUST_DOC_TEST_NAME_TASK_VARIABLE.template_value(),
 699                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 700                ),
 701                command: "cargo".into(),
 702                args: vec![
 703                    "test".into(),
 704                    "--doc".into(),
 705                    "-p".into(),
 706                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 707                    "--".into(),
 708                    "--nocapture".into(),
 709                    "--include-ignored".into(),
 710                    RUST_DOC_TEST_NAME_TASK_VARIABLE.template_value(),
 711                ],
 712                tags: vec!["rust-doc-test".to_owned()],
 713                cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
 714                ..TaskTemplate::default()
 715            },
 716            TaskTemplate {
 717                label: format!(
 718                    "Test mod '{}' (package: {})",
 719                    VariableName::Stem.template_value(),
 720                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 721                ),
 722                command: "cargo".into(),
 723                args: vec![
 724                    "test".into(),
 725                    "-p".into(),
 726                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 727                    "--".into(),
 728                    RUST_TEST_FRAGMENT_TASK_VARIABLE.template_value(),
 729                ],
 730                tags: vec!["rust-mod-test".to_owned()],
 731                cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
 732                ..TaskTemplate::default()
 733            },
 734            TaskTemplate {
 735                label: format!(
 736                    "Run {} {} (package: {})",
 737                    RUST_BIN_KIND_TASK_VARIABLE.template_value(),
 738                    RUST_BIN_NAME_TASK_VARIABLE.template_value(),
 739                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 740                ),
 741                command: "cargo".into(),
 742                args: vec![
 743                    "run".into(),
 744                    "-p".into(),
 745                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 746                    format!("--{}", RUST_BIN_KIND_TASK_VARIABLE.template_value()),
 747                    RUST_BIN_NAME_TASK_VARIABLE.template_value(),
 748                    RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE.template_value(),
 749                    RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE.template_value(),
 750                ],
 751                cwd: Some("$ZED_DIRNAME".to_owned()),
 752                tags: vec!["rust-main".to_owned()],
 753                ..TaskTemplate::default()
 754            },
 755            TaskTemplate {
 756                label: format!(
 757                    "Test (package: {})",
 758                    RUST_PACKAGE_TASK_VARIABLE.template_value()
 759                ),
 760                command: "cargo".into(),
 761                args: vec![
 762                    "test".into(),
 763                    "-p".into(),
 764                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 765                ],
 766                cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
 767                ..TaskTemplate::default()
 768            },
 769            TaskTemplate {
 770                label: "Run".into(),
 771                command: "cargo".into(),
 772                args: run_task_args,
 773                cwd: Some("$ZED_DIRNAME".to_owned()),
 774                ..TaskTemplate::default()
 775            },
 776            TaskTemplate {
 777                label: "Clean".into(),
 778                command: "cargo".into(),
 779                args: vec!["clean".into()],
 780                cwd: Some("$ZED_DIRNAME".to_owned()),
 781                ..TaskTemplate::default()
 782            },
 783        ];
 784
 785        if let Some(custom_target_dir) = custom_target_dir {
 786            task_templates = task_templates
 787                .into_iter()
 788                .map(|mut task_template| {
 789                    let mut args = task_template.args.split_off(1);
 790                    task_template.args.append(&mut vec![
 791                        "--target-dir".to_string(),
 792                        custom_target_dir.clone(),
 793                    ]);
 794                    task_template.args.append(&mut args);
 795
 796                    task_template
 797                })
 798                .collect();
 799        }
 800
 801        Task::ready(Some(TaskTemplates(task_templates)))
 802    }
 803
 804    fn lsp_task_source(&self) -> Option<LanguageServerName> {
 805        Some(SERVER_NAME)
 806    }
 807}
 808
 809/// Part of the data structure of Cargo metadata
 810#[derive(Debug, serde::Deserialize)]
 811struct CargoMetadata {
 812    packages: Vec<CargoPackage>,
 813}
 814
 815#[derive(Debug, serde::Deserialize)]
 816struct CargoPackage {
 817    id: String,
 818    targets: Vec<CargoTarget>,
 819    manifest_path: Arc<Path>,
 820}
 821
 822#[derive(Debug, serde::Deserialize)]
 823struct CargoTarget {
 824    name: String,
 825    kind: Vec<String>,
 826    src_path: String,
 827    #[serde(rename = "required-features", default)]
 828    required_features: Vec<String>,
 829}
 830
 831#[derive(Debug, PartialEq)]
 832enum TargetKind {
 833    Bin,
 834    Example,
 835}
 836
 837impl Display for TargetKind {
 838    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 839        match self {
 840            TargetKind::Bin => write!(f, "bin"),
 841            TargetKind::Example => write!(f, "example"),
 842        }
 843    }
 844}
 845
 846impl TryFrom<&str> for TargetKind {
 847    type Error = ();
 848    fn try_from(value: &str) -> Result<Self, ()> {
 849        match value {
 850            "bin" => Ok(Self::Bin),
 851            "example" => Ok(Self::Example),
 852            _ => Err(()),
 853        }
 854    }
 855}
 856/// Which package and binary target are we in?
 857#[derive(Debug, PartialEq)]
 858struct TargetInfo {
 859    package_name: String,
 860    target_name: String,
 861    target_kind: TargetKind,
 862    required_features: Vec<String>,
 863}
 864
 865async fn target_info_from_abs_path(
 866    abs_path: &Path,
 867    project_env: Option<&HashMap<String, String>>,
 868) -> Option<(Option<TargetInfo>, Arc<Path>)> {
 869    let mut command = util::command::new_smol_command("cargo");
 870    if let Some(envs) = project_env {
 871        command.envs(envs);
 872    }
 873    let output = command
 874        .current_dir(abs_path.parent()?)
 875        .arg("metadata")
 876        .arg("--no-deps")
 877        .arg("--format-version")
 878        .arg("1")
 879        .output()
 880        .await
 881        .log_err()?
 882        .stdout;
 883
 884    let metadata: CargoMetadata = serde_json::from_slice(&output).log_err()?;
 885    target_info_from_metadata(metadata, abs_path)
 886}
 887
 888fn target_info_from_metadata(
 889    metadata: CargoMetadata,
 890    abs_path: &Path,
 891) -> Option<(Option<TargetInfo>, Arc<Path>)> {
 892    let mut manifest_path = None;
 893    for package in metadata.packages {
 894        let Some(manifest_dir_path) = package.manifest_path.parent() else {
 895            continue;
 896        };
 897
 898        let Some(path_from_manifest_dir) = abs_path.strip_prefix(manifest_dir_path).ok() else {
 899            continue;
 900        };
 901        let candidate_path_length = path_from_manifest_dir.components().count();
 902        // Pick the most specific manifest path
 903        if let Some((path, current_length)) = &mut manifest_path {
 904            if candidate_path_length > *current_length {
 905                *path = Arc::from(manifest_dir_path);
 906                *current_length = candidate_path_length;
 907            }
 908        } else {
 909            manifest_path = Some((Arc::from(manifest_dir_path), candidate_path_length));
 910        };
 911
 912        for target in package.targets {
 913            let Some(bin_kind) = target
 914                .kind
 915                .iter()
 916                .find_map(|kind| TargetKind::try_from(kind.as_ref()).ok())
 917            else {
 918                continue;
 919            };
 920            let target_path = PathBuf::from(target.src_path);
 921            if target_path == abs_path {
 922                return manifest_path.map(|(path, _)| {
 923                    (
 924                        package_name_from_pkgid(&package.id).map(|package_name| TargetInfo {
 925                            package_name: package_name.to_owned(),
 926                            target_name: target.name,
 927                            required_features: target.required_features,
 928                            target_kind: bin_kind,
 929                        }),
 930                        path,
 931                    )
 932                });
 933            }
 934        }
 935    }
 936
 937    manifest_path.map(|(path, _)| (None, path))
 938}
 939
 940async fn human_readable_package_name(
 941    package_directory: &Path,
 942    project_env: Option<&HashMap<String, String>>,
 943) -> Option<String> {
 944    let mut command = util::command::new_smol_command("cargo");
 945    if let Some(envs) = project_env {
 946        command.envs(envs);
 947    }
 948    let pkgid = String::from_utf8(
 949        command
 950            .current_dir(package_directory)
 951            .arg("pkgid")
 952            .output()
 953            .await
 954            .log_err()?
 955            .stdout,
 956    )
 957    .ok()?;
 958    Some(package_name_from_pkgid(&pkgid)?.to_owned())
 959}
 960
 961// For providing local `cargo check -p $pkgid` task, we do not need most of the information we have returned.
 962// Output example in the root of Zed project:
 963// ```sh
 964// ❯ cargo pkgid zed
 965// path+file:///absolute/path/to/project/zed/crates/zed#0.131.0
 966// ```
 967// Another variant, if a project has a custom package name or hyphen in the name:
 968// ```
 969// path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0
 970// ```
 971//
 972// Extracts the package name from the output according to the spec:
 973// https://doc.rust-lang.org/cargo/reference/pkgid-spec.html#specification-grammar
 974fn package_name_from_pkgid(pkgid: &str) -> Option<&str> {
 975    fn split_off_suffix(input: &str, suffix_start: char) -> &str {
 976        match input.rsplit_once(suffix_start) {
 977            Some((without_suffix, _)) => without_suffix,
 978            None => input,
 979        }
 980    }
 981
 982    let (version_prefix, version_suffix) = pkgid.trim().rsplit_once('#')?;
 983    let package_name = match version_suffix.rsplit_once('@') {
 984        Some((custom_package_name, _version)) => custom_package_name,
 985        None => {
 986            let host_and_path = split_off_suffix(version_prefix, '?');
 987            let (_, package_name) = host_and_path.rsplit_once('/')?;
 988            package_name
 989        }
 990    };
 991    Some(package_name)
 992}
 993
 994async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
 995    maybe!(async {
 996        let mut last = None;
 997        let mut entries = fs::read_dir(&container_dir).await?;
 998        while let Some(entry) = entries.next().await {
 999            let path = entry?.path();
1000            if path.extension().is_some_and(|ext| ext == "metadata") {
1001                continue;
1002            }
1003            last = Some(path);
1004        }
1005
1006        let path = last.context("no cached binary")?;
1007        let path = match RustLspAdapter::GITHUB_ASSET_KIND {
1008            AssetKind::TarGz | AssetKind::Gz => path, // Tar and gzip extract in place.
1009            AssetKind::Zip => path.join("rust-analyzer.exe"), // zip contains a .exe
1010        };
1011
1012        anyhow::Ok(LanguageServerBinary {
1013            path,
1014            env: None,
1015            arguments: Default::default(),
1016        })
1017    })
1018    .await
1019    .log_err()
1020}
1021
1022fn test_fragment(variables: &TaskVariables, path: &Path, stem: &str) -> String {
1023    let fragment = if stem == "lib" {
1024        // This isn't quite right---it runs the tests for the entire library, rather than
1025        // just for the top-level `mod tests`. But we don't really have the means here to
1026        // filter out just that module.
1027        Some("--lib".to_owned())
1028    } else if stem == "mod" {
1029        maybe!({ Some(path.parent()?.file_name()?.to_string_lossy().to_string()) })
1030    } else if stem == "main" {
1031        if let (Some(bin_name), Some(bin_kind)) = (
1032            variables.get(&RUST_BIN_NAME_TASK_VARIABLE),
1033            variables.get(&RUST_BIN_KIND_TASK_VARIABLE),
1034        ) {
1035            Some(format!("--{bin_kind}={bin_name}"))
1036        } else {
1037            None
1038        }
1039    } else {
1040        Some(stem.to_owned())
1041    };
1042    fragment.unwrap_or_else(|| "--".to_owned())
1043}
1044
1045#[cfg(test)]
1046mod tests {
1047    use std::num::NonZeroU32;
1048
1049    use super::*;
1050    use crate::language;
1051    use gpui::{BorrowAppContext, Hsla, TestAppContext};
1052    use language::language_settings::AllLanguageSettings;
1053    use lsp::CompletionItemLabelDetails;
1054    use settings::SettingsStore;
1055    use theme::SyntaxTheme;
1056    use util::path;
1057
1058    #[gpui::test]
1059    async fn test_process_rust_diagnostics() {
1060        let mut params = lsp::PublishDiagnosticsParams {
1061            uri: lsp::Uri::from_file_path(path!("/a")).unwrap(),
1062            version: None,
1063            diagnostics: vec![
1064                // no newlines
1065                lsp::Diagnostic {
1066                    message: "use of moved value `a`".to_string(),
1067                    ..Default::default()
1068                },
1069                // newline at the end of a code span
1070                lsp::Diagnostic {
1071                    message: "consider importing this struct: `use b::c;\n`".to_string(),
1072                    ..Default::default()
1073                },
1074                // code span starting right after a newline
1075                lsp::Diagnostic {
1076                    message: "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
1077                        .to_string(),
1078                    ..Default::default()
1079                },
1080            ],
1081        };
1082        RustLspAdapter.process_diagnostics(&mut params, LanguageServerId(0), None);
1083
1084        assert_eq!(params.diagnostics[0].message, "use of moved value `a`");
1085
1086        // remove trailing newline from code span
1087        assert_eq!(
1088            params.diagnostics[1].message,
1089            "consider importing this struct: `use b::c;`"
1090        );
1091
1092        // do not remove newline before the start of code span
1093        assert_eq!(
1094            params.diagnostics[2].message,
1095            "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
1096        );
1097    }
1098
1099    #[gpui::test]
1100    async fn test_rust_label_for_completion() {
1101        let adapter = Arc::new(RustLspAdapter);
1102        let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1103        let grammar = language.grammar().unwrap();
1104        let theme = SyntaxTheme::new_test([
1105            ("type", Hsla::default()),
1106            ("keyword", Hsla::default()),
1107            ("function", Hsla::default()),
1108            ("property", Hsla::default()),
1109        ]);
1110
1111        language.set_theme(&theme);
1112
1113        let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1114        let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1115        let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1116        let highlight_field = grammar.highlight_id_for_name("property").unwrap();
1117
1118        assert_eq!(
1119            adapter
1120                .label_for_completion(
1121                    &lsp::CompletionItem {
1122                        kind: Some(lsp::CompletionItemKind::FUNCTION),
1123                        label: "hello(…)".to_string(),
1124                        label_details: Some(CompletionItemLabelDetails {
1125                            detail: Some("(use crate::foo)".into()),
1126                            description: Some("fn(&mut Option<T>) -> Vec<T>".to_string())
1127                        }),
1128                        ..Default::default()
1129                    },
1130                    &language
1131                )
1132                .await,
1133            Some(CodeLabel {
1134                text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1135                filter_range: 0..5,
1136                runs: vec![
1137                    (0..5, highlight_function),
1138                    (7..10, highlight_keyword),
1139                    (11..17, highlight_type),
1140                    (18..19, highlight_type),
1141                    (25..28, highlight_type),
1142                    (29..30, highlight_type),
1143                ],
1144            })
1145        );
1146        assert_eq!(
1147            adapter
1148                .label_for_completion(
1149                    &lsp::CompletionItem {
1150                        kind: Some(lsp::CompletionItemKind::FUNCTION),
1151                        label: "hello(…)".to_string(),
1152                        label_details: Some(CompletionItemLabelDetails {
1153                            detail: Some("(use crate::foo)".into()),
1154                            description: Some("async fn(&mut Option<T>) -> Vec<T>".to_string()),
1155                        }),
1156                        ..Default::default()
1157                    },
1158                    &language
1159                )
1160                .await,
1161            Some(CodeLabel {
1162                text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1163                filter_range: 0..5,
1164                runs: vec![
1165                    (0..5, highlight_function),
1166                    (7..10, highlight_keyword),
1167                    (11..17, highlight_type),
1168                    (18..19, highlight_type),
1169                    (25..28, highlight_type),
1170                    (29..30, highlight_type),
1171                ],
1172            })
1173        );
1174        assert_eq!(
1175            adapter
1176                .label_for_completion(
1177                    &lsp::CompletionItem {
1178                        kind: Some(lsp::CompletionItemKind::FIELD),
1179                        label: "len".to_string(),
1180                        detail: Some("usize".to_string()),
1181                        ..Default::default()
1182                    },
1183                    &language
1184                )
1185                .await,
1186            Some(CodeLabel {
1187                text: "len: usize".to_string(),
1188                filter_range: 0..3,
1189                runs: vec![(0..3, highlight_field), (5..10, highlight_type),],
1190            })
1191        );
1192
1193        assert_eq!(
1194            adapter
1195                .label_for_completion(
1196                    &lsp::CompletionItem {
1197                        kind: Some(lsp::CompletionItemKind::FUNCTION),
1198                        label: "hello(…)".to_string(),
1199                        label_details: Some(CompletionItemLabelDetails {
1200                            detail: Some("(use crate::foo)".to_string()),
1201                            description: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
1202                        }),
1203
1204                        ..Default::default()
1205                    },
1206                    &language
1207                )
1208                .await,
1209            Some(CodeLabel {
1210                text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1211                filter_range: 0..5,
1212                runs: vec![
1213                    (0..5, highlight_function),
1214                    (7..10, highlight_keyword),
1215                    (11..17, highlight_type),
1216                    (18..19, highlight_type),
1217                    (25..28, highlight_type),
1218                    (29..30, highlight_type),
1219                ],
1220            })
1221        );
1222
1223        assert_eq!(
1224            adapter
1225                .label_for_completion(
1226                    &lsp::CompletionItem {
1227                        kind: Some(lsp::CompletionItemKind::FUNCTION),
1228                        label: "hello".to_string(),
1229                        label_details: Some(CompletionItemLabelDetails {
1230                            detail: Some("(use crate::foo)".to_string()),
1231                            description: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
1232                        }),
1233                        ..Default::default()
1234                    },
1235                    &language
1236                )
1237                .await,
1238            Some(CodeLabel {
1239                text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1240                filter_range: 0..5,
1241                runs: vec![
1242                    (0..5, highlight_function),
1243                    (7..10, highlight_keyword),
1244                    (11..17, highlight_type),
1245                    (18..19, highlight_type),
1246                    (25..28, highlight_type),
1247                    (29..30, highlight_type),
1248                ],
1249            })
1250        );
1251
1252        assert_eq!(
1253            adapter
1254                .label_for_completion(
1255                    &lsp::CompletionItem {
1256                        kind: Some(lsp::CompletionItemKind::METHOD),
1257                        label: "await.as_deref_mut()".to_string(),
1258                        filter_text: Some("as_deref_mut".to_string()),
1259                        label_details: Some(CompletionItemLabelDetails {
1260                            detail: None,
1261                            description: Some("fn(&mut self) -> IterMut<'_, T>".to_string()),
1262                        }),
1263                        ..Default::default()
1264                    },
1265                    &language
1266                )
1267                .await,
1268            Some(CodeLabel {
1269                text: "await.as_deref_mut(&mut self) -> IterMut<'_, T>".to_string(),
1270                filter_range: 6..18,
1271                runs: vec![
1272                    (6..18, HighlightId(2)),
1273                    (20..23, HighlightId(1)),
1274                    (33..40, HighlightId(0)),
1275                    (45..46, HighlightId(0))
1276                ],
1277            })
1278        );
1279
1280        assert_eq!(
1281            adapter
1282                .label_for_completion(
1283                    &lsp::CompletionItem {
1284                        kind: Some(lsp::CompletionItemKind::METHOD),
1285                        label: "as_deref_mut()".to_string(),
1286                        filter_text: Some("as_deref_mut".to_string()),
1287                        label_details: Some(CompletionItemLabelDetails {
1288                            detail: None,
1289                            description: Some(
1290                                "pub fn as_deref_mut(&mut self) -> IterMut<'_, T>".to_string()
1291                            ),
1292                        }),
1293                        ..Default::default()
1294                    },
1295                    &language
1296                )
1297                .await,
1298            Some(CodeLabel {
1299                text: "pub fn as_deref_mut(&mut self) -> IterMut<'_, T>".to_string(),
1300                filter_range: 7..19,
1301                runs: vec![
1302                    (0..3, HighlightId(1)),
1303                    (4..6, HighlightId(1)),
1304                    (7..19, HighlightId(2)),
1305                    (21..24, HighlightId(1)),
1306                    (34..41, HighlightId(0)),
1307                    (46..47, HighlightId(0))
1308                ],
1309            })
1310        );
1311
1312        assert_eq!(
1313            adapter
1314                .label_for_completion(
1315                    &lsp::CompletionItem {
1316                        kind: Some(lsp::CompletionItemKind::FIELD),
1317                        label: "inner_value".to_string(),
1318                        filter_text: Some("value".to_string()),
1319                        detail: Some("String".to_string()),
1320                        ..Default::default()
1321                    },
1322                    &language,
1323                )
1324                .await,
1325            Some(CodeLabel {
1326                text: "inner_value: String".to_string(),
1327                filter_range: 6..11,
1328                runs: vec![(0..11, HighlightId(3)), (13..19, HighlightId(0))],
1329            })
1330        );
1331    }
1332
1333    #[gpui::test]
1334    async fn test_rust_label_for_symbol() {
1335        let adapter = Arc::new(RustLspAdapter);
1336        let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1337        let grammar = language.grammar().unwrap();
1338        let theme = SyntaxTheme::new_test([
1339            ("type", Hsla::default()),
1340            ("keyword", Hsla::default()),
1341            ("function", Hsla::default()),
1342            ("property", Hsla::default()),
1343        ]);
1344
1345        language.set_theme(&theme);
1346
1347        let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1348        let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1349        let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1350
1351        assert_eq!(
1352            adapter
1353                .label_for_symbol("hello", lsp::SymbolKind::FUNCTION, &language)
1354                .await,
1355            Some(CodeLabel {
1356                text: "fn hello".to_string(),
1357                filter_range: 3..8,
1358                runs: vec![(0..2, highlight_keyword), (3..8, highlight_function)],
1359            })
1360        );
1361
1362        assert_eq!(
1363            adapter
1364                .label_for_symbol("World", lsp::SymbolKind::TYPE_PARAMETER, &language)
1365                .await,
1366            Some(CodeLabel {
1367                text: "type World".to_string(),
1368                filter_range: 5..10,
1369                runs: vec![(0..4, highlight_keyword), (5..10, highlight_type)],
1370            })
1371        );
1372    }
1373
1374    #[gpui::test]
1375    async fn test_rust_autoindent(cx: &mut TestAppContext) {
1376        // cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
1377        cx.update(|cx| {
1378            let test_settings = SettingsStore::test(cx);
1379            cx.set_global(test_settings);
1380            language::init(cx);
1381            cx.update_global::<SettingsStore, _>(|store, cx| {
1382                store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1383                    s.defaults.tab_size = NonZeroU32::new(2);
1384                });
1385            });
1386        });
1387
1388        let language = crate::language("rust", tree_sitter_rust::LANGUAGE.into());
1389
1390        cx.new(|cx| {
1391            let mut buffer = Buffer::local("", cx).with_language(language, cx);
1392
1393            // indent between braces
1394            buffer.set_text("fn a() {}", cx);
1395            let ix = buffer.len() - 1;
1396            buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1397            assert_eq!(buffer.text(), "fn a() {\n  \n}");
1398
1399            // indent between braces, even after empty lines
1400            buffer.set_text("fn a() {\n\n\n}", cx);
1401            let ix = buffer.len() - 2;
1402            buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1403            assert_eq!(buffer.text(), "fn a() {\n\n\n  \n}");
1404
1405            // indent a line that continues a field expression
1406            buffer.set_text("fn a() {\n  \n}", cx);
1407            let ix = buffer.len() - 2;
1408            buffer.edit([(ix..ix, "b\n.c")], Some(AutoindentMode::EachLine), cx);
1409            assert_eq!(buffer.text(), "fn a() {\n  b\n    .c\n}");
1410
1411            // indent further lines that continue the field expression, even after empty lines
1412            let ix = buffer.len() - 2;
1413            buffer.edit([(ix..ix, "\n\n.d")], Some(AutoindentMode::EachLine), cx);
1414            assert_eq!(buffer.text(), "fn a() {\n  b\n    .c\n    \n    .d\n}");
1415
1416            // dedent the line after the field expression
1417            let ix = buffer.len() - 2;
1418            buffer.edit([(ix..ix, ";\ne")], Some(AutoindentMode::EachLine), cx);
1419            assert_eq!(
1420                buffer.text(),
1421                "fn a() {\n  b\n    .c\n    \n    .d;\n  e\n}"
1422            );
1423
1424            // indent inside a struct within a call
1425            buffer.set_text("const a: B = c(D {});", cx);
1426            let ix = buffer.len() - 3;
1427            buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1428            assert_eq!(buffer.text(), "const a: B = c(D {\n  \n});");
1429
1430            // indent further inside a nested call
1431            let ix = buffer.len() - 4;
1432            buffer.edit([(ix..ix, "e: f(\n\n)")], Some(AutoindentMode::EachLine), cx);
1433            assert_eq!(buffer.text(), "const a: B = c(D {\n  e: f(\n    \n  )\n});");
1434
1435            // keep that indent after an empty line
1436            let ix = buffer.len() - 8;
1437            buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1438            assert_eq!(
1439                buffer.text(),
1440                "const a: B = c(D {\n  e: f(\n    \n    \n  )\n});"
1441            );
1442
1443            buffer
1444        });
1445    }
1446
1447    #[test]
1448    fn test_package_name_from_pkgid() {
1449        for (input, expected) in [
1450            (
1451                "path+file:///absolute/path/to/project/zed/crates/zed#0.131.0",
1452                "zed",
1453            ),
1454            (
1455                "path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0",
1456                "my-custom-package",
1457            ),
1458        ] {
1459            assert_eq!(package_name_from_pkgid(input), Some(expected));
1460        }
1461    }
1462
1463    #[test]
1464    fn test_target_info_from_metadata() {
1465        for (input, absolute_path, expected) in [
1466            (
1467                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"}]}]}"#,
1468                "/path/to/zed/src/main.rs",
1469                Some((
1470                    Some(TargetInfo {
1471                        package_name: "zed".into(),
1472                        target_name: "zed".into(),
1473                        required_features: Vec::new(),
1474                        target_kind: TargetKind::Bin,
1475                    }),
1476                    Arc::from("/path/to/zed".as_ref()),
1477                )),
1478            ),
1479            (
1480                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"}]}]}"#,
1481                "/path/to/custom-package/src/main.rs",
1482                Some((
1483                    Some(TargetInfo {
1484                        package_name: "my-custom-package".into(),
1485                        target_name: "my-custom-bin".into(),
1486                        required_features: Vec::new(),
1487                        target_kind: TargetKind::Bin,
1488                    }),
1489                    Arc::from("/path/to/custom-package".as_ref()),
1490                )),
1491            ),
1492            (
1493                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"}]}"#,
1494                "/path/to/custom-package/src/main.rs",
1495                Some((
1496                    Some(TargetInfo {
1497                        package_name: "my-custom-package".into(),
1498                        target_name: "my-custom-bin".into(),
1499                        required_features: Vec::new(),
1500                        target_kind: TargetKind::Example,
1501                    }),
1502                    Arc::from("/path/to/custom-package".as_ref()),
1503                )),
1504            ),
1505            (
1506                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"]}]}]}"#,
1507                "/path/to/custom-package/src/main.rs",
1508                Some((
1509                    Some(TargetInfo {
1510                        package_name: "my-custom-package".into(),
1511                        target_name: "my-custom-bin".into(),
1512                        required_features: vec!["foo".to_owned(), "bar".to_owned()],
1513                        target_kind: TargetKind::Example,
1514                    }),
1515                    Arc::from("/path/to/custom-package".as_ref()),
1516                )),
1517            ),
1518            (
1519                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"}]}"#,
1520                "/path/to/custom-package/src/main.rs",
1521                Some((
1522                    Some(TargetInfo {
1523                        package_name: "my-custom-package".into(),
1524                        target_name: "my-custom-bin".into(),
1525                        required_features: vec![],
1526                        target_kind: TargetKind::Example,
1527                    }),
1528                    Arc::from("/path/to/custom-package".as_ref()),
1529                )),
1530            ),
1531            (
1532                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"}]}"#,
1533                "/path/to/custom-package/src/main.rs",
1534                Some((None, Arc::from("/path/to/custom-package".as_ref()))),
1535            ),
1536        ] {
1537            let metadata: CargoMetadata = serde_json::from_str(input).context(input).unwrap();
1538
1539            let absolute_path = Path::new(absolute_path);
1540
1541            assert_eq!(target_info_from_metadata(metadata, absolute_path), expected);
1542        }
1543    }
1544
1545    #[test]
1546    fn test_rust_test_fragment() {
1547        #[track_caller]
1548        fn check(
1549            variables: impl IntoIterator<Item = (VariableName, &'static str)>,
1550            path: &str,
1551            expected: &str,
1552        ) {
1553            let path = Path::new(path);
1554            let found = test_fragment(
1555                &TaskVariables::from_iter(variables.into_iter().map(|(k, v)| (k, v.to_owned()))),
1556                path,
1557                path.file_stem().unwrap().to_str().unwrap(),
1558            );
1559            assert_eq!(expected, found);
1560        }
1561
1562        check([], "/project/src/lib.rs", "--lib");
1563        check([], "/project/src/foo/mod.rs", "foo");
1564        check(
1565            [
1566                (RUST_BIN_KIND_TASK_VARIABLE.clone(), "bin"),
1567                (RUST_BIN_NAME_TASK_VARIABLE, "x"),
1568            ],
1569            "/project/src/main.rs",
1570            "--bin=x",
1571        );
1572        check([], "/project/src/main.rs", "--");
1573    }
1574}