rust.rs

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