rust.rs

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