rust.rs

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