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