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