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