rust.rs

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