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_MAIN_FUNCTION_TASK_VARIABLE: VariableName =
 473    VariableName::Custom(Cow::Borrowed("_rust_main_function_end"));
 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 is_main_function = task_variables
 493            .get(&RUST_MAIN_FUNCTION_TASK_VARIABLE)
 494            .is_some();
 495
 496        if is_main_function {
 497            if let Some(target) = local_abs_path.and_then(|path| {
 498                package_name_and_bin_name_from_abs_path(path, project_env.as_ref())
 499            }) {
 500                return Task::ready(Ok(TaskVariables::from_iter([
 501                    (RUST_PACKAGE_TASK_VARIABLE.clone(), target.package_name),
 502                    (RUST_BIN_NAME_TASK_VARIABLE.clone(), target.target_name),
 503                    (
 504                        RUST_BIN_KIND_TASK_VARIABLE.clone(),
 505                        target.target_kind.to_string(),
 506                    ),
 507                ])));
 508            }
 509        }
 510
 511        if let Some(package_name) = local_abs_path
 512            .and_then(|local_abs_path| local_abs_path.parent())
 513            .and_then(|path| human_readable_package_name(path, project_env.as_ref()))
 514        {
 515            return Task::ready(Ok(TaskVariables::from_iter([(
 516                RUST_PACKAGE_TASK_VARIABLE.clone(),
 517                package_name,
 518            )])));
 519        }
 520
 521        Task::ready(Ok(TaskVariables::default()))
 522    }
 523
 524    fn associated_tasks(
 525        &self,
 526        file: Option<Arc<dyn language::File>>,
 527        cx: &App,
 528    ) -> Option<TaskTemplates> {
 529        const DEFAULT_RUN_NAME_STR: &str = "RUST_DEFAULT_PACKAGE_RUN";
 530        let package_to_run = language_settings(Some("Rust".into()), file.as_ref(), cx)
 531            .tasks
 532            .variables
 533            .get(DEFAULT_RUN_NAME_STR)
 534            .cloned();
 535        let run_task_args = if let Some(package_to_run) = package_to_run {
 536            vec!["run".into(), "-p".into(), package_to_run]
 537        } else {
 538            vec!["run".into()]
 539        };
 540        Some(TaskTemplates(vec![
 541            TaskTemplate {
 542                label: format!(
 543                    "Check (package: {})",
 544                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 545                ),
 546                command: "cargo".into(),
 547                args: vec![
 548                    "check".into(),
 549                    "-p".into(),
 550                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 551                ],
 552                cwd: Some("$ZED_DIRNAME".to_owned()),
 553                ..TaskTemplate::default()
 554            },
 555            TaskTemplate {
 556                label: "Check all targets (workspace)".into(),
 557                command: "cargo".into(),
 558                args: vec!["check".into(), "--workspace".into(), "--all-targets".into()],
 559                cwd: Some("$ZED_DIRNAME".to_owned()),
 560                ..TaskTemplate::default()
 561            },
 562            TaskTemplate {
 563                label: format!(
 564                    "Test '{}' (package: {})",
 565                    VariableName::Symbol.template_value(),
 566                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 567                ),
 568                command: "cargo".into(),
 569                args: vec![
 570                    "test".into(),
 571                    "-p".into(),
 572                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 573                    VariableName::Symbol.template_value(),
 574                    "--".into(),
 575                    "--nocapture".into(),
 576                ],
 577                tags: vec!["rust-test".to_owned()],
 578                cwd: Some("$ZED_DIRNAME".to_owned()),
 579                ..TaskTemplate::default()
 580            },
 581            TaskTemplate {
 582                label: format!(
 583                    "Test '{}' (package: {})",
 584                    VariableName::Stem.template_value(),
 585                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 586                ),
 587                command: "cargo".into(),
 588                args: vec![
 589                    "test".into(),
 590                    "-p".into(),
 591                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 592                    VariableName::Stem.template_value(),
 593                ],
 594                tags: vec!["rust-mod-test".to_owned()],
 595                cwd: Some("$ZED_DIRNAME".to_owned()),
 596                ..TaskTemplate::default()
 597            },
 598            TaskTemplate {
 599                label: format!(
 600                    "Run {} {} (package: {})",
 601                    RUST_BIN_KIND_TASK_VARIABLE.template_value(),
 602                    RUST_BIN_NAME_TASK_VARIABLE.template_value(),
 603                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 604                ),
 605                command: "cargo".into(),
 606                args: vec![
 607                    "run".into(),
 608                    "-p".into(),
 609                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 610                    format!("--{}", RUST_BIN_KIND_TASK_VARIABLE.template_value()),
 611                    RUST_BIN_NAME_TASK_VARIABLE.template_value(),
 612                ],
 613                cwd: Some("$ZED_DIRNAME".to_owned()),
 614                tags: vec!["rust-main".to_owned()],
 615                ..TaskTemplate::default()
 616            },
 617            TaskTemplate {
 618                label: format!(
 619                    "Test (package: {})",
 620                    RUST_PACKAGE_TASK_VARIABLE.template_value()
 621                ),
 622                command: "cargo".into(),
 623                args: vec![
 624                    "test".into(),
 625                    "-p".into(),
 626                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 627                ],
 628                cwd: Some("$ZED_DIRNAME".to_owned()),
 629                ..TaskTemplate::default()
 630            },
 631            TaskTemplate {
 632                label: "Run".into(),
 633                command: "cargo".into(),
 634                args: run_task_args,
 635                cwd: Some("$ZED_DIRNAME".to_owned()),
 636                ..TaskTemplate::default()
 637            },
 638            TaskTemplate {
 639                label: "Clean".into(),
 640                command: "cargo".into(),
 641                args: vec!["clean".into()],
 642                cwd: Some("$ZED_DIRNAME".to_owned()),
 643                ..TaskTemplate::default()
 644            },
 645        ]))
 646    }
 647}
 648
 649/// Part of the data structure of Cargo metadata
 650#[derive(serde::Deserialize)]
 651struct CargoMetadata {
 652    packages: Vec<CargoPackage>,
 653}
 654
 655#[derive(serde::Deserialize)]
 656struct CargoPackage {
 657    id: String,
 658    targets: Vec<CargoTarget>,
 659}
 660
 661#[derive(serde::Deserialize)]
 662struct CargoTarget {
 663    name: String,
 664    kind: Vec<String>,
 665    src_path: String,
 666}
 667
 668#[derive(Debug, PartialEq)]
 669enum TargetKind {
 670    Bin,
 671    Example,
 672}
 673
 674impl Display for TargetKind {
 675    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 676        match self {
 677            TargetKind::Bin => write!(f, "bin"),
 678            TargetKind::Example => write!(f, "example"),
 679        }
 680    }
 681}
 682
 683impl TryFrom<&str> for TargetKind {
 684    type Error = ();
 685    fn try_from(value: &str) -> Result<Self, ()> {
 686        match value {
 687            "bin" => Ok(Self::Bin),
 688            "example" => Ok(Self::Example),
 689            _ => Err(()),
 690        }
 691    }
 692}
 693/// Which package and binary target are we in?
 694struct TargetInfo {
 695    package_name: String,
 696    target_name: String,
 697    target_kind: TargetKind,
 698}
 699
 700fn package_name_and_bin_name_from_abs_path(
 701    abs_path: &Path,
 702    project_env: Option<&HashMap<String, String>>,
 703) -> Option<TargetInfo> {
 704    let mut command = util::command::new_std_command("cargo");
 705    if let Some(envs) = project_env {
 706        command.envs(envs);
 707    }
 708    let output = command
 709        .current_dir(abs_path.parent()?)
 710        .arg("metadata")
 711        .arg("--no-deps")
 712        .arg("--format-version")
 713        .arg("1")
 714        .output()
 715        .log_err()?
 716        .stdout;
 717
 718    let metadata: CargoMetadata = serde_json::from_slice(&output).log_err()?;
 719
 720    retrieve_package_id_and_bin_name_from_metadata(metadata, abs_path).and_then(
 721        |(package_id, bin_name, target_kind)| {
 722            let package_name = package_name_from_pkgid(&package_id);
 723
 724            package_name.map(|package_name| TargetInfo {
 725                package_name: package_name.to_owned(),
 726                target_name: bin_name,
 727                target_kind,
 728            })
 729        },
 730    )
 731}
 732
 733fn retrieve_package_id_and_bin_name_from_metadata(
 734    metadata: CargoMetadata,
 735    abs_path: &Path,
 736) -> Option<(String, String, TargetKind)> {
 737    for package in metadata.packages {
 738        for target in package.targets {
 739            let Some(bin_kind) = target
 740                .kind
 741                .iter()
 742                .find_map(|kind| TargetKind::try_from(kind.as_ref()).ok())
 743            else {
 744                continue;
 745            };
 746            let target_path = PathBuf::from(target.src_path);
 747            if target_path == abs_path {
 748                return Some((package.id, target.name, bin_kind));
 749            }
 750        }
 751    }
 752
 753    None
 754}
 755
 756fn human_readable_package_name(
 757    package_directory: &Path,
 758    project_env: Option<&HashMap<String, String>>,
 759) -> Option<String> {
 760    let mut command = util::command::new_std_command("cargo");
 761    if let Some(envs) = project_env {
 762        command.envs(envs);
 763    }
 764    let pkgid = String::from_utf8(
 765        command
 766            .current_dir(package_directory)
 767            .arg("pkgid")
 768            .output()
 769            .log_err()?
 770            .stdout,
 771    )
 772    .ok()?;
 773    Some(package_name_from_pkgid(&pkgid)?.to_owned())
 774}
 775
 776// For providing local `cargo check -p $pkgid` task, we do not need most of the information we have returned.
 777// Output example in the root of Zed project:
 778// ```sh
 779// ❯ cargo pkgid zed
 780// path+file:///absolute/path/to/project/zed/crates/zed#0.131.0
 781// ```
 782// Another variant, if a project has a custom package name or hyphen in the name:
 783// ```
 784// path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0
 785// ```
 786//
 787// Extracts the package name from the output according to the spec:
 788// https://doc.rust-lang.org/cargo/reference/pkgid-spec.html#specification-grammar
 789fn package_name_from_pkgid(pkgid: &str) -> Option<&str> {
 790    fn split_off_suffix(input: &str, suffix_start: char) -> &str {
 791        match input.rsplit_once(suffix_start) {
 792            Some((without_suffix, _)) => without_suffix,
 793            None => input,
 794        }
 795    }
 796
 797    let (version_prefix, version_suffix) = pkgid.trim().rsplit_once('#')?;
 798    let package_name = match version_suffix.rsplit_once('@') {
 799        Some((custom_package_name, _version)) => custom_package_name,
 800        None => {
 801            let host_and_path = split_off_suffix(version_prefix, '?');
 802            let (_, package_name) = host_and_path.rsplit_once('/')?;
 803            package_name
 804        }
 805    };
 806    Some(package_name)
 807}
 808
 809async fn get_cached_server_binary(container_dir: PathBuf) -> Option<LanguageServerBinary> {
 810    maybe!(async {
 811        let mut last = None;
 812        let mut entries = fs::read_dir(&container_dir).await?;
 813        while let Some(entry) = entries.next().await {
 814            last = Some(entry?.path());
 815        }
 816
 817        anyhow::Ok(LanguageServerBinary {
 818            path: last.ok_or_else(|| anyhow!("no cached binary"))?,
 819            env: None,
 820            arguments: Default::default(),
 821        })
 822    })
 823    .await
 824    .log_err()
 825}
 826
 827#[cfg(test)]
 828mod tests {
 829    use std::num::NonZeroU32;
 830
 831    use super::*;
 832    use crate::language;
 833    use gpui::{AppContext as _, BorrowAppContext, Hsla, TestAppContext};
 834    use language::language_settings::AllLanguageSettings;
 835    use lsp::CompletionItemLabelDetails;
 836    use settings::SettingsStore;
 837    use theme::SyntaxTheme;
 838    use util::path;
 839
 840    #[gpui::test]
 841    async fn test_process_rust_diagnostics() {
 842        let mut params = lsp::PublishDiagnosticsParams {
 843            uri: lsp::Url::from_file_path(path!("/a")).unwrap(),
 844            version: None,
 845            diagnostics: vec![
 846                // no newlines
 847                lsp::Diagnostic {
 848                    message: "use of moved value `a`".to_string(),
 849                    ..Default::default()
 850                },
 851                // newline at the end of a code span
 852                lsp::Diagnostic {
 853                    message: "consider importing this struct: `use b::c;\n`".to_string(),
 854                    ..Default::default()
 855                },
 856                // code span starting right after a newline
 857                lsp::Diagnostic {
 858                    message: "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
 859                        .to_string(),
 860                    ..Default::default()
 861                },
 862            ],
 863        };
 864        RustLspAdapter.process_diagnostics(&mut params);
 865
 866        assert_eq!(params.diagnostics[0].message, "use of moved value `a`");
 867
 868        // remove trailing newline from code span
 869        assert_eq!(
 870            params.diagnostics[1].message,
 871            "consider importing this struct: `use b::c;`"
 872        );
 873
 874        // do not remove newline before the start of code span
 875        assert_eq!(
 876            params.diagnostics[2].message,
 877            "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
 878        );
 879    }
 880
 881    #[gpui::test]
 882    async fn test_rust_label_for_completion() {
 883        let adapter = Arc::new(RustLspAdapter);
 884        let language = language("rust", tree_sitter_rust::LANGUAGE.into());
 885        let grammar = language.grammar().unwrap();
 886        let theme = SyntaxTheme::new_test([
 887            ("type", Hsla::default()),
 888            ("keyword", Hsla::default()),
 889            ("function", Hsla::default()),
 890            ("property", Hsla::default()),
 891        ]);
 892
 893        language.set_theme(&theme);
 894
 895        let highlight_function = grammar.highlight_id_for_name("function").unwrap();
 896        let highlight_type = grammar.highlight_id_for_name("type").unwrap();
 897        let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
 898        let highlight_field = grammar.highlight_id_for_name("property").unwrap();
 899
 900        assert_eq!(
 901            adapter
 902                .label_for_completion(
 903                    &lsp::CompletionItem {
 904                        kind: Some(lsp::CompletionItemKind::FUNCTION),
 905                        label: "hello(…)".to_string(),
 906                        label_details: Some(CompletionItemLabelDetails {
 907                            detail: Some("(use crate::foo)".into()),
 908                            description: Some("fn(&mut Option<T>) -> Vec<T>".to_string())
 909                        }),
 910                        ..Default::default()
 911                    },
 912                    &language
 913                )
 914                .await,
 915            Some(CodeLabel {
 916                text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
 917                filter_range: 0..5,
 918                runs: vec![
 919                    (0..5, highlight_function),
 920                    (7..10, highlight_keyword),
 921                    (11..17, highlight_type),
 922                    (18..19, highlight_type),
 923                    (25..28, highlight_type),
 924                    (29..30, highlight_type),
 925                ],
 926            })
 927        );
 928        assert_eq!(
 929            adapter
 930                .label_for_completion(
 931                    &lsp::CompletionItem {
 932                        kind: Some(lsp::CompletionItemKind::FUNCTION),
 933                        label: "hello(…)".to_string(),
 934                        label_details: Some(CompletionItemLabelDetails {
 935                            detail: Some(" (use crate::foo)".into()),
 936                            description: Some("async fn(&mut Option<T>) -> Vec<T>".to_string()),
 937                        }),
 938                        ..Default::default()
 939                    },
 940                    &language
 941                )
 942                .await,
 943            Some(CodeLabel {
 944                text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
 945                filter_range: 0..5,
 946                runs: vec![
 947                    (0..5, highlight_function),
 948                    (7..10, highlight_keyword),
 949                    (11..17, highlight_type),
 950                    (18..19, highlight_type),
 951                    (25..28, highlight_type),
 952                    (29..30, highlight_type),
 953                ],
 954            })
 955        );
 956        assert_eq!(
 957            adapter
 958                .label_for_completion(
 959                    &lsp::CompletionItem {
 960                        kind: Some(lsp::CompletionItemKind::FIELD),
 961                        label: "len".to_string(),
 962                        detail: Some("usize".to_string()),
 963                        ..Default::default()
 964                    },
 965                    &language
 966                )
 967                .await,
 968            Some(CodeLabel {
 969                text: "len: usize".to_string(),
 970                filter_range: 0..3,
 971                runs: vec![(0..3, highlight_field), (5..10, highlight_type),],
 972            })
 973        );
 974
 975        assert_eq!(
 976            adapter
 977                .label_for_completion(
 978                    &lsp::CompletionItem {
 979                        kind: Some(lsp::CompletionItemKind::FUNCTION),
 980                        label: "hello(…)".to_string(),
 981                        label_details: Some(CompletionItemLabelDetails {
 982                            detail: Some(" (use crate::foo)".to_string()),
 983                            description: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
 984                        }),
 985
 986                        ..Default::default()
 987                    },
 988                    &language
 989                )
 990                .await,
 991            Some(CodeLabel {
 992                text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
 993                filter_range: 0..5,
 994                runs: vec![
 995                    (0..5, highlight_function),
 996                    (7..10, highlight_keyword),
 997                    (11..17, highlight_type),
 998                    (18..19, highlight_type),
 999                    (25..28, highlight_type),
1000                    (29..30, highlight_type),
1001                ],
1002            })
1003        );
1004    }
1005
1006    #[gpui::test]
1007    async fn test_rust_label_for_symbol() {
1008        let adapter = Arc::new(RustLspAdapter);
1009        let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1010        let grammar = language.grammar().unwrap();
1011        let theme = SyntaxTheme::new_test([
1012            ("type", Hsla::default()),
1013            ("keyword", Hsla::default()),
1014            ("function", Hsla::default()),
1015            ("property", Hsla::default()),
1016        ]);
1017
1018        language.set_theme(&theme);
1019
1020        let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1021        let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1022        let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1023
1024        assert_eq!(
1025            adapter
1026                .label_for_symbol("hello", lsp::SymbolKind::FUNCTION, &language)
1027                .await,
1028            Some(CodeLabel {
1029                text: "fn hello".to_string(),
1030                filter_range: 3..8,
1031                runs: vec![(0..2, highlight_keyword), (3..8, highlight_function)],
1032            })
1033        );
1034
1035        assert_eq!(
1036            adapter
1037                .label_for_symbol("World", lsp::SymbolKind::TYPE_PARAMETER, &language)
1038                .await,
1039            Some(CodeLabel {
1040                text: "type World".to_string(),
1041                filter_range: 5..10,
1042                runs: vec![(0..4, highlight_keyword), (5..10, highlight_type)],
1043            })
1044        );
1045    }
1046
1047    #[gpui::test]
1048    async fn test_rust_autoindent(cx: &mut TestAppContext) {
1049        // cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
1050        cx.update(|cx| {
1051            let test_settings = SettingsStore::test(cx);
1052            cx.set_global(test_settings);
1053            language::init(cx);
1054            cx.update_global::<SettingsStore, _>(|store, cx| {
1055                store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1056                    s.defaults.tab_size = NonZeroU32::new(2);
1057                });
1058            });
1059        });
1060
1061        let language = crate::language("rust", tree_sitter_rust::LANGUAGE.into());
1062
1063        cx.new(|cx| {
1064            let mut buffer = Buffer::local("", cx).with_language(language, cx);
1065
1066            // indent between braces
1067            buffer.set_text("fn a() {}", cx);
1068            let ix = buffer.len() - 1;
1069            buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1070            assert_eq!(buffer.text(), "fn a() {\n  \n}");
1071
1072            // indent between braces, even after empty lines
1073            buffer.set_text("fn a() {\n\n\n}", cx);
1074            let ix = buffer.len() - 2;
1075            buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1076            assert_eq!(buffer.text(), "fn a() {\n\n\n  \n}");
1077
1078            // indent a line that continues a field expression
1079            buffer.set_text("fn a() {\n  \n}", cx);
1080            let ix = buffer.len() - 2;
1081            buffer.edit([(ix..ix, "b\n.c")], Some(AutoindentMode::EachLine), cx);
1082            assert_eq!(buffer.text(), "fn a() {\n  b\n    .c\n}");
1083
1084            // indent further lines that continue the field expression, even after empty lines
1085            let ix = buffer.len() - 2;
1086            buffer.edit([(ix..ix, "\n\n.d")], Some(AutoindentMode::EachLine), cx);
1087            assert_eq!(buffer.text(), "fn a() {\n  b\n    .c\n    \n    .d\n}");
1088
1089            // dedent the line after the field expression
1090            let ix = buffer.len() - 2;
1091            buffer.edit([(ix..ix, ";\ne")], Some(AutoindentMode::EachLine), cx);
1092            assert_eq!(
1093                buffer.text(),
1094                "fn a() {\n  b\n    .c\n    \n    .d;\n  e\n}"
1095            );
1096
1097            // indent inside a struct within a call
1098            buffer.set_text("const a: B = c(D {});", cx);
1099            let ix = buffer.len() - 3;
1100            buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1101            assert_eq!(buffer.text(), "const a: B = c(D {\n  \n});");
1102
1103            // indent further inside a nested call
1104            let ix = buffer.len() - 4;
1105            buffer.edit([(ix..ix, "e: f(\n\n)")], Some(AutoindentMode::EachLine), cx);
1106            assert_eq!(buffer.text(), "const a: B = c(D {\n  e: f(\n    \n  )\n});");
1107
1108            // keep that indent after an empty line
1109            let ix = buffer.len() - 8;
1110            buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1111            assert_eq!(
1112                buffer.text(),
1113                "const a: B = c(D {\n  e: f(\n    \n    \n  )\n});"
1114            );
1115
1116            buffer
1117        });
1118    }
1119
1120    #[test]
1121    fn test_package_name_from_pkgid() {
1122        for (input, expected) in [
1123            (
1124                "path+file:///absolute/path/to/project/zed/crates/zed#0.131.0",
1125                "zed",
1126            ),
1127            (
1128                "path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0",
1129                "my-custom-package",
1130            ),
1131        ] {
1132            assert_eq!(package_name_from_pkgid(input), Some(expected));
1133        }
1134    }
1135
1136    #[test]
1137    fn test_retrieve_package_id_and_bin_name_from_metadata() {
1138        for (input, absolute_path, expected) in [
1139            (
1140                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"}]}]}"#,
1141                "/path/to/zed/src/main.rs",
1142                Some((
1143                    "path+file:///path/to/zed/crates/zed#0.131.0",
1144                    "zed",
1145                    TargetKind::Bin,
1146                )),
1147            ),
1148            (
1149                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"}]}]}"#,
1150                "/path/to/custom-package/src/main.rs",
1151                Some((
1152                    "path+file:///path/to/custom-package#my-custom-package@0.1.0",
1153                    "my-custom-bin",
1154                    TargetKind::Bin,
1155                )),
1156            ),
1157            (
1158                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"}]}]}"#,
1159                "/path/to/custom-package/src/main.rs",
1160                Some((
1161                    "path+file:///path/to/custom-package#my-custom-package@0.1.0",
1162                    "my-custom-bin",
1163                    TargetKind::Example,
1164                )),
1165            ),
1166            (
1167                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"}]}]}"#,
1168                "/path/to/custom-package/src/main.rs",
1169                None,
1170            ),
1171        ] {
1172            let metadata: CargoMetadata = serde_json::from_str(input).unwrap();
1173
1174            let absolute_path = Path::new(absolute_path);
1175
1176            assert_eq!(
1177                retrieve_package_id_and_bin_name_from_metadata(metadata, absolute_path),
1178                expected.map(|(pkgid, name, kind)| (pkgid.to_owned(), name.to_owned(), kind))
1179            );
1180        }
1181    }
1182}