rust.rs

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