rust.rs

   1use anyhow::{anyhow, Context, Result};
   2use async_compression::futures::bufread::GzipDecoder;
   3use async_trait::async_trait;
   4use collections::HashMap;
   5use futures::{io::BufReader, StreamExt};
   6use gpui::{AppContext, AsyncAppContext, 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").to_path_buf();
  86            if smol::block_on(delegate.read_text_file(p)).is_ok() {
  87                outermost_cargo_toml = Some(Arc::from(path));
  88            }
  89        }
  90
  91        outermost_cargo_toml
  92    }
  93    async fn check_if_user_installed(
  94        &self,
  95        delegate: &dyn LspAdapterDelegate,
  96        _: Arc<dyn LanguageToolchainStore>,
  97        _: &AsyncAppContext,
  98    ) -> Option<LanguageServerBinary> {
  99        let path = delegate.which("rust-analyzer".as_ref()).await?;
 100        let env = delegate.shell_env().await;
 101
 102        // It is surprisingly common for ~/.cargo/bin/rust-analyzer to be a symlink to
 103        // /usr/bin/rust-analyzer that fails when you run it; so we need to test it.
 104        log::info!("found rust-analyzer in PATH. trying to run `rust-analyzer --help`");
 105        let result = delegate
 106            .try_exec(LanguageServerBinary {
 107                path: path.clone(),
 108                arguments: vec!["--help".into()],
 109                env: Some(env.clone()),
 110            })
 111            .await;
 112        if let Err(err) = result {
 113            log::error!(
 114                "failed to run rust-analyzer after detecting it in PATH: binary: {:?}: {}",
 115                path,
 116                err
 117            );
 118            return None;
 119        }
 120
 121        Some(LanguageServerBinary {
 122            path,
 123            env: Some(env),
 124            arguments: vec![],
 125        })
 126    }
 127
 128    async fn fetch_latest_server_version(
 129        &self,
 130        delegate: &dyn LspAdapterDelegate,
 131    ) -> Result<Box<dyn 'static + Send + Any>> {
 132        let release = latest_github_release(
 133            "rust-lang/rust-analyzer",
 134            true,
 135            false,
 136            delegate.http_client(),
 137        )
 138        .await?;
 139        let asset_name = Self::build_asset_name();
 140
 141        let asset = release
 142            .assets
 143            .iter()
 144            .find(|asset| asset.name == asset_name)
 145            .with_context(|| format!("no asset found matching `{asset_name:?}`"))?;
 146        Ok(Box::new(GitHubLspBinaryVersion {
 147            name: release.tag_name,
 148            url: asset.browser_download_url.clone(),
 149        }))
 150    }
 151
 152    async fn fetch_server_binary(
 153        &self,
 154        version: Box<dyn 'static + Send + Any>,
 155        container_dir: PathBuf,
 156        delegate: &dyn LspAdapterDelegate,
 157    ) -> Result<LanguageServerBinary> {
 158        let version = version.downcast::<GitHubLspBinaryVersion>().unwrap();
 159        let destination_path = container_dir.join(format!("rust-analyzer-{}", version.name));
 160        let server_path = match Self::GITHUB_ASSET_KIND {
 161            AssetKind::TarGz | AssetKind::Gz => destination_path.clone(), // Tar and gzip extract in place.
 162            AssetKind::Zip => destination_path.clone().join("rust-analyzer.exe"), // zip contains a .exe
 163        };
 164
 165        if fs::metadata(&server_path).await.is_err() {
 166            remove_matching(&container_dir, |entry| entry != destination_path).await;
 167
 168            let mut response = delegate
 169                .http_client()
 170                .get(&version.url, Default::default(), true)
 171                .await
 172                .with_context(|| format!("downloading release from {}", version.url))?;
 173            match Self::GITHUB_ASSET_KIND {
 174                AssetKind::TarGz => {
 175                    let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
 176                    let archive = async_tar::Archive::new(decompressed_bytes);
 177                    archive.unpack(&destination_path).await.with_context(|| {
 178                        format!("extracting {} to {:?}", version.url, destination_path)
 179                    })?;
 180                }
 181                AssetKind::Gz => {
 182                    let mut decompressed_bytes =
 183                        GzipDecoder::new(BufReader::new(response.body_mut()));
 184                    let mut file =
 185                        fs::File::create(&destination_path).await.with_context(|| {
 186                            format!(
 187                                "creating a file {:?} for a download from {}",
 188                                destination_path, version.url,
 189                            )
 190                        })?;
 191                    futures::io::copy(&mut decompressed_bytes, &mut file)
 192                        .await
 193                        .with_context(|| {
 194                            format!("extracting {} to {:?}", version.url, destination_path)
 195                        })?;
 196                }
 197                AssetKind::Zip => {
 198                    node_runtime::extract_zip(
 199                        &destination_path,
 200                        BufReader::new(response.body_mut()),
 201                    )
 202                    .await
 203                    .with_context(|| {
 204                        format!("unzipping {} to {:?}", version.url, destination_path)
 205                    })?;
 206                }
 207            };
 208
 209            // todo("windows")
 210            #[cfg(not(windows))]
 211            {
 212                fs::set_permissions(
 213                    &server_path,
 214                    <fs::Permissions as fs::unix::PermissionsExt>::from_mode(0o755),
 215                )
 216                .await?;
 217            }
 218        }
 219
 220        Ok(LanguageServerBinary {
 221            path: server_path,
 222            env: None,
 223            arguments: Default::default(),
 224        })
 225    }
 226
 227    async fn cached_server_binary(
 228        &self,
 229        container_dir: PathBuf,
 230        _: &dyn LspAdapterDelegate,
 231    ) -> Option<LanguageServerBinary> {
 232        get_cached_server_binary(container_dir).await
 233    }
 234
 235    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
 236        vec!["rustc".into()]
 237    }
 238
 239    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
 240        Some("rust-analyzer/flycheck".into())
 241    }
 242
 243    fn process_diagnostics(&self, params: &mut lsp::PublishDiagnosticsParams) {
 244        static REGEX: LazyLock<Regex> =
 245            LazyLock::new(|| Regex::new(r"(?m)`([^`]+)\n`$").expect("Failed to create REGEX"));
 246
 247        for diagnostic in &mut params.diagnostics {
 248            for message in diagnostic
 249                .related_information
 250                .iter_mut()
 251                .flatten()
 252                .map(|info| &mut info.message)
 253                .chain([&mut diagnostic.message])
 254            {
 255                if let Cow::Owned(sanitized) = REGEX.replace_all(message, "`$1`") {
 256                    *message = sanitized;
 257                }
 258            }
 259        }
 260    }
 261
 262    async fn label_for_completion(
 263        &self,
 264        completion: &lsp::CompletionItem,
 265        language: &Arc<Language>,
 266    ) -> Option<CodeLabel> {
 267        let detail = completion
 268            .label_details
 269            .as_ref()
 270            .and_then(|detail| detail.detail.as_ref())
 271            .or(completion.detail.as_ref())
 272            .map(|detail| detail.trim());
 273        let function_signature = completion
 274            .label_details
 275            .as_ref()
 276            .and_then(|detail| detail.description.as_deref())
 277            .or(completion.detail.as_deref());
 278        match (detail, completion.kind) {
 279            (Some(detail), Some(lsp::CompletionItemKind::FIELD)) => {
 280                let name = &completion.label;
 281                let text = format!("{name}: {detail}");
 282                let prefix = "struct S { ";
 283                let source = Rope::from(format!("{prefix}{text} }}"));
 284                let runs =
 285                    language.highlight_text(&source, prefix.len()..prefix.len() + text.len());
 286                return Some(CodeLabel {
 287                    text,
 288                    runs,
 289                    filter_range: 0..name.len(),
 290                });
 291            }
 292            (
 293                Some(detail),
 294                Some(lsp::CompletionItemKind::CONSTANT | lsp::CompletionItemKind::VARIABLE),
 295            ) if completion.insert_text_format != Some(lsp::InsertTextFormat::SNIPPET) => {
 296                let name = &completion.label;
 297                let text = format!(
 298                    "{}: {}",
 299                    name,
 300                    completion.detail.as_deref().unwrap_or(detail)
 301                );
 302                let prefix = "let ";
 303                let source = Rope::from(format!("{prefix}{text} = ();"));
 304                let runs =
 305                    language.highlight_text(&source, prefix.len()..prefix.len() + text.len());
 306                return Some(CodeLabel {
 307                    text,
 308                    runs,
 309                    filter_range: 0..name.len(),
 310                });
 311            }
 312            (
 313                Some(detail),
 314                Some(lsp::CompletionItemKind::FUNCTION | lsp::CompletionItemKind::METHOD),
 315            ) => {
 316                static REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new("\\(…?\\)").unwrap());
 317                const FUNCTION_PREFIXES: [&str; 6] = [
 318                    "async fn",
 319                    "async unsafe fn",
 320                    "const fn",
 321                    "const unsafe fn",
 322                    "unsafe fn",
 323                    "fn",
 324                ];
 325                // Is it function `async`?
 326                let fn_keyword = FUNCTION_PREFIXES.iter().find_map(|prefix| {
 327                    function_signature.as_ref().and_then(|signature| {
 328                        signature
 329                            .strip_prefix(*prefix)
 330                            .map(|suffix| (*prefix, suffix))
 331                    })
 332                });
 333                // fn keyword should be followed by opening parenthesis.
 334                if let Some((prefix, suffix)) = fn_keyword {
 335                    let mut text = REGEX.replace(&completion.label, suffix).to_string();
 336                    let source = Rope::from(format!("{prefix} {text} {{}}"));
 337                    let run_start = prefix.len() + 1;
 338                    let runs = language.highlight_text(&source, run_start..run_start + text.len());
 339                    if detail.starts_with("(") {
 340                        text.push(' ');
 341                        text.push_str(&detail);
 342                    }
 343
 344                    return Some(CodeLabel {
 345                        filter_range: 0..completion.label.find('(').unwrap_or(text.len()),
 346                        text,
 347                        runs,
 348                    });
 349                } else if completion
 350                    .detail
 351                    .as_ref()
 352                    .map_or(false, |detail| detail.starts_with("macro_rules! "))
 353                {
 354                    let source = Rope::from(completion.label.as_str());
 355                    let runs = language.highlight_text(&source, 0..completion.label.len());
 356
 357                    return Some(CodeLabel {
 358                        filter_range: 0..completion.label.len(),
 359                        text: completion.label.clone(),
 360                        runs,
 361                    });
 362                }
 363            }
 364            (_, Some(kind)) => {
 365                let highlight_name = match kind {
 366                    lsp::CompletionItemKind::STRUCT
 367                    | lsp::CompletionItemKind::INTERFACE
 368                    | lsp::CompletionItemKind::ENUM => Some("type"),
 369                    lsp::CompletionItemKind::ENUM_MEMBER => Some("variant"),
 370                    lsp::CompletionItemKind::KEYWORD => Some("keyword"),
 371                    lsp::CompletionItemKind::VALUE | lsp::CompletionItemKind::CONSTANT => {
 372                        Some("constant")
 373                    }
 374                    _ => None,
 375                };
 376
 377                let mut label = completion.label.clone();
 378                if let Some(detail) = detail.filter(|detail| detail.starts_with("(")) {
 379                    label.push(' ');
 380                    label.push_str(detail);
 381                }
 382                let mut label = CodeLabel::plain(label, None);
 383                if let Some(highlight_name) = highlight_name {
 384                    let highlight_id = language.grammar()?.highlight_id_for_name(highlight_name)?;
 385                    label.runs.push((
 386                        0..label.text.rfind('(').unwrap_or(completion.label.len()),
 387                        highlight_id,
 388                    ));
 389                }
 390
 391                return Some(label);
 392            }
 393            _ => {}
 394        }
 395        None
 396    }
 397
 398    async fn label_for_symbol(
 399        &self,
 400        name: &str,
 401        kind: lsp::SymbolKind,
 402        language: &Arc<Language>,
 403    ) -> Option<CodeLabel> {
 404        let (text, filter_range, display_range) = match kind {
 405            lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
 406                let text = format!("fn {} () {{}}", name);
 407                let filter_range = 3..3 + name.len();
 408                let display_range = 0..filter_range.end;
 409                (text, filter_range, display_range)
 410            }
 411            lsp::SymbolKind::STRUCT => {
 412                let text = format!("struct {} {{}}", name);
 413                let filter_range = 7..7 + name.len();
 414                let display_range = 0..filter_range.end;
 415                (text, filter_range, display_range)
 416            }
 417            lsp::SymbolKind::ENUM => {
 418                let text = format!("enum {} {{}}", name);
 419                let filter_range = 5..5 + name.len();
 420                let display_range = 0..filter_range.end;
 421                (text, filter_range, display_range)
 422            }
 423            lsp::SymbolKind::INTERFACE => {
 424                let text = format!("trait {} {{}}", name);
 425                let filter_range = 6..6 + name.len();
 426                let display_range = 0..filter_range.end;
 427                (text, filter_range, display_range)
 428            }
 429            lsp::SymbolKind::CONSTANT => {
 430                let text = format!("const {}: () = ();", name);
 431                let filter_range = 6..6 + name.len();
 432                let display_range = 0..filter_range.end;
 433                (text, filter_range, display_range)
 434            }
 435            lsp::SymbolKind::MODULE => {
 436                let text = format!("mod {} {{}}", name);
 437                let filter_range = 4..4 + name.len();
 438                let display_range = 0..filter_range.end;
 439                (text, filter_range, display_range)
 440            }
 441            lsp::SymbolKind::TYPE_PARAMETER => {
 442                let text = format!("type {} {{}}", name);
 443                let filter_range = 5..5 + name.len();
 444                let display_range = 0..filter_range.end;
 445                (text, filter_range, display_range)
 446            }
 447            _ => return None,
 448        };
 449
 450        Some(CodeLabel {
 451            runs: language.highlight_text(&text.as_str().into(), display_range.clone()),
 452            text: text[display_range].to_string(),
 453            filter_range,
 454        })
 455    }
 456}
 457
 458pub(crate) struct RustContextProvider;
 459
 460const RUST_PACKAGE_TASK_VARIABLE: VariableName =
 461    VariableName::Custom(Cow::Borrowed("RUST_PACKAGE"));
 462
 463/// The bin name corresponding to the current file in Cargo.toml
 464const RUST_BIN_NAME_TASK_VARIABLE: VariableName =
 465    VariableName::Custom(Cow::Borrowed("RUST_BIN_NAME"));
 466
 467/// The bin kind (bin/example) corresponding to the current file in Cargo.toml
 468const RUST_BIN_KIND_TASK_VARIABLE: VariableName =
 469    VariableName::Custom(Cow::Borrowed("RUST_BIN_KIND"));
 470
 471const RUST_MAIN_FUNCTION_TASK_VARIABLE: VariableName =
 472    VariableName::Custom(Cow::Borrowed("_rust_main_function_end"));
 473
 474impl ContextProvider for RustContextProvider {
 475    fn build_context(
 476        &self,
 477        task_variables: &TaskVariables,
 478        location: &Location,
 479        project_env: Option<HashMap<String, String>>,
 480        _: Arc<dyn LanguageToolchainStore>,
 481        cx: &mut gpui::AppContext,
 482    ) -> Task<Result<TaskVariables>> {
 483        let local_abs_path = location
 484            .buffer
 485            .read(cx)
 486            .file()
 487            .and_then(|file| Some(file.as_local()?.abs_path(cx)));
 488
 489        let local_abs_path = local_abs_path.as_deref();
 490
 491        let is_main_function = task_variables
 492            .get(&RUST_MAIN_FUNCTION_TASK_VARIABLE)
 493            .is_some();
 494
 495        if is_main_function {
 496            if let Some(target) = local_abs_path.and_then(|path| {
 497                package_name_and_bin_name_from_abs_path(path, project_env.as_ref())
 498            }) {
 499                return Task::ready(Ok(TaskVariables::from_iter([
 500                    (RUST_PACKAGE_TASK_VARIABLE.clone(), target.package_name),
 501                    (RUST_BIN_NAME_TASK_VARIABLE.clone(), target.target_name),
 502                    (
 503                        RUST_BIN_KIND_TASK_VARIABLE.clone(),
 504                        target.target_kind.to_string(),
 505                    ),
 506                ])));
 507            }
 508        }
 509
 510        if let Some(package_name) = local_abs_path
 511            .and_then(|local_abs_path| local_abs_path.parent())
 512            .and_then(|path| human_readable_package_name(path, project_env.as_ref()))
 513        {
 514            return Task::ready(Ok(TaskVariables::from_iter([(
 515                RUST_PACKAGE_TASK_VARIABLE.clone(),
 516                package_name,
 517            )])));
 518        }
 519
 520        Task::ready(Ok(TaskVariables::default()))
 521    }
 522
 523    fn associated_tasks(
 524        &self,
 525        file: Option<Arc<dyn language::File>>,
 526        cx: &AppContext,
 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                    "cargo check -p {}",
 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: "cargo check --workspace --all-targets".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                    "cargo test -p {} {} -- --nocapture",
 564                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 565                    VariableName::Symbol.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                    "cargo test -p {} {}",
 583                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 584                    VariableName::Stem.template_value(),
 585                ),
 586                command: "cargo".into(),
 587                args: vec![
 588                    "test".into(),
 589                    "-p".into(),
 590                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 591                    VariableName::Stem.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                    "cargo run -p {} --{} {}",
 600                    RUST_PACKAGE_TASK_VARIABLE.template_value(),
 601                    RUST_BIN_KIND_TASK_VARIABLE.template_value(),
 602                    RUST_BIN_NAME_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                    "cargo test -p {}",
 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: "cargo 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: "cargo 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
 826#[cfg(test)]
 827mod tests {
 828    use std::num::NonZeroU32;
 829
 830    use super::*;
 831    use crate::language;
 832    use gpui::{BorrowAppContext, Context, Hsla, TestAppContext};
 833    use language::language_settings::AllLanguageSettings;
 834    use lsp::CompletionItemLabelDetails;
 835    use settings::SettingsStore;
 836    use theme::SyntaxTheme;
 837
 838    #[gpui::test]
 839    async fn test_process_rust_diagnostics() {
 840        let mut params = lsp::PublishDiagnosticsParams {
 841            uri: lsp::Url::from_file_path("/a").unwrap(),
 842            version: None,
 843            diagnostics: vec![
 844                // no newlines
 845                lsp::Diagnostic {
 846                    message: "use of moved value `a`".to_string(),
 847                    ..Default::default()
 848                },
 849                // newline at the end of a code span
 850                lsp::Diagnostic {
 851                    message: "consider importing this struct: `use b::c;\n`".to_string(),
 852                    ..Default::default()
 853                },
 854                // code span starting right after a newline
 855                lsp::Diagnostic {
 856                    message: "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
 857                        .to_string(),
 858                    ..Default::default()
 859                },
 860            ],
 861        };
 862        RustLspAdapter.process_diagnostics(&mut params);
 863
 864        assert_eq!(params.diagnostics[0].message, "use of moved value `a`");
 865
 866        // remove trailing newline from code span
 867        assert_eq!(
 868            params.diagnostics[1].message,
 869            "consider importing this struct: `use b::c;`"
 870        );
 871
 872        // do not remove newline before the start of code span
 873        assert_eq!(
 874            params.diagnostics[2].message,
 875            "cannot borrow `self.d` as mutable\n`self` is a `&` reference"
 876        );
 877    }
 878
 879    #[gpui::test]
 880    async fn test_rust_label_for_completion() {
 881        let adapter = Arc::new(RustLspAdapter);
 882        let language = language("rust", tree_sitter_rust::LANGUAGE.into());
 883        let grammar = language.grammar().unwrap();
 884        let theme = SyntaxTheme::new_test([
 885            ("type", Hsla::default()),
 886            ("keyword", Hsla::default()),
 887            ("function", Hsla::default()),
 888            ("property", Hsla::default()),
 889        ]);
 890
 891        language.set_theme(&theme);
 892
 893        let highlight_function = grammar.highlight_id_for_name("function").unwrap();
 894        let highlight_type = grammar.highlight_id_for_name("type").unwrap();
 895        let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
 896        let highlight_field = grammar.highlight_id_for_name("property").unwrap();
 897
 898        assert_eq!(
 899            adapter
 900                .label_for_completion(
 901                    &lsp::CompletionItem {
 902                        kind: Some(lsp::CompletionItemKind::FUNCTION),
 903                        label: "hello(…)".to_string(),
 904                        label_details: Some(CompletionItemLabelDetails {
 905                            detail: Some("(use crate::foo)".into()),
 906                            description: Some("fn(&mut Option<T>) -> Vec<T>".to_string())
 907                        }),
 908                        ..Default::default()
 909                    },
 910                    &language
 911                )
 912                .await,
 913            Some(CodeLabel {
 914                text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
 915                filter_range: 0..5,
 916                runs: vec![
 917                    (0..5, highlight_function),
 918                    (7..10, highlight_keyword),
 919                    (11..17, highlight_type),
 920                    (18..19, highlight_type),
 921                    (25..28, highlight_type),
 922                    (29..30, highlight_type),
 923                ],
 924            })
 925        );
 926        assert_eq!(
 927            adapter
 928                .label_for_completion(
 929                    &lsp::CompletionItem {
 930                        kind: Some(lsp::CompletionItemKind::FUNCTION),
 931                        label: "hello(…)".to_string(),
 932                        label_details: Some(CompletionItemLabelDetails {
 933                            detail: Some(" (use crate::foo)".into()),
 934                            description: Some("async fn(&mut Option<T>) -> Vec<T>".to_string()),
 935                        }),
 936                        ..Default::default()
 937                    },
 938                    &language
 939                )
 940                .await,
 941            Some(CodeLabel {
 942                text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
 943                filter_range: 0..5,
 944                runs: vec![
 945                    (0..5, highlight_function),
 946                    (7..10, highlight_keyword),
 947                    (11..17, highlight_type),
 948                    (18..19, highlight_type),
 949                    (25..28, highlight_type),
 950                    (29..30, highlight_type),
 951                ],
 952            })
 953        );
 954        assert_eq!(
 955            adapter
 956                .label_for_completion(
 957                    &lsp::CompletionItem {
 958                        kind: Some(lsp::CompletionItemKind::FIELD),
 959                        label: "len".to_string(),
 960                        detail: Some("usize".to_string()),
 961                        ..Default::default()
 962                    },
 963                    &language
 964                )
 965                .await,
 966            Some(CodeLabel {
 967                text: "len: usize".to_string(),
 968                filter_range: 0..3,
 969                runs: vec![(0..3, highlight_field), (5..10, highlight_type),],
 970            })
 971        );
 972
 973        assert_eq!(
 974            adapter
 975                .label_for_completion(
 976                    &lsp::CompletionItem {
 977                        kind: Some(lsp::CompletionItemKind::FUNCTION),
 978                        label: "hello(…)".to_string(),
 979                        label_details: Some(CompletionItemLabelDetails {
 980                            detail: Some(" (use crate::foo)".to_string()),
 981                            description: Some("fn(&mut Option<T>) -> Vec<T>".to_string()),
 982                        }),
 983
 984                        ..Default::default()
 985                    },
 986                    &language
 987                )
 988                .await,
 989            Some(CodeLabel {
 990                text: "hello(&mut Option<T>) -> Vec<T> (use crate::foo)".to_string(),
 991                filter_range: 0..5,
 992                runs: vec![
 993                    (0..5, highlight_function),
 994                    (7..10, highlight_keyword),
 995                    (11..17, highlight_type),
 996                    (18..19, highlight_type),
 997                    (25..28, highlight_type),
 998                    (29..30, highlight_type),
 999                ],
1000            })
1001        );
1002    }
1003
1004    #[gpui::test]
1005    async fn test_rust_label_for_symbol() {
1006        let adapter = Arc::new(RustLspAdapter);
1007        let language = language("rust", tree_sitter_rust::LANGUAGE.into());
1008        let grammar = language.grammar().unwrap();
1009        let theme = SyntaxTheme::new_test([
1010            ("type", Hsla::default()),
1011            ("keyword", Hsla::default()),
1012            ("function", Hsla::default()),
1013            ("property", Hsla::default()),
1014        ]);
1015
1016        language.set_theme(&theme);
1017
1018        let highlight_function = grammar.highlight_id_for_name("function").unwrap();
1019        let highlight_type = grammar.highlight_id_for_name("type").unwrap();
1020        let highlight_keyword = grammar.highlight_id_for_name("keyword").unwrap();
1021
1022        assert_eq!(
1023            adapter
1024                .label_for_symbol("hello", lsp::SymbolKind::FUNCTION, &language)
1025                .await,
1026            Some(CodeLabel {
1027                text: "fn hello".to_string(),
1028                filter_range: 3..8,
1029                runs: vec![(0..2, highlight_keyword), (3..8, highlight_function)],
1030            })
1031        );
1032
1033        assert_eq!(
1034            adapter
1035                .label_for_symbol("World", lsp::SymbolKind::TYPE_PARAMETER, &language)
1036                .await,
1037            Some(CodeLabel {
1038                text: "type World".to_string(),
1039                filter_range: 5..10,
1040                runs: vec![(0..4, highlight_keyword), (5..10, highlight_type)],
1041            })
1042        );
1043    }
1044
1045    #[gpui::test]
1046    async fn test_rust_autoindent(cx: &mut TestAppContext) {
1047        // cx.executor().set_block_on_ticks(usize::MAX..=usize::MAX);
1048        cx.update(|cx| {
1049            let test_settings = SettingsStore::test(cx);
1050            cx.set_global(test_settings);
1051            language::init(cx);
1052            cx.update_global::<SettingsStore, _>(|store, cx| {
1053                store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1054                    s.defaults.tab_size = NonZeroU32::new(2);
1055                });
1056            });
1057        });
1058
1059        let language = crate::language("rust", tree_sitter_rust::LANGUAGE.into());
1060
1061        cx.new_model(|cx| {
1062            let mut buffer = Buffer::local("", cx).with_language(language, cx);
1063
1064            // indent between braces
1065            buffer.set_text("fn a() {}", cx);
1066            let ix = buffer.len() - 1;
1067            buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1068            assert_eq!(buffer.text(), "fn a() {\n  \n}");
1069
1070            // indent between braces, even after empty lines
1071            buffer.set_text("fn a() {\n\n\n}", cx);
1072            let ix = buffer.len() - 2;
1073            buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1074            assert_eq!(buffer.text(), "fn a() {\n\n\n  \n}");
1075
1076            // indent a line that continues a field expression
1077            buffer.set_text("fn a() {\n  \n}", cx);
1078            let ix = buffer.len() - 2;
1079            buffer.edit([(ix..ix, "b\n.c")], Some(AutoindentMode::EachLine), cx);
1080            assert_eq!(buffer.text(), "fn a() {\n  b\n    .c\n}");
1081
1082            // indent further lines that continue the field expression, even after empty lines
1083            let ix = buffer.len() - 2;
1084            buffer.edit([(ix..ix, "\n\n.d")], Some(AutoindentMode::EachLine), cx);
1085            assert_eq!(buffer.text(), "fn a() {\n  b\n    .c\n    \n    .d\n}");
1086
1087            // dedent the line after the field expression
1088            let ix = buffer.len() - 2;
1089            buffer.edit([(ix..ix, ";\ne")], Some(AutoindentMode::EachLine), cx);
1090            assert_eq!(
1091                buffer.text(),
1092                "fn a() {\n  b\n    .c\n    \n    .d;\n  e\n}"
1093            );
1094
1095            // indent inside a struct within a call
1096            buffer.set_text("const a: B = c(D {});", cx);
1097            let ix = buffer.len() - 3;
1098            buffer.edit([(ix..ix, "\n\n")], Some(AutoindentMode::EachLine), cx);
1099            assert_eq!(buffer.text(), "const a: B = c(D {\n  \n});");
1100
1101            // indent further inside a nested call
1102            let ix = buffer.len() - 4;
1103            buffer.edit([(ix..ix, "e: f(\n\n)")], Some(AutoindentMode::EachLine), cx);
1104            assert_eq!(buffer.text(), "const a: B = c(D {\n  e: f(\n    \n  )\n});");
1105
1106            // keep that indent after an empty line
1107            let ix = buffer.len() - 8;
1108            buffer.edit([(ix..ix, "\n")], Some(AutoindentMode::EachLine), cx);
1109            assert_eq!(
1110                buffer.text(),
1111                "const a: B = c(D {\n  e: f(\n    \n    \n  )\n});"
1112            );
1113
1114            buffer
1115        });
1116    }
1117
1118    #[test]
1119    fn test_package_name_from_pkgid() {
1120        for (input, expected) in [
1121            (
1122                "path+file:///absolute/path/to/project/zed/crates/zed#0.131.0",
1123                "zed",
1124            ),
1125            (
1126                "path+file:///absolute/path/to/project/custom-package#my-custom-package@0.1.0",
1127                "my-custom-package",
1128            ),
1129        ] {
1130            assert_eq!(package_name_from_pkgid(input), Some(expected));
1131        }
1132    }
1133
1134    #[test]
1135    fn test_retrieve_package_id_and_bin_name_from_metadata() {
1136        for (input, absolute_path, expected) in [
1137            (
1138                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"}]}]}"#,
1139                "/path/to/zed/src/main.rs",
1140                Some((
1141                    "path+file:///path/to/zed/crates/zed#0.131.0",
1142                    "zed",
1143                    TargetKind::Bin,
1144                )),
1145            ),
1146            (
1147                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"}]}]}"#,
1148                "/path/to/custom-package/src/main.rs",
1149                Some((
1150                    "path+file:///path/to/custom-package#my-custom-package@0.1.0",
1151                    "my-custom-bin",
1152                    TargetKind::Bin,
1153                )),
1154            ),
1155            (
1156                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"}]}]}"#,
1157                "/path/to/custom-package/src/main.rs",
1158                Some((
1159                    "path+file:///path/to/custom-package#my-custom-package@0.1.0",
1160                    "my-custom-bin",
1161                    TargetKind::Example,
1162                )),
1163            ),
1164            (
1165                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"}]}]}"#,
1166                "/path/to/custom-package/src/main.rs",
1167                None,
1168            ),
1169        ] {
1170            let metadata: CargoMetadata = serde_json::from_str(input).unwrap();
1171
1172            let absolute_path = Path::new(absolute_path);
1173
1174            assert_eq!(
1175                retrieve_package_id_and_bin_name_from_metadata(metadata, absolute_path),
1176                expected.map(|(pkgid, name, kind)| (pkgid.to_owned(), name.to_owned(), kind))
1177            );
1178        }
1179    }
1180}