rust.rs

   1use anyhow::{anyhow, Context as _, Result};
   2use async_compression::futures::bufread::GzipDecoder;
   3use async_trait::async_trait;
   4use collections::HashMap;
   5use futures::{io::BufReader, StreamExt};
   6use gpui::{App, AsyncApp, SharedString, Task};
   7use http_client::github::AssetKind;
   8use http_client::github::{latest_github_release, GitHubLspBinaryVersion};
   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, TaskVariables, VariableName};
  21use util::{fs::remove_matching, maybe, ResultExt};
  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 {
 578            vec!["run".into(), "-p".into(), package_to_run]
 579        } else {
 580            vec!["run".into()]
 581        };
 582        let mut task_templates = vec![
 583            TaskTemplate {
 584                label: format!(
 585                    "Check (package: {})",
 586                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 587                ),
 588                command: "cargo".into(),
 589                args: vec![
 590                    "check".into(),
 591                    "-p".into(),
 592                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 593                ],
 594                cwd: Some("$ZED_DIRNAME".to_owned()),
 595                ..TaskTemplate::default()
 596            },
 597            TaskTemplate {
 598                label: "Check all targets (workspace)".into(),
 599                command: "cargo".into(),
 600                args: vec!["check".into(), "--workspace".into(), "--all-targets".into()],
 601                cwd: Some("$ZED_DIRNAME".to_owned()),
 602                ..TaskTemplate::default()
 603            },
 604            TaskTemplate {
 605                label: format!(
 606                    "Test '{}' (package: {})",
 607                    RUST_TEST_NAME_TASK_VARIABLE.template_value(),
 608                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 609                ),
 610                command: "cargo".into(),
 611                args: vec![
 612                    "test".into(),
 613                    "-p".into(),
 614                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 615                    RUST_TEST_NAME_TASK_VARIABLE.template_value(),
 616                    "--".into(),
 617                    "--nocapture".into(),
 618                ],
 619                tags: vec!["rust-test".to_owned()],
 620                cwd: Some("$ZED_DIRNAME".to_owned()),
 621                ..TaskTemplate::default()
 622            },
 623            TaskTemplate {
 624                label: format!(
 625                    "Doc test '{}' (package: {})",
 626                    RUST_DOC_TEST_NAME_TASK_VARIABLE.template_value(),
 627                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 628                ),
 629                command: "cargo".into(),
 630                args: vec![
 631                    "test".into(),
 632                    "--doc".into(),
 633                    "-p".into(),
 634                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 635                    RUST_DOC_TEST_NAME_TASK_VARIABLE.template_value(),
 636                    "--".into(),
 637                    "--nocapture".into(),
 638                ],
 639                tags: vec!["rust-doc-test".to_owned()],
 640                cwd: Some("$ZED_DIRNAME".to_owned()),
 641                ..TaskTemplate::default()
 642            },
 643            TaskTemplate {
 644                label: format!(
 645                    "Test mod '{}' (package: {})",
 646                    VariableName::Stem.template_value(),
 647                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 648                ),
 649                command: "cargo".into(),
 650                args: vec![
 651                    "test".into(),
 652                    "-p".into(),
 653                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 654                    RUST_TEST_FRAGMENT_TASK_VARIABLE.template_value(),
 655                ],
 656                tags: vec!["rust-mod-test".to_owned()],
 657                cwd: Some("$ZED_DIRNAME".to_owned()),
 658                ..TaskTemplate::default()
 659            },
 660            TaskTemplate {
 661                label: format!(
 662                    "Run {} {} (package: {})",
 663                    RUST_BIN_KIND_TASK_VARIABLE.template_value(),
 664                    RUST_BIN_NAME_TASK_VARIABLE.template_value(),
 665                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 666                ),
 667                command: "cargo".into(),
 668                args: vec![
 669                    "run".into(),
 670                    "-p".into(),
 671                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 672                    format!("--{}", RUST_BIN_KIND_TASK_VARIABLE.template_value()),
 673                    RUST_BIN_NAME_TASK_VARIABLE.template_value(),
 674                ],
 675                cwd: Some("$ZED_DIRNAME".to_owned()),
 676                tags: vec!["rust-main".to_owned()],
 677                ..TaskTemplate::default()
 678            },
 679            TaskTemplate {
 680                label: format!(
 681                    "Test (package: {})",
 682                    RUST_PACKAGE_TASK_VARIABLE.template_value()
 683                ),
 684                command: "cargo".into(),
 685                args: vec![
 686                    "test".into(),
 687                    "-p".into(),
 688                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 689                ],
 690                cwd: Some("$ZED_DIRNAME".to_owned()),
 691                ..TaskTemplate::default()
 692            },
 693            TaskTemplate {
 694                label: "Run".into(),
 695                command: "cargo".into(),
 696                args: run_task_args,
 697                cwd: Some("$ZED_DIRNAME".to_owned()),
 698                ..TaskTemplate::default()
 699            },
 700            TaskTemplate {
 701                label: "Clean".into(),
 702                command: "cargo".into(),
 703                args: vec!["clean".into()],
 704                cwd: Some("$ZED_DIRNAME".to_owned()),
 705                ..TaskTemplate::default()
 706            },
 707        ];
 708
 709        if let Some(custom_target_dir) = custom_target_dir {
 710            task_templates = task_templates
 711                .into_iter()
 712                .map(|mut task_template| {
 713                    let mut args = task_template.args.split_off(1);
 714                    task_template.args.append(&mut vec![
 715                        "--target-dir".to_string(),
 716                        custom_target_dir.clone(),
 717                    ]);
 718                    task_template.args.append(&mut args);
 719
 720                    task_template
 721                })
 722                .collect();
 723        }
 724
 725        Some(TaskTemplates(task_templates))
 726    }
 727}
 728
 729/// Part of the data structure of Cargo metadata
 730#[derive(serde::Deserialize)]
 731struct CargoMetadata {
 732    packages: Vec<CargoPackage>,
 733}
 734
 735#[derive(serde::Deserialize)]
 736struct CargoPackage {
 737    id: String,
 738    targets: Vec<CargoTarget>,
 739}
 740
 741#[derive(serde::Deserialize)]
 742struct CargoTarget {
 743    name: String,
 744    kind: Vec<String>,
 745    src_path: String,
 746}
 747
 748#[derive(Debug, PartialEq)]
 749enum TargetKind {
 750    Bin,
 751    Example,
 752}
 753
 754impl Display for TargetKind {
 755    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 756        match self {
 757            TargetKind::Bin => write!(f, "bin"),
 758            TargetKind::Example => write!(f, "example"),
 759        }
 760    }
 761}
 762
 763impl TryFrom<&str> for TargetKind {
 764    type Error = ();
 765    fn try_from(value: &str) -> Result<Self, ()> {
 766        match value {
 767            "bin" => Ok(Self::Bin),
 768            "example" => Ok(Self::Example),
 769            _ => Err(()),
 770        }
 771    }
 772}
 773/// Which package and binary target are we in?
 774struct TargetInfo {
 775    package_name: String,
 776    target_name: String,
 777    target_kind: TargetKind,
 778}
 779
 780fn package_name_and_bin_name_from_abs_path(
 781    abs_path: &Path,
 782    project_env: Option<&HashMap<String, String>>,
 783) -> Option<TargetInfo> {
 784    let mut command = util::command::new_std_command("cargo");
 785    if let Some(envs) = project_env {
 786        command.envs(envs);
 787    }
 788    let output = command
 789        .current_dir(abs_path.parent()?)
 790        .arg("metadata")
 791        .arg("--no-deps")
 792        .arg("--format-version")
 793        .arg("1")
 794        .output()
 795        .log_err()?
 796        .stdout;
 797
 798    let metadata: CargoMetadata = serde_json::from_slice(&output).log_err()?;
 799
 800    retrieve_package_id_and_bin_name_from_metadata(metadata, abs_path).and_then(
 801        |(package_id, bin_name, target_kind)| {
 802            let package_name = package_name_from_pkgid(&package_id);
 803
 804            package_name.map(|package_name| TargetInfo {
 805                package_name: package_name.to_owned(),
 806                target_name: bin_name,
 807                target_kind,
 808            })
 809        },
 810    )
 811}
 812
 813fn retrieve_package_id_and_bin_name_from_metadata(
 814    metadata: CargoMetadata,
 815    abs_path: &Path,
 816) -> Option<(String, String, TargetKind)> {
 817    for package in metadata.packages {
 818        for target in package.targets {
 819            let Some(bin_kind) = target
 820                .kind
 821                .iter()
 822                .find_map(|kind| TargetKind::try_from(kind.as_ref()).ok())
 823            else {
 824                continue;
 825            };
 826            let target_path = PathBuf::from(target.src_path);
 827            if target_path == abs_path {
 828                return Some((package.id, target.name, bin_kind));
 829            }
 830        }
 831    }
 832
 833    None
 834}
 835
 836fn human_readable_package_name(
 837    package_directory: &Path,
 838    project_env: Option<&HashMap<String, String>>,
 839) -> Option<String> {
 840    let mut command = util::command::new_std_command("cargo");
 841    if let Some(envs) = project_env {
 842        command.envs(envs);
 843    }
 844    let pkgid = String::from_utf8(
 845        command
 846            .current_dir(package_directory)
 847            .arg("pkgid")
 848            .output()
 849            .log_err()?
 850            .stdout,
 851    )
 852    .ok()?;
 853    Some(package_name_from_pkgid(&pkgid)?.to_owned())
 854}
 855
 856// For providing local `cargo check -p $pkgid` task, we do not need most of the information we have returned.
 857// Output example in the root of Zed project:
 858// ```sh
 859// ❯ cargo pkgid zed
 860// path+file:///absolute/path/to/project/zed/crates/zed#0.131.0
 861// ```
 862// Another variant, if a project has a custom package name or hyphen in the name:
 863// ```
 864// path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0
 865// ```
 866//
 867// Extracts the package name from the output according to the spec:
 868// https://doc.rust-lang.org/cargo/reference/pkgid-spec.html#specification-grammar
 869fn package_name_from_pkgid(pkgid: &str) -> Option<&str> {
 870    fn split_off_suffix(input: &str, suffix_start: char) -> &str {
 871        match input.rsplit_once(suffix_start) {
 872            Some((without_suffix, _)) => without_suffix,
 873            None => input,
 874        }
 875    }
 876
 877    let (version_prefix, version_suffix) = pkgid.trim().rsplit_once('#')?;
 878    let package_name = match version_suffix.rsplit_once('@') {
 879        Some((custom_package_name, _version)) => custom_package_name,
 880        None => {
 881            let host_and_path = split_off_suffix(version_prefix, '?');
 882            let (_, package_name) = host_and_path.rsplit_once('/')?;
 883            package_name
 884        }
 885    };
 886    Some(package_name)
 887}
 888
 889async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
 890    maybe!(async {
 891        let mut last = None;
 892        let mut entries = fs::read_dir(&container_dir).await?;
 893        while let Some(entry) = entries.next().await {
 894            last = Some(entry?.path());
 895        }
 896
 897        anyhow::Ok(LanguageServerBinary {
 898            path: last.ok_or_else(|| anyhow!("no cached binary"))?,
 899            env: None,
 900            arguments: Default::default(),
 901        })
 902    })
 903    .await
 904    .log_err()
 905}
 906
 907fn test_fragment(variables: &TaskVariables, path: &Path, stem: &str) -> String {
 908    let fragment = if stem == "lib" {
 909        // This isn't quite right---it runs the tests for the entire library, rather than
 910        // just for the top-level `mod tests`. But we don't really have the means here to
 911        // filter out just that module.
 912        Some("--lib".to_owned())
 913    } else if stem == "mod" {
 914        maybe!({ Some(path.parent()?.file_name()?.to_string_lossy().to_string()) })
 915    } else if stem == "main" {
 916        if let (Some(bin_name), Some(bin_kind)) = (
 917            variables.get(&RUST_BIN_NAME_TASK_VARIABLE),
 918            variables.get(&RUST_BIN_KIND_TASK_VARIABLE),
 919        ) {
 920            Some(format!("--{bin_kind}={bin_name}"))
 921        } else {
 922            None
 923        }
 924    } else {
 925        Some(stem.to_owned())
 926    };
 927    fragment.unwrap_or_else(|| "--".to_owned())
 928}
 929
 930#[cfg(test)]
 931mod tests {
 932    use std::num::NonZeroU32;
 933
 934    use super::*;
 935    use crate::language;
 936    use gpui::{AppContext as _, BorrowAppContext, Hsla, TestAppContext};
 937    use language::language_settings::AllLanguageSettings;
 938    use lsp::CompletionItemLabelDetails;
 939    use settings::SettingsStore;
 940    use theme::SyntaxTheme;
 941    use util::path;
 942
 943    #[gpui::test]
 944    async fn test_process_rust_diagnostics() {
 945        let mut params = lsp::PublishDiagnosticsParams {
 946            uri: lsp::Url::from_file_path(path!("/a")).unwrap(),
 947            version: None,
 948            diagnostics: vec![
 949                // no newlines
 950                lsp::Diagnostic {
 951                    message: "use of moved value `a`".to_string(),
 952                    ..Default::default()
 953                },
 954                // newline at the end of a code span
 955                lsp::Diagnostic {
 956                    message: "consider importing this struct: `use b::c;\n`".to_string(),
 957                    ..Default::default()
 958                },
 959                // code span starting right after a newline
 960                lsp::Diagnostic {
 961                    message: "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
 962                        .to_string(),
 963                    ..Default::default()
 964                },
 965            ],
 966        };
 967        RustLspAdapter.process_diagnostics(&mut params, LanguageServerId(0), None);
 968
 969        assert_eq!(params.diagnostics[0].message, "use of moved value `a`");
 970
 971        // remove trailing newline from code span
 972        assert_eq!(
 973            params.diagnostics[1].message,
 974            "consider importing this struct: `use b::c;`"
 975        );
 976
 977        // do not remove newline before the start of code span
 978        assert_eq!(
 979            params.diagnostics[2].message,
 980            "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
 981        );
 982    }
 983
 984    #[gpui::test]
 985    async fn test_rust_label_for_completion() {
 986        let adapter = Arc::new(RustLspAdapter);
 987        let language = language("rust", tree_sitter_rust::LANGUAGE.into());
 988        let grammar = language.grammar().unwrap();
 989        let theme = SyntaxTheme::new_test([
 990            ("type", Hsla::default()),
 991            ("keyword", Hsla::default()),
 992            ("function", Hsla::default()),
 993            ("property", Hsla::default()),
 994        ]);
 995
 996        language.set_theme(&theme);
 997
 998        let highlight_function = grammar.highlight_id_for_name("function").unwrap();
 999        let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1000        let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1001        let highlight_field = grammar.highlight_id_for_name("property").unwrap();
1002
1003        assert_eq!(
1004            adapter
1005                .label_for_completion(
1006                    &lsp::CompletionItem {
1007                        kind: Some(lsp::CompletionItemKind::FUNCTION),
1008                        label: "hello(…)".to_string(),
1009                        label_details: Some(CompletionItemLabelDetails {
1010                            detail: Some("(use crate::foo)".into()),
1011                            description: Some("fn(&mut Option<T>) -> Vec<T>".to_string())
1012                        }),
1013                        ..Default::default()
1014                    },
1015                    &language
1016                )
1017                .await,
1018            Some(CodeLabel {
1019                text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1020                filter_range: 0..5,
1021                runs: vec![
1022                    (0..5, highlight_function),
1023                    (7..10, highlight_keyword),
1024                    (11..17, highlight_type),
1025                    (18..19, highlight_type),
1026                    (25..28, highlight_type),
1027                    (29..30, highlight_type),
1028                ],
1029            })
1030        );
1031        assert_eq!(
1032            adapter
1033                .label_for_completion(
1034                    &lsp::CompletionItem {
1035                        kind: Some(lsp::CompletionItemKind::FUNCTION),
1036                        label: "hello(…)".to_string(),
1037                        label_details: Some(CompletionItemLabelDetails {
1038                            detail: Some(" (use crate::foo)".into()),
1039                            description: Some("async fn(&mut Option<T>) -> Vec<T>".to_string()),
1040                        }),
1041                        ..Default::default()
1042                    },
1043                    &language
1044                )
1045                .await,
1046            Some(CodeLabel {
1047                text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1048                filter_range: 0..5,
1049                runs: vec![
1050                    (0..5, highlight_function),
1051                    (7..10, highlight_keyword),
1052                    (11..17, highlight_type),
1053                    (18..19, highlight_type),
1054                    (25..28, highlight_type),
1055                    (29..30, highlight_type),
1056                ],
1057            })
1058        );
1059        assert_eq!(
1060            adapter
1061                .label_for_completion(
1062                    &lsp::CompletionItem {
1063                        kind: Some(lsp::CompletionItemKind::FIELD),
1064                        label: "len".to_string(),
1065                        detail: Some("usize".to_string()),
1066                        ..Default::default()
1067                    },
1068                    &language
1069                )
1070                .await,
1071            Some(CodeLabel {
1072                text: "len: usize".to_string(),
1073                filter_range: 0..3,
1074                runs: vec![(0..3, highlight_field), (5..10, highlight_type),],
1075            })
1076        );
1077
1078        assert_eq!(
1079            adapter
1080                .label_for_completion(
1081                    &lsp::CompletionItem {
1082                        kind: Some(lsp::CompletionItemKind::FUNCTION),
1083                        label: "hello(…)".to_string(),
1084                        label_details: Some(CompletionItemLabelDetails {
1085                            detail: Some(" (use crate::foo)".to_string()),
1086                            description: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
1087                        }),
1088
1089                        ..Default::default()
1090                    },
1091                    &language
1092                )
1093                .await,
1094            Some(CodeLabel {
1095                text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
1096                filter_range: 0..5,
1097                runs: vec![
1098                    (0..5, highlight_function),
1099                    (7..10, highlight_keyword),
1100                    (11..17, highlight_type),
1101                    (18..19, highlight_type),
1102                    (25..28, highlight_type),
1103                    (29..30, highlight_type),
1104                ],
1105            })
1106        );
1107    }
1108
1109    #[gpui::test]
1110    async fn test_rust_label_for_symbol() {
1111        let adapter = Arc::new(RustLspAdapter);
1112        let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1113        let grammar = language.grammar().unwrap();
1114        let theme = SyntaxTheme::new_test([
1115            ("type", Hsla::default()),
1116            ("keyword", Hsla::default()),
1117            ("function", Hsla::default()),
1118            ("property", Hsla::default()),
1119        ]);
1120
1121        language.set_theme(&theme);
1122
1123        let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1124        let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1125        let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1126
1127        assert_eq!(
1128            adapter
1129                .label_for_symbol("hello", lsp::SymbolKind::FUNCTION, &language)
1130                .await,
1131            Some(CodeLabel {
1132                text: "fn hello".to_string(),
1133                filter_range: 3..8,
1134                runs: vec![(0..2, highlight_keyword), (3..8, highlight_function)],
1135            })
1136        );
1137
1138        assert_eq!(
1139            adapter
1140                .label_for_symbol("World", lsp::SymbolKind::TYPE_PARAMETER, &language)
1141                .await,
1142            Some(CodeLabel {
1143                text: "type World".to_string(),
1144                filter_range: 5..10,
1145                runs: vec![(0..4, highlight_keyword), (5..10, highlight_type)],
1146            })
1147        );
1148    }
1149
1150    #[gpui::test]
1151    async fn test_rust_autoindent(cx: &mut TestAppContext) {
1152        // cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
1153        cx.update(|cx| {
1154            let test_settings = SettingsStore::test(cx);
1155            cx.set_global(test_settings);
1156            language::init(cx);
1157            cx.update_global::<SettingsStore, _>(|store, cx| {
1158                store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1159                    s.defaults.tab_size = NonZeroU32::new(2);
1160                });
1161            });
1162        });
1163
1164        let language = crate::language("rust", tree_sitter_rust::LANGUAGE.into());
1165
1166        cx.new(|cx| {
1167            let mut buffer = Buffer::local("", cx).with_language(language, cx);
1168
1169            // indent between braces
1170            buffer.set_text("fn a() {}", cx);
1171            let ix = buffer.len() - 1;
1172            buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1173            assert_eq!(buffer.text(), "fn a() {\n  \n}");
1174
1175            // indent between braces, even after empty lines
1176            buffer.set_text("fn a() {\n\n\n}", cx);
1177            let ix = buffer.len() - 2;
1178            buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1179            assert_eq!(buffer.text(), "fn a() {\n\n\n  \n}");
1180
1181            // indent a line that continues a field expression
1182            buffer.set_text("fn a() {\n  \n}", cx);
1183            let ix = buffer.len() - 2;
1184            buffer.edit([(ix..ix, "b\n.c")], Some(AutoindentMode::EachLine), cx);
1185            assert_eq!(buffer.text(), "fn a() {\n  b\n    .c\n}");
1186
1187            // indent further lines that continue the field expression, even after empty lines
1188            let ix = buffer.len() - 2;
1189            buffer.edit([(ix..ix, "\n\n.d")], Some(AutoindentMode::EachLine), cx);
1190            assert_eq!(buffer.text(), "fn a() {\n  b\n    .c\n    \n    .d\n}");
1191
1192            // dedent the line after the field expression
1193            let ix = buffer.len() - 2;
1194            buffer.edit([(ix..ix, ";\ne")], Some(AutoindentMode::EachLine), cx);
1195            assert_eq!(
1196                buffer.text(),
1197                "fn a() {\n  b\n    .c\n    \n    .d;\n  e\n}"
1198            );
1199
1200            // indent inside a struct within a call
1201            buffer.set_text("const a: B = c(D {});", cx);
1202            let ix = buffer.len() - 3;
1203            buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1204            assert_eq!(buffer.text(), "const a: B = c(D {\n  \n});");
1205
1206            // indent further inside a nested call
1207            let ix = buffer.len() - 4;
1208            buffer.edit([(ix..ix, "e: f(\n\n)")], Some(AutoindentMode::EachLine), cx);
1209            assert_eq!(buffer.text(), "const a: B = c(D {\n  e: f(\n    \n  )\n});");
1210
1211            // keep that indent after an empty line
1212            let ix = buffer.len() - 8;
1213            buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1214            assert_eq!(
1215                buffer.text(),
1216                "const a: B = c(D {\n  e: f(\n    \n    \n  )\n});"
1217            );
1218
1219            buffer
1220        });
1221    }
1222
1223    #[test]
1224    fn test_package_name_from_pkgid() {
1225        for (input, expected) in [
1226            (
1227                "path+file:///absolute/path/to/project/zed/crates/zed#0.131.0",
1228                "zed",
1229            ),
1230            (
1231                "path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0",
1232                "my-custom-package",
1233            ),
1234        ] {
1235            assert_eq!(package_name_from_pkgid(input), Some(expected));
1236        }
1237    }
1238
1239    #[test]
1240    fn test_retrieve_package_id_and_bin_name_from_metadata() {
1241        for (input, absolute_path, expected) in [
1242            (
1243                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"}]}]}"#,
1244                "/path/to/zed/src/main.rs",
1245                Some((
1246                    "path+file:///path/to/zed/crates/zed#0.131.0",
1247                    "zed",
1248                    TargetKind::Bin,
1249                )),
1250            ),
1251            (
1252                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"}]}]}"#,
1253                "/path/to/custom-package/src/main.rs",
1254                Some((
1255                    "path+file:///path/to/custom-package#my-custom-package@0.1.0",
1256                    "my-custom-bin",
1257                    TargetKind::Bin,
1258                )),
1259            ),
1260            (
1261                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"}]}]}"#,
1262                "/path/to/custom-package/src/main.rs",
1263                Some((
1264                    "path+file:///path/to/custom-package#my-custom-package@0.1.0",
1265                    "my-custom-bin",
1266                    TargetKind::Example,
1267                )),
1268            ),
1269            (
1270                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"}]}]}"#,
1271                "/path/to/custom-package/src/main.rs",
1272                None,
1273            ),
1274        ] {
1275            let metadata: CargoMetadata = serde_json::from_str(input).unwrap();
1276
1277            let absolute_path = Path::new(absolute_path);
1278
1279            assert_eq!(
1280                retrieve_package_id_and_bin_name_from_metadata(metadata, absolute_path),
1281                expected.map(|(pkgid, name, kind)| (pkgid.to_owned(), name.to_owned(), kind))
1282            );
1283        }
1284    }
1285
1286    #[test]
1287    fn test_rust_test_fragment() {
1288        #[track_caller]
1289        fn check(
1290            variables: impl IntoIterator<Item = (VariableName, &'static str)>,
1291            path: &str,
1292            expected: &str,
1293        ) {
1294            let path = Path::new(path);
1295            let found = test_fragment(
1296                &TaskVariables::from_iter(variables.into_iter().map(|(k, v)| (k, v.to_owned()))),
1297                path,
1298                &path.file_stem().unwrap().to_str().unwrap(),
1299            );
1300            assert_eq!(expected, found);
1301        }
1302
1303        check([], "/project/src/lib.rs", "--lib");
1304        check([], "/project/src/foo/mod.rs", "foo");
1305        check(
1306            [
1307                (RUST_BIN_KIND_TASK_VARIABLE.clone(), "bin"),
1308                (RUST_BIN_NAME_TASK_VARIABLE, "x"),
1309            ],
1310            "/project/src/main.rs",
1311            "--bin=x",
1312        );
1313        check([], "/project/src/main.rs", "--");
1314    }
1315}