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