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