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
 839    #[gpui::test]
 840    async fn test_process_rust_diagnostics() {
 841        let mut params = lsp::PublishDiagnosticsParams {
 842            uri: lsp::Url::from_file_path("/a").unwrap(),
 843            version: None,
 844            diagnostics: vec![
 845                // no newlines
 846                lsp::Diagnostic {
 847                    message: "use of moved value `a`".to_string(),
 848                    ..Default::default()
 849                },
 850                // newline at the end of a code span
 851                lsp::Diagnostic {
 852                    message: "consider importing this struct: `use b::c;\n`".to_string(),
 853                    ..Default::default()
 854                },
 855                // code span starting right after a newline
 856                lsp::Diagnostic {
 857                    message: "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
 858                        .to_string(),
 859                    ..Default::default()
 860                },
 861            ],
 862        };
 863        RustLspAdapter.process_diagnostics(&mut params);
 864
 865        assert_eq!(params.diagnostics[0].message, "use of moved value `a`");
 866
 867        // remove trailing newline from code span
 868        assert_eq!(
 869            params.diagnostics[1].message,
 870            "consider importing this struct: `use b::c;`"
 871        );
 872
 873        // do not remove newline before the start of code span
 874        assert_eq!(
 875            params.diagnostics[2].message,
 876            "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
 877        );
 878    }
 879
 880    #[gpui::test]
 881    async fn test_rust_label_for_completion() {
 882        let adapter = Arc::new(RustLspAdapter);
 883        let language = language("rust", tree_sitter_rust::LANGUAGE.into());
 884        let grammar = language.grammar().unwrap();
 885        let theme = SyntaxTheme::new_test([
 886            ("type", Hsla::default()),
 887            ("keyword", Hsla::default()),
 888            ("function", Hsla::default()),
 889            ("property", Hsla::default()),
 890        ]);
 891
 892        language.set_theme(&theme);
 893
 894        let highlight_function = grammar.highlight_id_for_name("function").unwrap();
 895        let highlight_type = grammar.highlight_id_for_name("type").unwrap();
 896        let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
 897        let highlight_field = grammar.highlight_id_for_name("property").unwrap();
 898
 899        assert_eq!(
 900            adapter
 901                .label_for_completion(
 902                    &lsp::CompletionItem {
 903                        kind: Some(lsp::CompletionItemKind::FUNCTION),
 904                        label: "hello(…)".to_string(),
 905                        label_details: Some(CompletionItemLabelDetails {
 906                            detail: Some("(use crate::foo)".into()),
 907                            description: Some("fn(&mut Option<T>) -> Vec<T>".to_string())
 908                        }),
 909                        ..Default::default()
 910                    },
 911                    &language
 912                )
 913                .await,
 914            Some(CodeLabel {
 915                text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
 916                filter_range: 0..5,
 917                runs: vec![
 918                    (0..5, highlight_function),
 919                    (7..10, highlight_keyword),
 920                    (11..17, highlight_type),
 921                    (18..19, highlight_type),
 922                    (25..28, highlight_type),
 923                    (29..30, highlight_type),
 924                ],
 925            })
 926        );
 927        assert_eq!(
 928            adapter
 929                .label_for_completion(
 930                    &lsp::CompletionItem {
 931                        kind: Some(lsp::CompletionItemKind::FUNCTION),
 932                        label: "hello(…)".to_string(),
 933                        label_details: Some(CompletionItemLabelDetails {
 934                            detail: Some(" (use crate::foo)".into()),
 935                            description: Some("async fn(&mut Option<T>) -> Vec<T>".to_string()),
 936                        }),
 937                        ..Default::default()
 938                    },
 939                    &language
 940                )
 941                .await,
 942            Some(CodeLabel {
 943                text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
 944                filter_range: 0..5,
 945                runs: vec![
 946                    (0..5, highlight_function),
 947                    (7..10, highlight_keyword),
 948                    (11..17, highlight_type),
 949                    (18..19, highlight_type),
 950                    (25..28, highlight_type),
 951                    (29..30, highlight_type),
 952                ],
 953            })
 954        );
 955        assert_eq!(
 956            adapter
 957                .label_for_completion(
 958                    &lsp::CompletionItem {
 959                        kind: Some(lsp::CompletionItemKind::FIELD),
 960                        label: "len".to_string(),
 961                        detail: Some("usize".to_string()),
 962                        ..Default::default()
 963                    },
 964                    &language
 965                )
 966                .await,
 967            Some(CodeLabel {
 968                text: "len: usize".to_string(),
 969                filter_range: 0..3,
 970                runs: vec![(0..3, highlight_field), (5..10, highlight_type),],
 971            })
 972        );
 973
 974        assert_eq!(
 975            adapter
 976                .label_for_completion(
 977                    &lsp::CompletionItem {
 978                        kind: Some(lsp::CompletionItemKind::FUNCTION),
 979                        label: "hello(…)".to_string(),
 980                        label_details: Some(CompletionItemLabelDetails {
 981                            detail: Some(" (use crate::foo)".to_string()),
 982                            description: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
 983                        }),
 984
 985                        ..Default::default()
 986                    },
 987                    &language
 988                )
 989                .await,
 990            Some(CodeLabel {
 991                text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
 992                filter_range: 0..5,
 993                runs: vec![
 994                    (0..5, highlight_function),
 995                    (7..10, highlight_keyword),
 996                    (11..17, highlight_type),
 997                    (18..19, highlight_type),
 998                    (25..28, highlight_type),
 999                    (29..30, highlight_type),
1000                ],
1001            })
1002        );
1003    }
1004
1005    #[gpui::test]
1006    async fn test_rust_label_for_symbol() {
1007        let adapter = Arc::new(RustLspAdapter);
1008        let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1009        let grammar = language.grammar().unwrap();
1010        let theme = SyntaxTheme::new_test([
1011            ("type", Hsla::default()),
1012            ("keyword", Hsla::default()),
1013            ("function", Hsla::default()),
1014            ("property", Hsla::default()),
1015        ]);
1016
1017        language.set_theme(&theme);
1018
1019        let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1020        let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1021        let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1022
1023        assert_eq!(
1024            adapter
1025                .label_for_symbol("hello", lsp::SymbolKind::FUNCTION, &language)
1026                .await,
1027            Some(CodeLabel {
1028                text: "fn hello".to_string(),
1029                filter_range: 3..8,
1030                runs: vec![(0..2, highlight_keyword), (3..8, highlight_function)],
1031            })
1032        );
1033
1034        assert_eq!(
1035            adapter
1036                .label_for_symbol("World", lsp::SymbolKind::TYPE_PARAMETER, &language)
1037                .await,
1038            Some(CodeLabel {
1039                text: "type World".to_string(),
1040                filter_range: 5..10,
1041                runs: vec![(0..4, highlight_keyword), (5..10, highlight_type)],
1042            })
1043        );
1044    }
1045
1046    #[gpui::test]
1047    async fn test_rust_autoindent(cx: &mut TestAppContext) {
1048        // cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
1049        cx.update(|cx| {
1050            let test_settings = SettingsStore::test(cx);
1051            cx.set_global(test_settings);
1052            language::init(cx);
1053            cx.update_global::<SettingsStore, _>(|store, cx| {
1054                store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1055                    s.defaults.tab_size = NonZeroU32::new(2);
1056                });
1057            });
1058        });
1059
1060        let language = crate::language("rust", tree_sitter_rust::LANGUAGE.into());
1061
1062        cx.new(|cx| {
1063            let mut buffer = Buffer::local("", cx).with_language(language, cx);
1064
1065            // indent between braces
1066            buffer.set_text("fn a() {}", cx);
1067            let ix = buffer.len() - 1;
1068            buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1069            assert_eq!(buffer.text(), "fn a() {\n  \n}");
1070
1071            // indent between braces, even after empty lines
1072            buffer.set_text("fn a() {\n\n\n}", cx);
1073            let ix = buffer.len() - 2;
1074            buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1075            assert_eq!(buffer.text(), "fn a() {\n\n\n  \n}");
1076
1077            // indent a line that continues a field expression
1078            buffer.set_text("fn a() {\n  \n}", cx);
1079            let ix = buffer.len() - 2;
1080            buffer.edit([(ix..ix, "b\n.c")], Some(AutoindentMode::EachLine), cx);
1081            assert_eq!(buffer.text(), "fn a() {\n  b\n    .c\n}");
1082
1083            // indent further lines that continue the field expression, even after empty lines
1084            let ix = buffer.len() - 2;
1085            buffer.edit([(ix..ix, "\n\n.d")], Some(AutoindentMode::EachLine), cx);
1086            assert_eq!(buffer.text(), "fn a() {\n  b\n    .c\n    \n    .d\n}");
1087
1088            // dedent the line after the field expression
1089            let ix = buffer.len() - 2;
1090            buffer.edit([(ix..ix, ";\ne")], Some(AutoindentMode::EachLine), cx);
1091            assert_eq!(
1092                buffer.text(),
1093                "fn a() {\n  b\n    .c\n    \n    .d;\n  e\n}"
1094            );
1095
1096            // indent inside a struct within a call
1097            buffer.set_text("const a: B = c(D {});", cx);
1098            let ix = buffer.len() - 3;
1099            buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1100            assert_eq!(buffer.text(), "const a: B = c(D {\n  \n});");
1101
1102            // indent further inside a nested call
1103            let ix = buffer.len() - 4;
1104            buffer.edit([(ix..ix, "e: f(\n\n)")], Some(AutoindentMode::EachLine), cx);
1105            assert_eq!(buffer.text(), "const a: B = c(D {\n  e: f(\n    \n  )\n});");
1106
1107            // keep that indent after an empty line
1108            let ix = buffer.len() - 8;
1109            buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1110            assert_eq!(
1111                buffer.text(),
1112                "const a: B = c(D {\n  e: f(\n    \n    \n  )\n});"
1113            );
1114
1115            buffer
1116        });
1117    }
1118
1119    #[test]
1120    fn test_package_name_from_pkgid() {
1121        for (input, expected) in [
1122            (
1123                "path+file:///absolute/path/to/project/zed/crates/zed#0.131.0",
1124                "zed",
1125            ),
1126            (
1127                "path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0",
1128                "my-custom-package",
1129            ),
1130        ] {
1131            assert_eq!(package_name_from_pkgid(input), Some(expected));
1132        }
1133    }
1134
1135    #[test]
1136    fn test_retrieve_package_id_and_bin_name_from_metadata() {
1137        for (input, absolute_path, expected) in [
1138            (
1139                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"}]}]}"#,
1140                "/path/to/zed/src/main.rs",
1141                Some((
1142                    "path+file:///path/to/zed/crates/zed#0.131.0",
1143                    "zed",
1144                    TargetKind::Bin,
1145                )),
1146            ),
1147            (
1148                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"}]}]}"#,
1149                "/path/to/custom-package/src/main.rs",
1150                Some((
1151                    "path+file:///path/to/custom-package#my-custom-package@0.1.0",
1152                    "my-custom-bin",
1153                    TargetKind::Bin,
1154                )),
1155            ),
1156            (
1157                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"}]}]}"#,
1158                "/path/to/custom-package/src/main.rs",
1159                Some((
1160                    "path+file:///path/to/custom-package#my-custom-package@0.1.0",
1161                    "my-custom-bin",
1162                    TargetKind::Example,
1163                )),
1164            ),
1165            (
1166                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"}]}]}"#,
1167                "/path/to/custom-package/src/main.rs",
1168                None,
1169            ),
1170        ] {
1171            let metadata: CargoMetadata = serde_json::from_str(input).unwrap();
1172
1173            let absolute_path = Path::new(absolute_path);
1174
1175            assert_eq!(
1176                retrieve_package_id_and_bin_name_from_metadata(metadata, absolute_path),
1177                expected.map(|(pkgid, name, kind)| (pkgid.to_owned(), name.to_owned(), kind))
1178            );
1179        }
1180    }
1181}