rust.rs

   1use anyhow::{Context as _, Result};
   2use async_trait::async_trait;
   3use collections::HashMap;
   4use futures::StreamExt;
   5use futures::lock::OwnedMutexGuard;
   6use gpui::{App, AppContext, AsyncApp, Entity, SharedString, Task};
   7use http_client::github::AssetKind;
   8use http_client::github::{GitHubLspBinaryVersion, latest_github_release};
   9use http_client::github_download::{GithubBinaryMetadata, download_server_binary};
  10pub use language::*;
  11use lsp::{InitializeParams, LanguageServerBinary, LanguageServerBinaryOptions};
  12use project::lsp_store::rust_analyzer_ext::CARGO_DIAGNOSTICS_SOURCE_NAME;
  13use project::project_settings::ProjectSettings;
  14use regex::Regex;
  15use serde_json::json;
  16use settings::Settings as _;
  17use smallvec::SmallVec;
  18use smol::fs::{self};
  19use std::cmp::Reverse;
  20use std::fmt::Display;
  21use std::ops::Range;
  22use std::process::Stdio;
  23use std::{
  24    borrow::Cow,
  25    path::{Path, PathBuf},
  26    sync::{Arc, LazyLock},
  27};
  28use task::{TaskTemplate, TaskTemplates, TaskVariables, VariableName};
  29use util::fs::{make_file_executable, remove_matching};
  30use util::merge_json_value_into;
  31use util::rel_path::RelPath;
  32use util::{ResultExt, maybe};
  33
  34use crate::language_settings::LanguageSettings;
  35
  36pub struct RustLspAdapter;
  37
  38#[cfg(target_os = "macos")]
  39impl RustLspAdapter {
  40    const GITHUB_ASSET_KIND: AssetKind = AssetKind::Gz;
  41    const ARCH_SERVER_NAME: &str = "apple-darwin";
  42}
  43
  44#[cfg(target_os = "linux")]
  45impl RustLspAdapter {
  46    const GITHUB_ASSET_KIND: AssetKind = AssetKind::Gz;
  47    const ARCH_SERVER_NAME: &str = "unknown-linux";
  48}
  49
  50#[cfg(target_os = "freebsd")]
  51impl RustLspAdapter {
  52    const GITHUB_ASSET_KIND: AssetKind = AssetKind::Gz;
  53    const ARCH_SERVER_NAME: &str = "unknown-freebsd";
  54}
  55
  56#[cfg(target_os = "windows")]
  57impl RustLspAdapter {
  58    const GITHUB_ASSET_KIND: AssetKind = AssetKind::Zip;
  59    const ARCH_SERVER_NAME: &str = "pc-windows-msvc";
  60}
  61
  62const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("rust-analyzer");
  63
  64#[cfg(target_os = "linux")]
  65enum LibcType {
  66    Gnu,
  67    Musl,
  68}
  69
  70impl RustLspAdapter {
  71    fn convert_rust_analyzer_schema(raw_schema: &serde_json::Value) -> serde_json::Value {
  72        let Some(schema_array) = raw_schema.as_array() else {
  73            return raw_schema.clone();
  74        };
  75
  76        let mut root_properties = serde_json::Map::new();
  77
  78        for item in schema_array {
  79            if let Some(props) = item.get("properties").and_then(|p| p.as_object()) {
  80                for (key, value) in props {
  81                    let parts: Vec<&str> = key.split('.').collect();
  82
  83                    if parts.is_empty() {
  84                        continue;
  85                    }
  86
  87                    let parts_to_process = if parts.first() == Some(&"rust-analyzer") {
  88                        &parts[1..]
  89                    } else {
  90                        &parts[..]
  91                    };
  92
  93                    if parts_to_process.is_empty() {
  94                        continue;
  95                    }
  96
  97                    let mut current = &mut root_properties;
  98
  99                    for (i, part) in parts_to_process.iter().enumerate() {
 100                        let is_last = i == parts_to_process.len() - 1;
 101
 102                        if is_last {
 103                            current.insert(part.to_string(), value.clone());
 104                        } else {
 105                            let next_current = current
 106                                .entry(part.to_string())
 107                                .or_insert_with(|| {
 108                                    serde_json::json!({
 109                                        "type": "object",
 110                                        "properties": {}
 111                                    })
 112                                })
 113                                .as_object_mut()
 114                                .expect("should be an object")
 115                                .entry("properties")
 116                                .or_insert_with(|| serde_json::json!({}))
 117                                .as_object_mut()
 118                                .expect("properties should be an object");
 119
 120                            current = next_current;
 121                        }
 122                    }
 123                }
 124            }
 125        }
 126
 127        serde_json::json!({
 128            "type": "object",
 129            "properties": root_properties
 130        })
 131    }
 132
 133    #[cfg(target_os = "linux")]
 134    async fn determine_libc_type() -> LibcType {
 135        use futures::pin_mut;
 136
 137        async fn from_ldd_version() -> Option<LibcType> {
 138            use util::command::new_smol_command;
 139
 140            let ldd_output = new_smol_command("ldd")
 141                .arg("--version")
 142                .output()
 143                .await
 144                .ok()?;
 145            let ldd_version = String::from_utf8_lossy(&ldd_output.stdout);
 146
 147            if ldd_version.contains("GNU libc") || ldd_version.contains("GLIBC") {
 148                Some(LibcType::Gnu)
 149            } else if ldd_version.contains("musl") {
 150                Some(LibcType::Musl)
 151            } else {
 152                None
 153            }
 154        }
 155
 156        if let Some(libc_type) = from_ldd_version().await {
 157            return libc_type;
 158        }
 159
 160        let Ok(dir_entries) = smol::fs::read_dir("/lib").await else {
 161            // defaulting to gnu because nix doesn't have /lib files due to not following FHS
 162            return LibcType::Gnu;
 163        };
 164        let dir_entries = dir_entries.filter_map(async move |e| e.ok());
 165        pin_mut!(dir_entries);
 166
 167        let mut has_musl = false;
 168        let mut has_gnu = false;
 169
 170        while let Some(entry) = dir_entries.next().await {
 171            let file_name = entry.file_name();
 172            let file_name = file_name.to_string_lossy();
 173            if file_name.starts_with("ld-musl-") {
 174                has_musl = true;
 175            } else if file_name.starts_with("ld-linux-") {
 176                has_gnu = true;
 177            }
 178        }
 179
 180        match (has_musl, has_gnu) {
 181            (true, _) => LibcType::Musl,
 182            (_, true) => LibcType::Gnu,
 183            _ => LibcType::Gnu,
 184        }
 185    }
 186
 187    #[cfg(target_os = "linux")]
 188    async fn build_arch_server_name_linux() -> String {
 189        let libc = match Self::determine_libc_type().await {
 190            LibcType::Musl => "musl",
 191            LibcType::Gnu => "gnu",
 192        };
 193
 194        format!("{}-{}", Self::ARCH_SERVER_NAME, libc)
 195    }
 196
 197    async fn build_asset_name() -> String {
 198        let extension = match Self::GITHUB_ASSET_KIND {
 199            AssetKind::TarGz => "tar.gz",
 200            AssetKind::Gz => "gz",
 201            AssetKind::Zip => "zip",
 202        };
 203
 204        #[cfg(target_os = "linux")]
 205        let arch_server_name = Self::build_arch_server_name_linux().await;
 206        #[cfg(not(target_os = "linux"))]
 207        let arch_server_name = Self::ARCH_SERVER_NAME.to_string();
 208
 209        format!(
 210            "{}-{}-{}.{}",
 211            SERVER_NAME,
 212            std::env::consts::ARCH,
 213            &arch_server_name,
 214            extension
 215        )
 216    }
 217}
 218
 219pub(crate) struct CargoManifestProvider;
 220
 221impl ManifestProvider for CargoManifestProvider {
 222    fn name(&self) -> ManifestName {
 223        SharedString::new_static("Cargo.toml").into()
 224    }
 225
 226    fn search(
 227        &self,
 228        ManifestQuery {
 229            path,
 230            depth,
 231            delegate,
 232        }: ManifestQuery,
 233    ) -> Option<Arc<RelPath>> {
 234        let mut outermost_cargo_toml = None;
 235        for path in path.ancestors().take(depth) {
 236            let p = path.join(RelPath::unix("Cargo.toml").unwrap());
 237            if delegate.exists(&p, Some(false)) {
 238                outermost_cargo_toml = Some(Arc::from(path));
 239            }
 240        }
 241
 242        outermost_cargo_toml
 243    }
 244}
 245
 246#[async_trait(?Send)]
 247impl LspAdapter for RustLspAdapter {
 248    fn name(&self) -> LanguageServerName {
 249        SERVER_NAME
 250    }
 251
 252    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
 253        vec![CARGO_DIAGNOSTICS_SOURCE_NAME.to_owned()]
 254    }
 255
 256    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
 257        Some("rust-analyzer/flycheck".into())
 258    }
 259
 260    fn process_diagnostics(
 261        &self,
 262        params: &mut lsp::PublishDiagnosticsParams,
 263        _: LanguageServerId,
 264        _: Option<&'_ Buffer>,
 265    ) {
 266        static REGEX: LazyLock<Regex> =
 267            LazyLock::new(|| Regex::new(r"(?m)`([^`]+)\n`$").expect("Failed to create REGEX"));
 268
 269        for diagnostic in &mut params.diagnostics {
 270            for message in diagnostic
 271                .related_information
 272                .iter_mut()
 273                .flatten()
 274                .map(|info| &mut info.message)
 275                .chain([&mut diagnostic.message])
 276            {
 277                if let Cow::Owned(sanitized) = REGEX.replace_all(message, "`$1`") {
 278                    *message = sanitized;
 279                }
 280            }
 281        }
 282    }
 283
 284    fn diagnostic_message_to_markdown(&self, message: &str) -> Option<String> {
 285        static REGEX: LazyLock<Regex> =
 286            LazyLock::new(|| Regex::new(r"(?m)\n *").expect("Failed to create REGEX"));
 287        Some(REGEX.replace_all(message, "\n\n").to_string())
 288    }
 289
 290    async fn label_for_completion(
 291        &self,
 292        completion: &lsp::CompletionItem,
 293        language: &Arc<Language>,
 294    ) -> Option<CodeLabel> {
 295        // rust-analyzer calls these detail left and detail right in terms of where it expects things to be rendered
 296        // this usually contains signatures of the thing to be completed
 297        let detail_right = completion
 298            .label_details
 299            .as_ref()
 300            .and_then(|detail| detail.description.as_ref())
 301            .or(completion.detail.as_ref())
 302            .map(|detail| detail.trim());
 303        // this tends to contain alias and import information
 304        let mut detail_left = completion
 305            .label_details
 306            .as_ref()
 307            .and_then(|detail| detail.detail.as_deref());
 308        let mk_label = |text: String, filter_range: &dyn Fn() -> Range<usize>, runs| {
 309            let filter_range = completion
 310                .filter_text
 311                .as_deref()
 312                .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
 313                .or_else(|| {
 314                    text.find(&completion.label)
 315                        .map(|ix| ix..ix + completion.label.len())
 316                })
 317                .unwrap_or_else(filter_range);
 318
 319            CodeLabel::new(text, filter_range, runs)
 320        };
 321        let mut label = match (detail_right, completion.kind) {
 322            (Some(signature), Some(lsp::CompletionItemKind::FIELD)) => {
 323                let name = &completion.label;
 324                let text = format!("{name}: {signature}");
 325                let prefix = "struct S { ";
 326                let source = Rope::from_iter([prefix, &text, " }"]);
 327                let runs =
 328                    language.highlight_text(&source, prefix.len()..prefix.len() + text.len());
 329                mk_label(text, &|| 0..completion.label.len(), runs)
 330            }
 331            (
 332                Some(signature),
 333                Some(lsp::CompletionItemKind::CONSTANT | lsp::CompletionItemKind::VARIABLE),
 334            ) if completion.insert_text_format != Some(lsp::InsertTextFormat::SNIPPET) => {
 335                let name = &completion.label;
 336                let text = format!("{name}: {signature}",);
 337                let prefix = "let ";
 338                let source = Rope::from_iter([prefix, &text, " = ();"]);
 339                let runs =
 340                    language.highlight_text(&source, prefix.len()..prefix.len() + text.len());
 341                mk_label(text, &|| 0..completion.label.len(), runs)
 342            }
 343            (
 344                function_signature,
 345                Some(lsp::CompletionItemKind::FUNCTION | lsp::CompletionItemKind::METHOD),
 346            ) => {
 347                const FUNCTION_PREFIXES: [&str; 6] = [
 348                    "async fn",
 349                    "async unsafe fn",
 350                    "const fn",
 351                    "const unsafe fn",
 352                    "unsafe fn",
 353                    "fn",
 354                ];
 355                let fn_prefixed = FUNCTION_PREFIXES.iter().find_map(|&prefix| {
 356                    function_signature?
 357                        .strip_prefix(prefix)
 358                        .map(|suffix| (prefix, suffix))
 359                });
 360                let label = if let Some(label) = completion
 361                    .label
 362                    .strip_suffix("(…)")
 363                    .or_else(|| completion.label.strip_suffix("()"))
 364                {
 365                    label
 366                } else {
 367                    &completion.label
 368                };
 369
 370                static FULL_SIGNATURE_REGEX: LazyLock<Regex> =
 371                    LazyLock::new(|| Regex::new(r"fn (.?+)\(").expect("Failed to create REGEX"));
 372                if let Some((function_signature, match_)) = function_signature
 373                    .filter(|it| it.contains(&label))
 374                    .and_then(|it| Some((it, FULL_SIGNATURE_REGEX.find(it)?)))
 375                {
 376                    let source = Rope::from(function_signature);
 377                    let runs = language.highlight_text(&source, 0..function_signature.len());
 378                    mk_label(
 379                        function_signature.to_owned(),
 380                        &|| match_.range().start - 3..match_.range().end - 1,
 381                        runs,
 382                    )
 383                } else if let Some((prefix, suffix)) = fn_prefixed {
 384                    let text = format!("{label}{suffix}");
 385                    let source = Rope::from_iter([prefix, " ", &text, " {}"]);
 386                    let run_start = prefix.len() + 1;
 387                    let runs = language.highlight_text(&source, run_start..run_start + text.len());
 388                    mk_label(text, &|| 0..label.len(), runs)
 389                } else if completion
 390                    .detail
 391                    .as_ref()
 392                    .is_some_and(|detail| detail.starts_with("macro_rules! "))
 393                {
 394                    let text = completion.label.clone();
 395                    let len = text.len();
 396                    let source = Rope::from(text.as_str());
 397                    let runs = language.highlight_text(&source, 0..len);
 398                    mk_label(text, &|| 0..completion.label.len(), runs)
 399                } else if detail_left.is_none() {
 400                    return None;
 401                } else {
 402                    mk_label(
 403                        completion.label.clone(),
 404                        &|| 0..completion.label.len(),
 405                        vec![],
 406                    )
 407                }
 408            }
 409            (_, kind) => {
 410                let mut label;
 411                let mut runs = vec![];
 412
 413                if completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
 414                    && let Some(
 415                        lsp::CompletionTextEdit::InsertAndReplace(lsp::InsertReplaceEdit {
 416                            new_text,
 417                            ..
 418                        })
 419                        | lsp::CompletionTextEdit::Edit(lsp::TextEdit { new_text, .. }),
 420                    ) = completion.text_edit.as_ref()
 421                    && let Ok(mut snippet) = snippet::Snippet::parse(new_text)
 422                    && snippet.tabstops.len() > 1
 423                {
 424                    label = String::new();
 425
 426                    // we never display the final tabstop
 427                    snippet.tabstops.remove(snippet.tabstops.len() - 1);
 428
 429                    let mut text_pos = 0;
 430
 431                    let mut all_stop_ranges = snippet
 432                        .tabstops
 433                        .into_iter()
 434                        .flat_map(|stop| stop.ranges)
 435                        .collect::<SmallVec<[_; 8]>>();
 436                    all_stop_ranges.sort_unstable_by_key(|a| (a.start, Reverse(a.end)));
 437
 438                    for range in &all_stop_ranges {
 439                        let start_pos = range.start as usize;
 440                        let end_pos = range.end as usize;
 441
 442                        label.push_str(&snippet.text[text_pos..start_pos]);
 443
 444                        if start_pos == end_pos {
 445                            let caret_start = label.len();
 446                            label.push('…');
 447                            runs.push((caret_start..label.len(), HighlightId::TABSTOP_INSERT_ID));
 448                        } else {
 449                            let label_start = label.len();
 450                            label.push_str(&snippet.text[start_pos..end_pos]);
 451                            let label_end = label.len();
 452                            runs.push((label_start..label_end, HighlightId::TABSTOP_REPLACE_ID));
 453                        }
 454
 455                        text_pos = end_pos;
 456                    }
 457
 458                    label.push_str(&snippet.text[text_pos..]);
 459
 460                    if detail_left.is_some_and(|detail_left| detail_left == new_text) {
 461                        // We only include the left detail if it isn't the snippet again
 462                        detail_left.take();
 463                    }
 464
 465                    runs.extend(language.highlight_text(&Rope::from(&label), 0..label.len()));
 466                } else {
 467                    let highlight_name = kind.and_then(|kind| match kind {
 468                        lsp::CompletionItemKind::STRUCT
 469                        | lsp::CompletionItemKind::INTERFACE
 470                        | lsp::CompletionItemKind::ENUM => Some("type"),
 471                        lsp::CompletionItemKind::ENUM_MEMBER => Some("variant"),
 472                        lsp::CompletionItemKind::KEYWORD => Some("keyword"),
 473                        lsp::CompletionItemKind::VALUE | lsp::CompletionItemKind::CONSTANT => {
 474                            Some("constant")
 475                        }
 476                        _ => None,
 477                    });
 478
 479                    label = completion.label.clone();
 480
 481                    if let Some(highlight_name) = highlight_name {
 482                        let highlight_id =
 483                            language.grammar()?.highlight_id_for_name(highlight_name)?;
 484                        runs.push((
 485                            0..label.rfind('(').unwrap_or(completion.label.len()),
 486                            highlight_id,
 487                        ));
 488                    } else if detail_left.is_none()
 489                        && kind != Some(lsp::CompletionItemKind::SNIPPET)
 490                    {
 491                        return None;
 492                    }
 493                }
 494
 495                let label_len = label.len();
 496
 497                mk_label(label, &|| 0..label_len, runs)
 498            }
 499        };
 500
 501        if let Some(detail_left) = detail_left {
 502            label.text.push(' ');
 503            if !detail_left.starts_with('(') {
 504                label.text.push('(');
 505            }
 506            label.text.push_str(detail_left);
 507            if !detail_left.ends_with(')') {
 508                label.text.push(')');
 509            }
 510        }
 511
 512        Some(label)
 513    }
 514
 515    async fn initialization_options_schema(
 516        self: Arc<Self>,
 517        delegate: &Arc<dyn LspAdapterDelegate>,
 518        cached_binary: OwnedMutexGuard<Option<(bool, LanguageServerBinary)>>,
 519        cx: &mut AsyncApp,
 520    ) -> Option<serde_json::Value> {
 521        let binary = self
 522            .get_language_server_command(
 523                delegate.clone(),
 524                None,
 525                LanguageServerBinaryOptions {
 526                    allow_path_lookup: true,
 527                    allow_binary_download: false,
 528                    pre_release: false,
 529                },
 530                cached_binary,
 531                cx.clone(),
 532            )
 533            .await
 534            .0
 535            .ok()?;
 536
 537        let mut command = util::command::new_smol_command(&binary.path);
 538        command
 539            .arg("--print-config-schema")
 540            .stdout(Stdio::piped())
 541            .stderr(Stdio::piped());
 542        let cmd = command
 543            .spawn()
 544            .map_err(|e| log::debug!("failed to spawn command {command:?}: {e}"))
 545            .ok()?;
 546        let output = cmd
 547            .output()
 548            .await
 549            .map_err(|e| log::debug!("failed to execute command {command:?}: {e}"))
 550            .ok()?;
 551        if !output.status.success() {
 552            return None;
 553        }
 554
 555        let raw_schema: serde_json::Value = serde_json::from_slice(output.stdout.as_slice())
 556            .map_err(|e| log::debug!("failed to parse rust-analyzer's JSON schema output: {e}"))
 557            .ok()?;
 558
 559        // Convert rust-analyzer's array-based schema format to nested JSON Schema
 560        let converted_schema = Self::convert_rust_analyzer_schema(&raw_schema);
 561        Some(converted_schema)
 562    }
 563
 564    async fn label_for_symbol(
 565        &self,
 566        name: &str,
 567        kind: lsp::SymbolKind,
 568        language: &Arc<Language>,
 569    ) -> Option<CodeLabel> {
 570        let (prefix, suffix) = match kind {
 571            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => ("fn ", "();"),
 572            lsp::SymbolKind::STRUCT => ("struct ", ";"),
 573            lsp::SymbolKind::ENUM => ("enum ", "{}"),
 574            lsp::SymbolKind::INTERFACE => ("trait ", "{}"),
 575            lsp::SymbolKind::CONSTANT => ("const ", ":()=();"),
 576            lsp::SymbolKind::MODULE => ("mod ", ";"),
 577            lsp::SymbolKind::PACKAGE => ("extern crate ", ";"),
 578            lsp::SymbolKind::TYPE_PARAMETER => ("type ", "=();"),
 579            lsp::SymbolKind::ENUM_MEMBER => {
 580                let prefix = "enum E {";
 581                return Some(CodeLabel::new(
 582                    name.to_string(),
 583                    0..name.len(),
 584                    language.highlight_text(
 585                        &Rope::from_iter([prefix, name, "}"]),
 586                        prefix.len()..prefix.len() + name.len(),
 587                    ),
 588                ));
 589            }
 590            _ => return None,
 591        };
 592
 593        let filter_range = prefix.len()..prefix.len() + name.len();
 594        let display_range = 0..filter_range.end;
 595        Some(CodeLabel::new(
 596            format!("{prefix}{name}"),
 597            filter_range,
 598            language.highlight_text(&Rope::from_iter([prefix, name, suffix]), display_range),
 599        ))
 600    }
 601
 602    fn prepare_initialize_params(
 603        &self,
 604        mut original: InitializeParams,
 605        cx: &App,
 606    ) -> Result<InitializeParams> {
 607        let enable_lsp_tasks = ProjectSettings::get_global(cx)
 608            .lsp
 609            .get(&SERVER_NAME)
 610            .is_some_and(|s| s.enable_lsp_tasks);
 611        if enable_lsp_tasks {
 612            let experimental = json!({
 613                "runnables": {
 614                    "kinds": [ "cargo", "shell" ],
 615                },
 616            });
 617            if let Some(original_experimental) = &mut original.capabilities.experimental {
 618                merge_json_value_into(experimental, original_experimental);
 619            } else {
 620                original.capabilities.experimental = Some(experimental);
 621            }
 622        }
 623
 624        Ok(original)
 625    }
 626}
 627
 628impl LspInstaller for RustLspAdapter {
 629    type BinaryVersion = GitHubLspBinaryVersion;
 630    async fn check_if_user_installed(
 631        &self,
 632        delegate: &dyn LspAdapterDelegate,
 633        _: Option<Toolchain>,
 634        _: &AsyncApp,
 635    ) -> Option<LanguageServerBinary> {
 636        let path = delegate.which("rust-analyzer".as_ref()).await?;
 637        let env = delegate.shell_env().await;
 638
 639        // It is surprisingly common for ~/.cargo/bin/rust-analyzer to be a symlink to
 640        // /usr/bin/rust-analyzer that fails when you run it; so we need to test it.
 641        log::debug!("found rust-analyzer in PATH. trying to run `rust-analyzer --help`");
 642        let result = delegate
 643            .try_exec(LanguageServerBinary {
 644                path: path.clone(),
 645                arguments: vec!["--help".into()],
 646                env: Some(env.clone()),
 647            })
 648            .await;
 649        if let Err(err) = result {
 650            log::debug!(
 651                "failed to run rust-analyzer after detecting it in PATH: binary: {:?}: {}",
 652                path,
 653                err
 654            );
 655            return None;
 656        }
 657
 658        Some(LanguageServerBinary {
 659            path,
 660            env: Some(env),
 661            arguments: vec![],
 662        })
 663    }
 664
 665    async fn fetch_latest_server_version(
 666        &self,
 667        delegate: &dyn LspAdapterDelegate,
 668        pre_release: bool,
 669        _: &mut AsyncApp,
 670    ) -> Result<GitHubLspBinaryVersion> {
 671        let release = latest_github_release(
 672            "rust-lang/rust-analyzer",
 673            true,
 674            pre_release,
 675            delegate.http_client(),
 676        )
 677        .await?;
 678        let asset_name = Self::build_asset_name().await;
 679        let asset = release
 680            .assets
 681            .into_iter()
 682            .find(|asset| asset.name == asset_name)
 683            .with_context(|| format!("no asset found matching `{asset_name:?}`"))?;
 684        Ok(GitHubLspBinaryVersion {
 685            name: release.tag_name,
 686            url: asset.browser_download_url,
 687            digest: asset.digest,
 688        })
 689    }
 690
 691    async fn fetch_server_binary(
 692        &self,
 693        version: GitHubLspBinaryVersion,
 694        container_dir: PathBuf,
 695        delegate: &dyn LspAdapterDelegate,
 696    ) -> Result<LanguageServerBinary> {
 697        let GitHubLspBinaryVersion {
 698            name,
 699            url,
 700            digest: expected_digest,
 701        } = version;
 702        let destination_path = container_dir.join(format!("rust-analyzer-{name}"));
 703        let server_path = match Self::GITHUB_ASSET_KIND {
 704            AssetKind::TarGz | AssetKind::Gz => destination_path.clone(), // Tar and gzip extract in place.
 705            AssetKind::Zip => destination_path.clone().join("rust-analyzer.exe"), // zip contains a .exe
 706        };
 707
 708        let binary = LanguageServerBinary {
 709            path: server_path.clone(),
 710            env: None,
 711            arguments: Default::default(),
 712        };
 713
 714        let metadata_path = destination_path.with_extension("metadata");
 715        let metadata = GithubBinaryMetadata::read_from_file(&metadata_path)
 716            .await
 717            .ok();
 718        if let Some(metadata) = metadata {
 719            let validity_check = async || {
 720                delegate
 721                    .try_exec(LanguageServerBinary {
 722                        path: server_path.clone(),
 723                        arguments: vec!["--version".into()],
 724                        env: None,
 725                    })
 726                    .await
 727                    .inspect_err(|err| {
 728                        log::warn!("Unable to run {server_path:?} asset, redownloading: {err:#}",)
 729                    })
 730            };
 731            if let (Some(actual_digest), Some(expected_digest)) =
 732                (&metadata.digest, &expected_digest)
 733            {
 734                if actual_digest == expected_digest {
 735                    if validity_check().await.is_ok() {
 736                        return Ok(binary);
 737                    }
 738                } else {
 739                    log::info!(
 740                        "SHA-256 mismatch for {destination_path:?} asset, downloading new asset. Expected: {expected_digest}, Got: {actual_digest}"
 741                    );
 742                }
 743            } else if validity_check().await.is_ok() {
 744                return Ok(binary);
 745            }
 746        }
 747
 748        download_server_binary(
 749            &*delegate.http_client(),
 750            &url,
 751            expected_digest.as_deref(),
 752            &destination_path,
 753            Self::GITHUB_ASSET_KIND,
 754        )
 755        .await?;
 756        make_file_executable(&server_path).await?;
 757        remove_matching(&container_dir, |path| path != destination_path).await;
 758        GithubBinaryMetadata::write_to_file(
 759            &GithubBinaryMetadata {
 760                metadata_version: 1,
 761                digest: expected_digest,
 762            },
 763            &metadata_path,
 764        )
 765        .await?;
 766
 767        Ok(LanguageServerBinary {
 768            path: server_path,
 769            env: None,
 770            arguments: Default::default(),
 771        })
 772    }
 773
 774    async fn cached_server_binary(
 775        &self,
 776        container_dir: PathBuf,
 777        _: &dyn LspAdapterDelegate,
 778    ) -> Option<LanguageServerBinary> {
 779        get_cached_server_binary(container_dir).await
 780    }
 781}
 782
 783pub(crate) struct RustContextProvider;
 784
 785const RUST_PACKAGE_TASK_VARIABLE: VariableName =
 786    VariableName::Custom(Cow::Borrowed("RUST_PACKAGE"));
 787
 788/// The bin name corresponding to the current file in Cargo.toml
 789const RUST_BIN_NAME_TASK_VARIABLE: VariableName =
 790    VariableName::Custom(Cow::Borrowed("RUST_BIN_NAME"));
 791
 792/// The bin kind (bin/example) corresponding to the current file in Cargo.toml
 793const RUST_BIN_KIND_TASK_VARIABLE: VariableName =
 794    VariableName::Custom(Cow::Borrowed("RUST_BIN_KIND"));
 795
 796/// The flag to list required features for executing a bin, if any
 797const RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE: VariableName =
 798    VariableName::Custom(Cow::Borrowed("RUST_BIN_REQUIRED_FEATURES_FLAG"));
 799
 800/// The list of required features for executing a bin, if any
 801const RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE: VariableName =
 802    VariableName::Custom(Cow::Borrowed("RUST_BIN_REQUIRED_FEATURES"));
 803
 804const RUST_TEST_FRAGMENT_TASK_VARIABLE: VariableName =
 805    VariableName::Custom(Cow::Borrowed("RUST_TEST_FRAGMENT"));
 806
 807const RUST_DOC_TEST_NAME_TASK_VARIABLE: VariableName =
 808    VariableName::Custom(Cow::Borrowed("RUST_DOC_TEST_NAME"));
 809
 810const RUST_TEST_NAME_TASK_VARIABLE: VariableName =
 811    VariableName::Custom(Cow::Borrowed("RUST_TEST_NAME"));
 812
 813const RUST_MANIFEST_DIRNAME_TASK_VARIABLE: VariableName =
 814    VariableName::Custom(Cow::Borrowed("RUST_MANIFEST_DIRNAME"));
 815
 816impl ContextProvider for RustContextProvider {
 817    fn build_context(
 818        &self,
 819        task_variables: &TaskVariables,
 820        location: ContextLocation<'_>,
 821        project_env: Option<HashMap<String, String>>,
 822        _: Arc<dyn LanguageToolchainStore>,
 823        cx: &mut gpui::App,
 824    ) -> Task<Result<TaskVariables>> {
 825        let local_abs_path = location
 826            .file_location
 827            .buffer
 828            .read(cx)
 829            .file()
 830            .and_then(|file| Some(file.as_local()?.abs_path(cx)));
 831
 832        let mut variables = TaskVariables::default();
 833
 834        if let (Some(path), Some(stem)) = (&local_abs_path, task_variables.get(&VariableName::Stem))
 835        {
 836            let fragment = test_fragment(&variables, path, stem);
 837            variables.insert(RUST_TEST_FRAGMENT_TASK_VARIABLE, fragment);
 838        };
 839        if let Some(test_name) =
 840            task_variables.get(&VariableName::Custom(Cow::Borrowed("_test_name")))
 841        {
 842            variables.insert(RUST_TEST_NAME_TASK_VARIABLE, test_name.into());
 843        }
 844        if let Some(doc_test_name) =
 845            task_variables.get(&VariableName::Custom(Cow::Borrowed("_doc_test_name")))
 846        {
 847            variables.insert(RUST_DOC_TEST_NAME_TASK_VARIABLE, doc_test_name.into());
 848        }
 849        cx.background_spawn(async move {
 850            if let Some(path) = local_abs_path
 851                .as_deref()
 852                .and_then(|local_abs_path| local_abs_path.parent())
 853                && let Some(package_name) =
 854                    human_readable_package_name(path, project_env.as_ref()).await
 855            {
 856                variables.insert(RUST_PACKAGE_TASK_VARIABLE.clone(), package_name);
 857            }
 858            if let Some(path) = local_abs_path.as_ref()
 859                && let Some((target, manifest_path)) =
 860                    target_info_from_abs_path(path, project_env.as_ref()).await
 861            {
 862                if let Some(target) = target {
 863                    variables.extend(TaskVariables::from_iter([
 864                        (RUST_PACKAGE_TASK_VARIABLE.clone(), target.package_name),
 865                        (RUST_BIN_NAME_TASK_VARIABLE.clone(), target.target_name),
 866                        (
 867                            RUST_BIN_KIND_TASK_VARIABLE.clone(),
 868                            target.target_kind.to_string(),
 869                        ),
 870                    ]));
 871                    if target.required_features.is_empty() {
 872                        variables.insert(RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE, "".into());
 873                        variables.insert(RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE, "".into());
 874                    } else {
 875                        variables.insert(
 876                            RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE.clone(),
 877                            "--features".to_string(),
 878                        );
 879                        variables.insert(
 880                            RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE.clone(),
 881                            target.required_features.join(","),
 882                        );
 883                    }
 884                }
 885                variables.extend(TaskVariables::from_iter([(
 886                    RUST_MANIFEST_DIRNAME_TASK_VARIABLE.clone(),
 887                    manifest_path.to_string_lossy().into_owned(),
 888                )]));
 889            }
 890            Ok(variables)
 891        })
 892    }
 893
 894    fn associated_tasks(
 895        &self,
 896        buffer: Option<Entity<Buffer>>,
 897        cx: &App,
 898    ) -> Task<Option<TaskTemplates>> {
 899        const DEFAULT_RUN_NAME_STR: &str = "RUST_DEFAULT_PACKAGE_RUN";
 900        const CUSTOM_TARGET_DIR: &str = "RUST_TARGET_DIR";
 901
 902        let language = LanguageName::new_static("Rust");
 903        let settings = LanguageSettings::resolve(buffer.map(|b| b.read(cx)), Some(&language), cx);
 904        let package_to_run = settings.tasks.variables.get(DEFAULT_RUN_NAME_STR).cloned();
 905        let custom_target_dir = settings.tasks.variables.get(CUSTOM_TARGET_DIR).cloned();
 906        let run_task_args = if let Some(package_to_run) = package_to_run {
 907            vec!["run".into(), "-p".into(), package_to_run]
 908        } else {
 909            vec!["run".into()]
 910        };
 911        let mut task_templates = vec![
 912            TaskTemplate {
 913                label: format!(
 914                    "Check (package: {})",
 915                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 916                ),
 917                command: "cargo".into(),
 918                args: vec![
 919                    "check".into(),
 920                    "-p".into(),
 921                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 922                ],
 923                cwd: Some("$ZED_DIRNAME".to_owned()),
 924                ..TaskTemplate::default()
 925            },
 926            TaskTemplate {
 927                label: "Check all targets (workspace)".into(),
 928                command: "cargo".into(),
 929                args: vec!["check".into(), "--workspace".into(), "--all-targets".into()],
 930                cwd: Some("$ZED_DIRNAME".to_owned()),
 931                ..TaskTemplate::default()
 932            },
 933            TaskTemplate {
 934                label: format!(
 935                    "Test '{}' (package: {})",
 936                    RUST_TEST_NAME_TASK_VARIABLE.template_value(),
 937                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 938                ),
 939                command: "cargo".into(),
 940                args: vec![
 941                    "test".into(),
 942                    "-p".into(),
 943                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 944                    "--".into(),
 945                    "--nocapture".into(),
 946                    "--include-ignored".into(),
 947                    RUST_TEST_NAME_TASK_VARIABLE.template_value(),
 948                ],
 949                tags: vec!["rust-test".to_owned()],
 950                cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
 951                ..TaskTemplate::default()
 952            },
 953            TaskTemplate {
 954                label: format!(
 955                    "Doc test '{}' (package: {})",
 956                    RUST_DOC_TEST_NAME_TASK_VARIABLE.template_value(),
 957                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 958                ),
 959                command: "cargo".into(),
 960                args: vec![
 961                    "test".into(),
 962                    "--doc".into(),
 963                    "-p".into(),
 964                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 965                    "--".into(),
 966                    "--nocapture".into(),
 967                    "--include-ignored".into(),
 968                    RUST_DOC_TEST_NAME_TASK_VARIABLE.template_value(),
 969                ],
 970                tags: vec!["rust-doc-test".to_owned()],
 971                cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
 972                ..TaskTemplate::default()
 973            },
 974            TaskTemplate {
 975                label: format!(
 976                    "Test mod '{}' (package: {})",
 977                    VariableName::Stem.template_value(),
 978                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 979                ),
 980                command: "cargo".into(),
 981                args: vec![
 982                    "test".into(),
 983                    "-p".into(),
 984                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 985                    "--".into(),
 986                    RUST_TEST_FRAGMENT_TASK_VARIABLE.template_value(),
 987                ],
 988                tags: vec!["rust-mod-test".to_owned()],
 989                cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
 990                ..TaskTemplate::default()
 991            },
 992            TaskTemplate {
 993                label: format!(
 994                    "Run {} {} (package: {})",
 995                    RUST_BIN_KIND_TASK_VARIABLE.template_value(),
 996                    RUST_BIN_NAME_TASK_VARIABLE.template_value(),
 997                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 998                ),
 999                command: "cargo".into(),
1000                args: vec![
1001                    "run".into(),
1002                    "-p".into(),
1003                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
1004                    format!("--{}", RUST_BIN_KIND_TASK_VARIABLE.template_value()),
1005                    RUST_BIN_NAME_TASK_VARIABLE.template_value(),
1006                    RUST_BIN_REQUIRED_FEATURES_FLAG_TASK_VARIABLE.template_value(),
1007                    RUST_BIN_REQUIRED_FEATURES_TASK_VARIABLE.template_value(),
1008                ],
1009                cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
1010                tags: vec!["rust-main".to_owned()],
1011                ..TaskTemplate::default()
1012            },
1013            TaskTemplate {
1014                label: format!(
1015                    "Test (package: {})",
1016                    RUST_PACKAGE_TASK_VARIABLE.template_value()
1017                ),
1018                command: "cargo".into(),
1019                args: vec![
1020                    "test".into(),
1021                    "-p".into(),
1022                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
1023                ],
1024                cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
1025                ..TaskTemplate::default()
1026            },
1027            TaskTemplate {
1028                label: "Run".into(),
1029                command: "cargo".into(),
1030                args: run_task_args,
1031                cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
1032                ..TaskTemplate::default()
1033            },
1034            TaskTemplate {
1035                label: "Clean".into(),
1036                command: "cargo".into(),
1037                args: vec!["clean".into()],
1038                cwd: Some(RUST_MANIFEST_DIRNAME_TASK_VARIABLE.template_value()),
1039                ..TaskTemplate::default()
1040            },
1041        ];
1042
1043        if let Some(custom_target_dir) = custom_target_dir {
1044            task_templates = task_templates
1045                .into_iter()
1046                .map(|mut task_template| {
1047                    let mut args = task_template.args.split_off(1);
1048                    task_template.args.append(&mut vec![
1049                        "--target-dir".to_string(),
1050                        custom_target_dir.clone(),
1051                    ]);
1052                    task_template.args.append(&mut args);
1053
1054                    task_template
1055                })
1056                .collect();
1057        }
1058
1059        Task::ready(Some(TaskTemplates(task_templates)))
1060    }
1061
1062    fn lsp_task_source(&self) -> Option<LanguageServerName> {
1063        Some(SERVER_NAME)
1064    }
1065}
1066
1067/// Part of the data structure of Cargo metadata
1068#[derive(Debug, serde::Deserialize)]
1069struct CargoMetadata {
1070    packages: Vec<CargoPackage>,
1071}
1072
1073#[derive(Debug, serde::Deserialize)]
1074struct CargoPackage {
1075    id: String,
1076    targets: Vec<CargoTarget>,
1077    manifest_path: Arc<Path>,
1078}
1079
1080#[derive(Debug, serde::Deserialize)]
1081struct CargoTarget {
1082    name: String,
1083    kind: Vec<String>,
1084    src_path: String,
1085    #[serde(rename = "required-features", default)]
1086    required_features: Vec<String>,
1087}
1088
1089#[derive(Debug, PartialEq)]
1090enum TargetKind {
1091    Bin,
1092    Example,
1093}
1094
1095impl Display for TargetKind {
1096    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1097        match self {
1098            TargetKind::Bin => write!(f, "bin"),
1099            TargetKind::Example => write!(f, "example"),
1100        }
1101    }
1102}
1103
1104impl TryFrom<&str> for TargetKind {
1105    type Error = ();
1106    fn try_from(value: &str) -> Result<Self, ()> {
1107        match value {
1108            "bin" => Ok(Self::Bin),
1109            "example" => Ok(Self::Example),
1110            _ => Err(()),
1111        }
1112    }
1113}
1114/// Which package and binary target are we in?
1115#[derive(Debug, PartialEq)]
1116struct TargetInfo {
1117    package_name: String,
1118    target_name: String,
1119    target_kind: TargetKind,
1120    required_features: Vec<String>,
1121}
1122
1123async fn target_info_from_abs_path(
1124    abs_path: &Path,
1125    project_env: Option<&HashMap<String, String>>,
1126) -> Option<(Option<TargetInfo>, Arc<Path>)> {
1127    let mut command = util::command::new_smol_command("cargo");
1128    if let Some(envs) = project_env {
1129        command.envs(envs);
1130    }
1131    let output = command
1132        .current_dir(abs_path.parent()?)
1133        .arg("metadata")
1134        .arg("--no-deps")
1135        .arg("--format-version")
1136        .arg("1")
1137        .output()
1138        .await
1139        .log_err()?
1140        .stdout;
1141
1142    let metadata: CargoMetadata = serde_json::from_slice(&output).log_err()?;
1143    target_info_from_metadata(metadata, abs_path)
1144}
1145
1146fn target_info_from_metadata(
1147    metadata: CargoMetadata,
1148    abs_path: &Path,
1149) -> Option<(Option<TargetInfo>, Arc<Path>)> {
1150    let mut manifest_path = None;
1151    for package in metadata.packages {
1152        let Some(manifest_dir_path) = package.manifest_path.parent() else {
1153            continue;
1154        };
1155
1156        let Some(path_from_manifest_dir) = abs_path.strip_prefix(manifest_dir_path).ok() else {
1157            continue;
1158        };
1159        let candidate_path_length = path_from_manifest_dir.components().count();
1160        // Pick the most specific manifest path
1161        if let Some((path, current_length)) = &mut manifest_path {
1162            if candidate_path_length > *current_length {
1163                *path = Arc::from(manifest_dir_path);
1164                *current_length = candidate_path_length;
1165            }
1166        } else {
1167            manifest_path = Some((Arc::from(manifest_dir_path), candidate_path_length));
1168        };
1169
1170        for target in package.targets {
1171            let Some(bin_kind) = target
1172                .kind
1173                .iter()
1174                .find_map(|kind| TargetKind::try_from(kind.as_ref()).ok())
1175            else {
1176                continue;
1177            };
1178            let target_path = PathBuf::from(target.src_path);
1179            if target_path == abs_path {
1180                return manifest_path.map(|(path, _)| {
1181                    (
1182                        package_name_from_pkgid(&package.id).map(|package_name| TargetInfo {
1183                            package_name: package_name.to_owned(),
1184                            target_name: target.name,
1185                            required_features: target.required_features,
1186                            target_kind: bin_kind,
1187                        }),
1188                        path,
1189                    )
1190                });
1191            }
1192        }
1193    }
1194
1195    manifest_path.map(|(path, _)| (None, path))
1196}
1197
1198async fn human_readable_package_name(
1199    package_directory: &Path,
1200    project_env: Option<&HashMap<String, String>>,
1201) -> Option<String> {
1202    let mut command = util::command::new_smol_command("cargo");
1203    if let Some(envs) = project_env {
1204        command.envs(envs);
1205    }
1206    let pkgid = String::from_utf8(
1207        command
1208            .current_dir(package_directory)
1209            .arg("pkgid")
1210            .output()
1211            .await
1212            .log_err()?
1213            .stdout,
1214    )
1215    .ok()?;
1216    Some(package_name_from_pkgid(&pkgid)?.to_owned())
1217}
1218
1219// For providing local `cargo check -p $pkgid` task, we do not need most of the information we have returned.
1220// Output example in the root of Zed project:
1221// ```sh
1222// ❯ cargo pkgid zed
1223// path+file:///absolute/path/to/project/zed/crates/zed#0.131.0
1224// ```
1225// Another variant, if a project has a custom package name or hyphen in the name:
1226// ```
1227// path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0
1228// ```
1229//
1230// Extracts the package name from the output according to the spec:
1231// https://doc.rust-lang.org/cargo/reference/pkgid-spec.html#specification-grammar
1232fn package_name_from_pkgid(pkgid: &str) -> Option<&str> {
1233    fn split_off_suffix(input: &str, suffix_start: char) -> &str {
1234        match input.rsplit_once(suffix_start) {
1235            Some((without_suffix, _)) => without_suffix,
1236            None => input,
1237        }
1238    }
1239
1240    let (version_prefix, version_suffix) = pkgid.trim().rsplit_once('#')?;
1241    let package_name = match version_suffix.rsplit_once('@') {
1242        Some((custom_package_name, _version)) => custom_package_name,
1243        None => {
1244            let host_and_path = split_off_suffix(version_prefix, '?');
1245            let (_, package_name) = host_and_path.rsplit_once('/')?;
1246            package_name
1247        }
1248    };
1249    Some(package_name)
1250}
1251
1252async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
1253    let binary_result = maybe!(async {
1254        let mut last = None;
1255        let mut entries = fs::read_dir(&container_dir)
1256            .await
1257            .with_context(|| format!("listing {container_dir:?}"))?;
1258        while let Some(entry) = entries.next().await {
1259            let path = entry?.path();
1260            if path.extension().is_some_and(|ext| ext == "metadata") {
1261                continue;
1262            }
1263            last = Some(path);
1264        }
1265
1266        let path = match last {
1267            Some(last) => last,
1268            None => return Ok(None),
1269        };
1270        let path = match RustLspAdapter::GITHUB_ASSET_KIND {
1271            AssetKind::TarGz | AssetKind::Gz => path, // Tar and gzip extract in place.
1272            AssetKind::Zip => path.join("rust-analyzer.exe"), // zip contains a .exe
1273        };
1274
1275        anyhow::Ok(Some(LanguageServerBinary {
1276            path,
1277            env: None,
1278            arguments: Vec::new(),
1279        }))
1280    })
1281    .await;
1282
1283    match binary_result {
1284        Ok(Some(binary)) => Some(binary),
1285        Ok(None) => {
1286            log::info!("No cached rust-analyzer binary found");
1287            None
1288        }
1289        Err(e) => {
1290            log::error!("Failed to look up cached rust-analyzer binary: {e:#}");
1291            None
1292        }
1293    }
1294}
1295
1296fn test_fragment(variables: &TaskVariables, path: &Path, stem: &str) -> String {
1297    let fragment = if stem == "lib" {
1298        // This isn't quite right---it runs the tests for the entire library, rather than
1299        // just for the top-level `mod tests`. But we don't really have the means here to
1300        // filter out just that module.
1301        Some("--lib".to_owned())
1302    } else if stem == "mod" {
1303        maybe!({ Some(path.parent()?.file_name()?.to_string_lossy().into_owned()) })
1304    } else if stem == "main" {
1305        if let (Some(bin_name), Some(bin_kind)) = (
1306            variables.get(&RUST_BIN_NAME_TASK_VARIABLE),
1307            variables.get(&RUST_BIN_KIND_TASK_VARIABLE),
1308        ) {
1309            Some(format!("--{bin_kind}={bin_name}"))
1310        } else {
1311            None
1312        }
1313    } else {
1314        Some(stem.to_owned())
1315    };
1316    fragment.unwrap_or_else(|| "--".to_owned())
1317}
1318
1319#[cfg(test)]
1320mod tests {
1321    use std::num::NonZeroU32;
1322
1323    use super::*;
1324    use crate::language;
1325    use gpui::{BorrowAppContext, Hsla, TestAppContext};
1326    use lsp::CompletionItemLabelDetails;
1327    use settings::SettingsStore;
1328    use theme::SyntaxTheme;
1329    use util::path;
1330
1331    #[gpui::test]
1332    async fn test_process_rust_diagnostics() {
1333        let mut params = lsp::PublishDiagnosticsParams {
1334            uri: lsp::Uri::from_file_path(path!("/a")).unwrap(),
1335            version: None,
1336            diagnostics: vec![
1337                // no newlines
1338                lsp::Diagnostic {
1339                    message: "use of moved value `a`".to_string(),
1340                    ..Default::default()
1341                },
1342                // newline at the end of a code span
1343                lsp::Diagnostic {
1344                    message: "consider importing this struct: `use b::c;\n`".to_string(),
1345                    ..Default::default()
1346                },
1347                // code span starting right after a newline
1348                lsp::Diagnostic {
1349                    message: "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
1350                        .to_string(),
1351                    ..Default::default()
1352                },
1353            ],
1354        };
1355        RustLspAdapter.process_diagnostics(&mut params, LanguageServerId(0), None);
1356
1357        assert_eq!(params.diagnostics[0].message, "use of moved value `a`");
1358
1359        // remove trailing newline from code span
1360        assert_eq!(
1361            params.diagnostics[1].message,
1362            "consider importing this struct: `use b::c;`"
1363        );
1364
1365        // do not remove newline before the start of code span
1366        assert_eq!(
1367            params.diagnostics[2].message,
1368            "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
1369        );
1370    }
1371
1372    #[gpui::test]
1373    async fn test_rust_label_for_completion() {
1374        let adapter = Arc::new(RustLspAdapter);
1375        let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1376        let grammar = language.grammar().unwrap();
1377        let theme = SyntaxTheme::new_test([
1378            ("type", Hsla::default()),
1379            ("keyword", Hsla::default()),
1380            ("function", Hsla::default()),
1381            ("property", Hsla::default()),
1382        ]);
1383
1384        language.set_theme(&theme);
1385
1386        let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1387        let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1388        let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1389        let highlight_field = grammar.highlight_id_for_name("property").unwrap();
1390
1391        assert_eq!(
1392            adapter
1393                .label_for_completion(
1394                    &lsp::CompletionItem {
1395                        kind: Some(lsp::CompletionItemKind::FUNCTION),
1396                        label: "hello(…)".to_string(),
1397                        label_details: Some(CompletionItemLabelDetails {
1398                            detail: Some("(use crate::foo)".into()),
1399                            description: Some("fn(&mut Option<T>) -> Vec<T>".to_string())
1400                        }),
1401                        ..Default::default()
1402                    },
1403                    &language
1404                )
1405                .await,
1406            Some(CodeLabel::new(
1407                "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1408                0..5,
1409                vec![
1410                    (0..5, highlight_function),
1411                    (7..10, highlight_keyword),
1412                    (11..17, highlight_type),
1413                    (18..19, highlight_type),
1414                    (25..28, highlight_type),
1415                    (29..30, highlight_type),
1416                ],
1417            ))
1418        );
1419        assert_eq!(
1420            adapter
1421                .label_for_completion(
1422                    &lsp::CompletionItem {
1423                        kind: Some(lsp::CompletionItemKind::FUNCTION),
1424                        label: "hello(…)".to_string(),
1425                        label_details: Some(CompletionItemLabelDetails {
1426                            detail: Some("(use crate::foo)".into()),
1427                            description: Some("async fn(&mut Option<T>) -> Vec<T>".to_string()),
1428                        }),
1429                        ..Default::default()
1430                    },
1431                    &language
1432                )
1433                .await,
1434            Some(CodeLabel::new(
1435                "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1436                0..5,
1437                vec![
1438                    (0..5, highlight_function),
1439                    (7..10, highlight_keyword),
1440                    (11..17, highlight_type),
1441                    (18..19, highlight_type),
1442                    (25..28, highlight_type),
1443                    (29..30, highlight_type),
1444                ],
1445            ))
1446        );
1447        assert_eq!(
1448            adapter
1449                .label_for_completion(
1450                    &lsp::CompletionItem {
1451                        kind: Some(lsp::CompletionItemKind::FIELD),
1452                        label: "len".to_string(),
1453                        detail: Some("usize".to_string()),
1454                        ..Default::default()
1455                    },
1456                    &language
1457                )
1458                .await,
1459            Some(CodeLabel::new(
1460                "len: usize".to_string(),
1461                0..3,
1462                vec![(0..3, highlight_field), (5..10, highlight_type),],
1463            ))
1464        );
1465
1466        assert_eq!(
1467            adapter
1468                .label_for_completion(
1469                    &lsp::CompletionItem {
1470                        kind: Some(lsp::CompletionItemKind::FUNCTION),
1471                        label: "hello(…)".to_string(),
1472                        label_details: Some(CompletionItemLabelDetails {
1473                            detail: Some("(use crate::foo)".to_string()),
1474                            description: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
1475                        }),
1476
1477                        ..Default::default()
1478                    },
1479                    &language
1480                )
1481                .await,
1482            Some(CodeLabel::new(
1483                "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1484                0..5,
1485                vec![
1486                    (0..5, highlight_function),
1487                    (7..10, highlight_keyword),
1488                    (11..17, highlight_type),
1489                    (18..19, highlight_type),
1490                    (25..28, highlight_type),
1491                    (29..30, highlight_type),
1492                ],
1493            ))
1494        );
1495
1496        assert_eq!(
1497            adapter
1498                .label_for_completion(
1499                    &lsp::CompletionItem {
1500                        kind: Some(lsp::CompletionItemKind::FUNCTION),
1501                        label: "hello".to_string(),
1502                        label_details: Some(CompletionItemLabelDetails {
1503                            detail: Some("(use crate::foo)".to_string()),
1504                            description: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
1505                        }),
1506                        ..Default::default()
1507                    },
1508                    &language
1509                )
1510                .await,
1511            Some(CodeLabel::new(
1512                "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1513                0..5,
1514                vec![
1515                    (0..5, highlight_function),
1516                    (7..10, highlight_keyword),
1517                    (11..17, highlight_type),
1518                    (18..19, highlight_type),
1519                    (25..28, highlight_type),
1520                    (29..30, highlight_type),
1521                ],
1522            ))
1523        );
1524
1525        assert_eq!(
1526            adapter
1527                .label_for_completion(
1528                    &lsp::CompletionItem {
1529                        kind: Some(lsp::CompletionItemKind::METHOD),
1530                        label: "await.as_deref_mut()".to_string(),
1531                        filter_text: Some("as_deref_mut".to_string()),
1532                        label_details: Some(CompletionItemLabelDetails {
1533                            detail: None,
1534                            description: Some("fn(&mut self) -> IterMut<'_, T>".to_string()),
1535                        }),
1536                        ..Default::default()
1537                    },
1538                    &language
1539                )
1540                .await,
1541            Some(CodeLabel::new(
1542                "await.as_deref_mut(&mut self) -> IterMut<'_, T>".to_string(),
1543                6..18,
1544                vec![
1545                    (6..18, HighlightId(2)),
1546                    (20..23, HighlightId(1)),
1547                    (33..40, HighlightId(0)),
1548                    (45..46, HighlightId(0))
1549                ],
1550            ))
1551        );
1552
1553        assert_eq!(
1554            adapter
1555                .label_for_completion(
1556                    &lsp::CompletionItem {
1557                        kind: Some(lsp::CompletionItemKind::METHOD),
1558                        label: "as_deref_mut()".to_string(),
1559                        filter_text: Some("as_deref_mut".to_string()),
1560                        label_details: Some(CompletionItemLabelDetails {
1561                            detail: None,
1562                            description: Some(
1563                                "pub fn as_deref_mut(&mut self) -> IterMut<'_, T>".to_string()
1564                            ),
1565                        }),
1566                        ..Default::default()
1567                    },
1568                    &language
1569                )
1570                .await,
1571            Some(CodeLabel::new(
1572                "pub fn as_deref_mut(&mut self) -> IterMut<'_, T>".to_string(),
1573                7..19,
1574                vec![
1575                    (0..3, HighlightId(1)),
1576                    (4..6, HighlightId(1)),
1577                    (7..19, HighlightId(2)),
1578                    (21..24, HighlightId(1)),
1579                    (34..41, HighlightId(0)),
1580                    (46..47, HighlightId(0))
1581                ],
1582            ))
1583        );
1584
1585        assert_eq!(
1586            adapter
1587                .label_for_completion(
1588                    &lsp::CompletionItem {
1589                        kind: Some(lsp::CompletionItemKind::FIELD),
1590                        label: "inner_value".to_string(),
1591                        filter_text: Some("value".to_string()),
1592                        detail: Some("String".to_string()),
1593                        ..Default::default()
1594                    },
1595                    &language,
1596                )
1597                .await,
1598            Some(CodeLabel::new(
1599                "inner_value: String".to_string(),
1600                6..11,
1601                vec![(0..11, HighlightId(3)), (13..19, HighlightId(0))],
1602            ))
1603        );
1604
1605        // Snippet with insert tabstop (empty placeholder)
1606        assert_eq!(
1607            adapter
1608                .label_for_completion(
1609                    &lsp::CompletionItem {
1610                        kind: Some(lsp::CompletionItemKind::SNIPPET),
1611                        label: "println!".to_string(),
1612                        insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
1613                        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1614                            range: lsp::Range::default(),
1615                            new_text: "println!(\"$1\", $2)$0".to_string(),
1616                        })),
1617                        ..Default::default()
1618                    },
1619                    &language,
1620                )
1621                .await,
1622            Some(CodeLabel::new(
1623                "println!(\"\", …)".to_string(),
1624                0..8,
1625                vec![
1626                    (10..13, HighlightId::TABSTOP_INSERT_ID),
1627                    (16..19, HighlightId::TABSTOP_INSERT_ID),
1628                    (0..7, HighlightId(2)),
1629                    (7..8, HighlightId(2)),
1630                ],
1631            ))
1632        );
1633
1634        // Snippet with replace tabstop (placeholder with default text)
1635        assert_eq!(
1636            adapter
1637                .label_for_completion(
1638                    &lsp::CompletionItem {
1639                        kind: Some(lsp::CompletionItemKind::SNIPPET),
1640                        label: "vec!".to_string(),
1641                        insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
1642                        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1643                            range: lsp::Range::default(),
1644                            new_text: "vec![${1:elem}]$0".to_string(),
1645                        })),
1646                        ..Default::default()
1647                    },
1648                    &language,
1649                )
1650                .await,
1651            Some(CodeLabel::new(
1652                "vec![elem]".to_string(),
1653                0..4,
1654                vec![
1655                    (5..9, HighlightId::TABSTOP_REPLACE_ID),
1656                    (0..3, HighlightId(2)),
1657                    (3..4, HighlightId(2)),
1658                ],
1659            ))
1660        );
1661
1662        // Snippet with tabstop appearing more than once
1663        assert_eq!(
1664            adapter
1665                .label_for_completion(
1666                    &lsp::CompletionItem {
1667                        kind: Some(lsp::CompletionItemKind::SNIPPET),
1668                        label: "if let".to_string(),
1669                        insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
1670                        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1671                            range: lsp::Range::default(),
1672                            new_text: "if let ${1:pat} = $1 {\n    $0\n}".to_string(),
1673                        })),
1674                        ..Default::default()
1675                    },
1676                    &language,
1677                )
1678                .await,
1679            Some(CodeLabel::new(
1680                "if let pat = … {\n    \n}".to_string(),
1681                0..6,
1682                vec![
1683                    (7..10, HighlightId::TABSTOP_REPLACE_ID),
1684                    (13..16, HighlightId::TABSTOP_INSERT_ID),
1685                    (0..2, HighlightId(1)),
1686                    (3..6, HighlightId(1)),
1687                ],
1688            ))
1689        );
1690
1691        // Snippet with tabstops not in left-to-right order
1692        assert_eq!(
1693            adapter
1694                .label_for_completion(
1695                    &lsp::CompletionItem {
1696                        kind: Some(lsp::CompletionItemKind::SNIPPET),
1697                        label: "for".to_string(),
1698                        insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
1699                        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1700                            range: lsp::Range::default(),
1701                            new_text: "for ${2:item} in ${1:iter} {\n    $0\n}".to_string(),
1702                        })),
1703                        ..Default::default()
1704                    },
1705                    &language,
1706                )
1707                .await,
1708            Some(CodeLabel::new(
1709                "for item in iter {\n    \n}".to_string(),
1710                0..3,
1711                vec![
1712                    (4..8, HighlightId::TABSTOP_REPLACE_ID),
1713                    (12..16, HighlightId::TABSTOP_REPLACE_ID),
1714                    (0..3, HighlightId(1)),
1715                    (9..11, HighlightId(1)),
1716                ],
1717            ))
1718        );
1719
1720        // Postfix completion without actual tabstops (only implicit final $0)
1721        // The label should use completion.label so it can be filtered by "ref"
1722        let ref_completion = adapter
1723            .label_for_completion(
1724                &lsp::CompletionItem {
1725                    kind: Some(lsp::CompletionItemKind::SNIPPET),
1726                    label: "ref".to_string(),
1727                    filter_text: Some("ref".to_string()),
1728                    label_details: Some(CompletionItemLabelDetails {
1729                        detail: None,
1730                        description: Some("&expr".to_string()),
1731                    }),
1732                    detail: Some("&expr".to_string()),
1733                    insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
1734                    text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1735                        range: lsp::Range::default(),
1736                        new_text: "&String::new()".to_string(),
1737                    })),
1738                    ..Default::default()
1739                },
1740                &language,
1741            )
1742            .await;
1743        assert!(
1744            ref_completion.is_some(),
1745            "ref postfix completion should have a label"
1746        );
1747        let ref_label = ref_completion.unwrap();
1748        let filter_text = &ref_label.text[ref_label.filter_range.clone()];
1749        assert!(
1750            filter_text.contains("ref"),
1751            "filter range text '{filter_text}' should contain 'ref' for filtering to work",
1752        );
1753
1754        // Test for correct range calculation with mixed empty and non-empty tabstops.(See https://github.com/zed-industries/zed/issues/44825)
1755        let res = adapter
1756            .label_for_completion(
1757                &lsp::CompletionItem {
1758                    kind: Some(lsp::CompletionItemKind::STRUCT),
1759                    label: "Particles".to_string(),
1760                    insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
1761                    text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1762                        range: lsp::Range::default(),
1763                        new_text: "Particles { pos_x: $1, pos_y: $2, vel_x: $3, vel_y: $4, acc_x: ${5:()}, acc_y: ${6:()}, mass: $7 }$0".to_string(),
1764                    })),
1765                    ..Default::default()
1766                },
1767                &language,
1768            )
1769            .await
1770            .unwrap();
1771
1772        assert_eq!(
1773            res,
1774            CodeLabel::new(
1775                "Particles { pos_x: …, pos_y: …, vel_x: …, vel_y: …, acc_x: (), acc_y: (), mass: … }".to_string(),
1776                0..9,
1777                vec![
1778                    (19..22, HighlightId::TABSTOP_INSERT_ID),
1779                    (31..34, HighlightId::TABSTOP_INSERT_ID),
1780                    (43..46, HighlightId::TABSTOP_INSERT_ID),
1781                    (55..58, HighlightId::TABSTOP_INSERT_ID),
1782                    (67..69, HighlightId::TABSTOP_REPLACE_ID),
1783                    (78..80, HighlightId::TABSTOP_REPLACE_ID),
1784                    (88..91, HighlightId::TABSTOP_INSERT_ID),
1785                    (0..9, highlight_type),
1786                    (60..65, highlight_field),
1787                    (71..76, highlight_field),
1788                ],
1789            )
1790        );
1791    }
1792
1793    #[gpui::test]
1794    async fn test_rust_label_for_symbol() {
1795        let adapter = Arc::new(RustLspAdapter);
1796        let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1797        let grammar = language.grammar().unwrap();
1798        let theme = SyntaxTheme::new_test([
1799            ("type", Hsla::default()),
1800            ("keyword", Hsla::default()),
1801            ("function", Hsla::default()),
1802            ("property", Hsla::default()),
1803        ]);
1804
1805        language.set_theme(&theme);
1806
1807        let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1808        let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1809        let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1810
1811        assert_eq!(
1812            adapter
1813                .label_for_symbol("hello", lsp::SymbolKind::FUNCTION, &language)
1814                .await,
1815            Some(CodeLabel::new(
1816                "fn hello".to_string(),
1817                3..8,
1818                vec![(0..2, highlight_keyword), (3..8, highlight_function)],
1819            ))
1820        );
1821
1822        assert_eq!(
1823            adapter
1824                .label_for_symbol("World", lsp::SymbolKind::TYPE_PARAMETER, &language)
1825                .await,
1826            Some(CodeLabel::new(
1827                "type World".to_string(),
1828                5..10,
1829                vec![(0..4, highlight_keyword), (5..10, highlight_type)],
1830            ))
1831        );
1832
1833        assert_eq!(
1834            adapter
1835                .label_for_symbol("zed", lsp::SymbolKind::PACKAGE, &language)
1836                .await,
1837            Some(CodeLabel::new(
1838                "extern crate zed".to_string(),
1839                13..16,
1840                vec![(0..6, highlight_keyword), (7..12, highlight_keyword),],
1841            ))
1842        );
1843
1844        assert_eq!(
1845            adapter
1846                .label_for_symbol("Variant", lsp::SymbolKind::ENUM_MEMBER, &language)
1847                .await,
1848            Some(CodeLabel::new(
1849                "Variant".to_string(),
1850                0..7,
1851                vec![(0..7, highlight_type)],
1852            ))
1853        );
1854    }
1855
1856    #[gpui::test]
1857    async fn test_rust_autoindent(cx: &mut TestAppContext) {
1858        // cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
1859        cx.update(|cx| {
1860            let test_settings = SettingsStore::test(cx);
1861            cx.set_global(test_settings);
1862            cx.update_global::<SettingsStore, _>(|store, cx| {
1863                store.update_user_settings(cx, |s| {
1864                    s.project.all_languages.defaults.tab_size = NonZeroU32::new(2);
1865                });
1866            });
1867        });
1868
1869        let language = crate::language("rust", tree_sitter_rust::LANGUAGE.into());
1870
1871        cx.new(|cx| {
1872            let mut buffer = Buffer::local("", cx).with_language(language, cx);
1873
1874            // indent between braces
1875            buffer.set_text("fn a() {}", cx);
1876            let ix = buffer.len() - 1;
1877            buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1878            assert_eq!(buffer.text(), "fn a() {\n  \n}");
1879
1880            // indent between braces, even after empty lines
1881            buffer.set_text("fn a() {\n\n\n}", cx);
1882            let ix = buffer.len() - 2;
1883            buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1884            assert_eq!(buffer.text(), "fn a() {\n\n\n  \n}");
1885
1886            // indent a line that continues a field expression
1887            buffer.set_text("fn a() {\n  \n}", cx);
1888            let ix = buffer.len() - 2;
1889            buffer.edit([(ix..ix, "b\n.c")], Some(AutoindentMode::EachLine), cx);
1890            assert_eq!(buffer.text(), "fn a() {\n  b\n    .c\n}");
1891
1892            // indent further lines that continue the field expression, even after empty lines
1893            let ix = buffer.len() - 2;
1894            buffer.edit([(ix..ix, "\n\n.d")], Some(AutoindentMode::EachLine), cx);
1895            assert_eq!(buffer.text(), "fn a() {\n  b\n    .c\n    \n    .d\n}");
1896
1897            // dedent the line after the field expression
1898            let ix = buffer.len() - 2;
1899            buffer.edit([(ix..ix, ";\ne")], Some(AutoindentMode::EachLine), cx);
1900            assert_eq!(
1901                buffer.text(),
1902                "fn a() {\n  b\n    .c\n    \n    .d;\n  e\n}"
1903            );
1904
1905            // indent inside a struct within a call
1906            buffer.set_text("const a: B = c(D {});", cx);
1907            let ix = buffer.len() - 3;
1908            buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1909            assert_eq!(buffer.text(), "const a: B = c(D {\n  \n});");
1910
1911            // indent further inside a nested call
1912            let ix = buffer.len() - 4;
1913            buffer.edit([(ix..ix, "e: f(\n\n)")], Some(AutoindentMode::EachLine), cx);
1914            assert_eq!(buffer.text(), "const a: B = c(D {\n  e: f(\n    \n  )\n});");
1915
1916            // keep that indent after an empty line
1917            let ix = buffer.len() - 8;
1918            buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1919            assert_eq!(
1920                buffer.text(),
1921                "const a: B = c(D {\n  e: f(\n    \n    \n  )\n});"
1922            );
1923
1924            buffer
1925        });
1926    }
1927
1928    #[test]
1929    fn test_package_name_from_pkgid() {
1930        for (input, expected) in [
1931            (
1932                "path+file:///absolute/path/to/project/zed/crates/zed#0.131.0",
1933                "zed",
1934            ),
1935            (
1936                "path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0",
1937                "my-custom-package",
1938            ),
1939        ] {
1940            assert_eq!(package_name_from_pkgid(input), Some(expected));
1941        }
1942    }
1943
1944    #[test]
1945    fn test_target_info_from_metadata() {
1946        for (input, absolute_path, expected) in [
1947            (
1948                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"}]}]}"#,
1949                "/path/to/zed/src/main.rs",
1950                Some((
1951                    Some(TargetInfo {
1952                        package_name: "zed".into(),
1953                        target_name: "zed".into(),
1954                        required_features: Vec::new(),
1955                        target_kind: TargetKind::Bin,
1956                    }),
1957                    Arc::from("/path/to/zed".as_ref()),
1958                )),
1959            ),
1960            (
1961                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"}]}]}"#,
1962                "/path/to/custom-package/src/main.rs",
1963                Some((
1964                    Some(TargetInfo {
1965                        package_name: "my-custom-package".into(),
1966                        target_name: "my-custom-bin".into(),
1967                        required_features: Vec::new(),
1968                        target_kind: TargetKind::Bin,
1969                    }),
1970                    Arc::from("/path/to/custom-package".as_ref()),
1971                )),
1972            ),
1973            (
1974                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"}]}"#,
1975                "/path/to/custom-package/src/main.rs",
1976                Some((
1977                    Some(TargetInfo {
1978                        package_name: "my-custom-package".into(),
1979                        target_name: "my-custom-bin".into(),
1980                        required_features: Vec::new(),
1981                        target_kind: TargetKind::Example,
1982                    }),
1983                    Arc::from("/path/to/custom-package".as_ref()),
1984                )),
1985            ),
1986            (
1987                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"]}]}]}"#,
1988                "/path/to/custom-package/src/main.rs",
1989                Some((
1990                    Some(TargetInfo {
1991                        package_name: "my-custom-package".into(),
1992                        target_name: "my-custom-bin".into(),
1993                        required_features: vec!["foo".to_owned(), "bar".to_owned()],
1994                        target_kind: TargetKind::Example,
1995                    }),
1996                    Arc::from("/path/to/custom-package".as_ref()),
1997                )),
1998            ),
1999            (
2000                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"}]}"#,
2001                "/path/to/custom-package/src/main.rs",
2002                Some((
2003                    Some(TargetInfo {
2004                        package_name: "my-custom-package".into(),
2005                        target_name: "my-custom-bin".into(),
2006                        required_features: vec![],
2007                        target_kind: TargetKind::Example,
2008                    }),
2009                    Arc::from("/path/to/custom-package".as_ref()),
2010                )),
2011            ),
2012            (
2013                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"}]}"#,
2014                "/path/to/custom-package/src/main.rs",
2015                Some((None, Arc::from("/path/to/custom-package".as_ref()))),
2016            ),
2017        ] {
2018            let metadata: CargoMetadata = serde_json::from_str(input).context(input).unwrap();
2019
2020            let absolute_path = Path::new(absolute_path);
2021
2022            assert_eq!(target_info_from_metadata(metadata, absolute_path), expected);
2023        }
2024    }
2025
2026    #[test]
2027    fn test_rust_test_fragment() {
2028        #[track_caller]
2029        fn check(
2030            variables: impl IntoIterator<Item = (VariableName, &'static str)>,
2031            path: &str,
2032            expected: &str,
2033        ) {
2034            let path = Path::new(path);
2035            let found = test_fragment(
2036                &TaskVariables::from_iter(variables.into_iter().map(|(k, v)| (k, v.to_owned()))),
2037                path,
2038                path.file_stem().unwrap().to_str().unwrap(),
2039            );
2040            assert_eq!(expected, found);
2041        }
2042
2043        check([], "/project/src/lib.rs", "--lib");
2044        check([], "/project/src/foo/mod.rs", "foo");
2045        check(
2046            [
2047                (RUST_BIN_KIND_TASK_VARIABLE.clone(), "bin"),
2048                (RUST_BIN_NAME_TASK_VARIABLE, "x"),
2049            ],
2050            "/project/src/main.rs",
2051            "--bin=x",
2052        );
2053        check([], "/project/src/main.rs", "--");
2054    }
2055
2056    #[test]
2057    fn test_convert_rust_analyzer_schema() {
2058        let raw_schema = serde_json::json!([
2059            {
2060                "title": "Assist",
2061                "properties": {
2062                    "rust-analyzer.assist.emitMustUse": {
2063                        "markdownDescription": "Insert #[must_use] when generating `as_` methods for enum variants.",
2064                        "default": false,
2065                        "type": "boolean"
2066                    }
2067                }
2068            },
2069            {
2070                "title": "Assist",
2071                "properties": {
2072                    "rust-analyzer.assist.expressionFillDefault": {
2073                        "markdownDescription": "Placeholder expression to use for missing expressions in assists.",
2074                        "default": "todo",
2075                        "type": "string"
2076                    }
2077                }
2078            },
2079            {
2080                "title": "Cache Priming",
2081                "properties": {
2082                    "rust-analyzer.cachePriming.enable": {
2083                        "markdownDescription": "Warm up caches on project load.",
2084                        "default": true,
2085                        "type": "boolean"
2086                    }
2087                }
2088            }
2089        ]);
2090
2091        let converted = RustLspAdapter::convert_rust_analyzer_schema(&raw_schema);
2092
2093        assert_eq!(
2094            converted.get("type").and_then(|v| v.as_str()),
2095            Some("object")
2096        );
2097
2098        let properties = converted
2099            .pointer("/properties")
2100            .expect("should have properties")
2101            .as_object()
2102            .expect("properties should be object");
2103
2104        assert!(properties.contains_key("assist"));
2105        assert!(properties.contains_key("cachePriming"));
2106        assert!(!properties.contains_key("rust-analyzer"));
2107
2108        let assist_props = properties
2109            .get("assist")
2110            .expect("should have assist")
2111            .pointer("/properties")
2112            .expect("assist should have properties")
2113            .as_object()
2114            .expect("assist properties should be object");
2115
2116        assert!(assist_props.contains_key("emitMustUse"));
2117        assert!(assist_props.contains_key("expressionFillDefault"));
2118
2119        let emit_must_use = assist_props
2120            .get("emitMustUse")
2121            .expect("should have emitMustUse");
2122        assert_eq!(
2123            emit_must_use.get("type").and_then(|v| v.as_str()),
2124            Some("boolean")
2125        );
2126        assert_eq!(
2127            emit_must_use.get("default").and_then(|v| v.as_bool()),
2128            Some(false)
2129        );
2130
2131        let cache_priming_props = properties
2132            .get("cachePriming")
2133            .expect("should have cachePriming")
2134            .pointer("/properties")
2135            .expect("cachePriming should have properties")
2136            .as_object()
2137            .expect("cachePriming properties should be object");
2138
2139        assert!(cache_priming_props.contains_key("enable"));
2140    }
2141}