language.rs

   1//! The `language` crate provides a large chunk of Zed's language-related
   2//! features (the other big contributors being project and lsp crates that revolve around LSP features).
   3//! Namely, this crate:
   4//! - Provides [`Language`], [`Grammar`] and [`LanguageRegistry`] types that
   5//!   use Tree-sitter to provide syntax highlighting to the editor; note though that `language` doesn't perform the highlighting by itself. It only maps ranges in a buffer to colors. Treesitter is also used for buffer outlines (lists of symbols in a buffer)
   6//! - Exposes [`LanguageConfig`] that describes how constructs (like brackets or line comments) should be handled by the editor for a source file of a particular language.
   7//!
   8//! Notably we do *not* assign a single language to a single file; in real world a single file can consist of multiple programming languages - HTML is a good example of that - and `language` crate tends to reflect that status quo in its API.
   9mod buffer;
  10mod diagnostic_set;
  11mod highlight_map;
  12mod language_registry;
  13pub mod language_settings;
  14mod manifest;
  15mod outline;
  16pub mod proto;
  17mod syntax_map;
  18mod task_context;
  19mod text_diff;
  20mod toolchain;
  21
  22#[cfg(test)]
  23pub mod buffer_tests;
  24
  25use crate::language_settings::SoftWrap;
  26pub use crate::language_settings::{EditPredictionsMode, IndentGuideSettings};
  27use anyhow::{Context as _, Result};
  28use async_trait::async_trait;
  29use collections::{HashMap, HashSet, IndexSet};
  30use futures::Future;
  31use gpui::{App, AsyncApp, Entity, SharedString};
  32pub use highlight_map::HighlightMap;
  33use http_client::HttpClient;
  34pub use language_registry::{
  35    LanguageName, LanguageServerStatusUpdate, LoadedLanguage, ServerHealth,
  36};
  37use lsp::{CodeActionKind, InitializeParams, LanguageServerBinary, LanguageServerBinaryOptions};
  38pub use manifest::{ManifestDelegate, ManifestName, ManifestProvider, ManifestQuery};
  39use parking_lot::Mutex;
  40use regex::Regex;
  41use schemars::{JsonSchema, SchemaGenerator, json_schema};
  42use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
  43use serde_json::Value;
  44use settings::WorktreeId;
  45use smol::future::FutureExt as _;
  46use std::num::NonZeroU32;
  47use std::{
  48    ffi::OsStr,
  49    fmt::Debug,
  50    hash::Hash,
  51    mem,
  52    ops::{DerefMut, Range},
  53    path::{Path, PathBuf},
  54    pin::Pin,
  55    str,
  56    sync::{
  57        Arc, LazyLock,
  58        atomic::{AtomicUsize, Ordering::SeqCst},
  59    },
  60};
  61use syntax_map::{QueryCursorHandle, SyntaxSnapshot};
  62use task::RunnableTag;
  63pub use task_context::{ContextLocation, ContextProvider, RunnableRange};
  64pub use text_diff::{
  65    DiffOptions, apply_diff_patch, line_diff, text_diff, text_diff_with_options, unified_diff,
  66};
  67use theme::SyntaxTheme;
  68pub use toolchain::{
  69    LanguageToolchainStore, LocalLanguageToolchainStore, Toolchain, ToolchainList, ToolchainLister,
  70    ToolchainMetadata, ToolchainScope,
  71};
  72use tree_sitter::{self, Query, QueryCursor, WasmStore, wasmtime};
  73use util::rel_path::RelPath;
  74use util::serde::default_true;
  75
  76pub use buffer::Operation;
  77pub use buffer::*;
  78pub use diagnostic_set::{DiagnosticEntry, DiagnosticEntryRef, DiagnosticGroup};
  79pub use language_registry::{
  80    AvailableLanguage, BinaryStatus, LanguageNotFound, LanguageQueries, LanguageRegistry,
  81    QUERY_FILENAME_PREFIXES,
  82};
  83pub use lsp::{LanguageServerId, LanguageServerName};
  84pub use outline::*;
  85pub use syntax_map::{
  86    OwnedSyntaxLayer, SyntaxLayer, SyntaxMapMatches, ToTreeSitterPoint, TreeSitterOptions,
  87};
  88pub use text::{AnchorRangeExt, LineEnding};
  89pub use tree_sitter::{Node, Parser, Tree, TreeCursor};
  90
  91/// Initializes the `language` crate.
  92///
  93/// This should be called before making use of items from the create.
  94pub fn init(cx: &mut App) {
  95    language_settings::init(cx);
  96}
  97
  98static QUERY_CURSORS: Mutex<Vec<QueryCursor>> = Mutex::new(vec![]);
  99static PARSERS: Mutex<Vec<Parser>> = Mutex::new(vec![]);
 100
 101pub fn with_parser<F, R>(func: F) -> R
 102where
 103    F: FnOnce(&mut Parser) -> R,
 104{
 105    let mut parser = PARSERS.lock().pop().unwrap_or_else(|| {
 106        let mut parser = Parser::new();
 107        parser
 108            .set_wasm_store(WasmStore::new(&WASM_ENGINE).unwrap())
 109            .unwrap();
 110        parser
 111    });
 112    parser.set_included_ranges(&[]).unwrap();
 113    let result = func(&mut parser);
 114    PARSERS.lock().push(parser);
 115    result
 116}
 117
 118pub fn with_query_cursor<F, R>(func: F) -> R
 119where
 120    F: FnOnce(&mut QueryCursor) -> R,
 121{
 122    let mut cursor = QueryCursorHandle::new();
 123    func(cursor.deref_mut())
 124}
 125
 126static NEXT_LANGUAGE_ID: AtomicUsize = AtomicUsize::new(0);
 127static NEXT_GRAMMAR_ID: AtomicUsize = AtomicUsize::new(0);
 128static WASM_ENGINE: LazyLock<wasmtime::Engine> = LazyLock::new(|| {
 129    wasmtime::Engine::new(&wasmtime::Config::new()).expect("Failed to create Wasmtime engine")
 130});
 131
 132/// A shared grammar for plain text, exposed for reuse by downstream crates.
 133pub static PLAIN_TEXT: LazyLock<Arc<Language>> = LazyLock::new(|| {
 134    Arc::new(Language::new(
 135        LanguageConfig {
 136            name: "Plain Text".into(),
 137            soft_wrap: Some(SoftWrap::EditorWidth),
 138            matcher: LanguageMatcher {
 139                path_suffixes: vec!["txt".to_owned()],
 140                first_line_pattern: None,
 141            },
 142            ..Default::default()
 143        },
 144        None,
 145    ))
 146});
 147
 148/// Types that represent a position in a buffer, and can be converted into
 149/// an LSP position, to send to a language server.
 150pub trait ToLspPosition {
 151    /// Converts the value into an LSP position.
 152    fn to_lsp_position(self) -> lsp::Position;
 153}
 154
 155#[derive(Debug, Clone, PartialEq, Eq, Hash)]
 156pub struct Location {
 157    pub buffer: Entity<Buffer>,
 158    pub range: Range<Anchor>,
 159}
 160
 161type ServerBinaryCache = futures::lock::Mutex<Option<(bool, LanguageServerBinary)>>;
 162
 163/// Represents a Language Server, with certain cached sync properties.
 164/// Uses [`LspAdapter`] under the hood, but calls all 'static' methods
 165/// once at startup, and caches the results.
 166pub struct CachedLspAdapter {
 167    pub name: LanguageServerName,
 168    pub disk_based_diagnostic_sources: Vec<String>,
 169    pub disk_based_diagnostics_progress_token: Option<String>,
 170    language_ids: HashMap<LanguageName, String>,
 171    pub adapter: Arc<dyn LspAdapter>,
 172    cached_binary: ServerBinaryCache,
 173}
 174
 175impl Debug for CachedLspAdapter {
 176    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 177        f.debug_struct("CachedLspAdapter")
 178            .field("name", &self.name)
 179            .field(
 180                "disk_based_diagnostic_sources",
 181                &self.disk_based_diagnostic_sources,
 182            )
 183            .field(
 184                "disk_based_diagnostics_progress_token",
 185                &self.disk_based_diagnostics_progress_token,
 186            )
 187            .field("language_ids", &self.language_ids)
 188            .finish_non_exhaustive()
 189    }
 190}
 191
 192impl CachedLspAdapter {
 193    pub fn new(adapter: Arc<dyn LspAdapter>) -> Arc<Self> {
 194        let name = adapter.name();
 195        let disk_based_diagnostic_sources = adapter.disk_based_diagnostic_sources();
 196        let disk_based_diagnostics_progress_token = adapter.disk_based_diagnostics_progress_token();
 197        let language_ids = adapter.language_ids();
 198
 199        Arc::new(CachedLspAdapter {
 200            name,
 201            disk_based_diagnostic_sources,
 202            disk_based_diagnostics_progress_token,
 203            language_ids,
 204            adapter,
 205            cached_binary: Default::default(),
 206        })
 207    }
 208
 209    pub fn name(&self) -> LanguageServerName {
 210        self.adapter.name()
 211    }
 212
 213    pub async fn get_language_server_command(
 214        self: Arc<Self>,
 215        delegate: Arc<dyn LspAdapterDelegate>,
 216        toolchains: Option<Toolchain>,
 217        binary_options: LanguageServerBinaryOptions,
 218        cx: &mut AsyncApp,
 219    ) -> Result<LanguageServerBinary> {
 220        let mut cached_binary = self.cached_binary.lock().await;
 221        self.adapter
 222            .clone()
 223            .get_language_server_command(
 224                delegate,
 225                toolchains,
 226                binary_options,
 227                &mut cached_binary,
 228                cx,
 229            )
 230            .await
 231    }
 232
 233    pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
 234        self.adapter.code_action_kinds()
 235    }
 236
 237    pub fn process_diagnostics(
 238        &self,
 239        params: &mut lsp::PublishDiagnosticsParams,
 240        server_id: LanguageServerId,
 241        existing_diagnostics: Option<&'_ Buffer>,
 242    ) {
 243        self.adapter
 244            .process_diagnostics(params, server_id, existing_diagnostics)
 245    }
 246
 247    pub fn retain_old_diagnostic(&self, previous_diagnostic: &Diagnostic, cx: &App) -> bool {
 248        self.adapter.retain_old_diagnostic(previous_diagnostic, cx)
 249    }
 250
 251    pub fn underline_diagnostic(&self, diagnostic: &lsp::Diagnostic) -> bool {
 252        self.adapter.underline_diagnostic(diagnostic)
 253    }
 254
 255    pub fn diagnostic_message_to_markdown(&self, message: &str) -> Option<String> {
 256        self.adapter.diagnostic_message_to_markdown(message)
 257    }
 258
 259    pub async fn process_completions(&self, completion_items: &mut [lsp::CompletionItem]) {
 260        self.adapter.process_completions(completion_items).await
 261    }
 262
 263    pub async fn labels_for_completions(
 264        &self,
 265        completion_items: &[lsp::CompletionItem],
 266        language: &Arc<Language>,
 267    ) -> Result<Vec<Option<CodeLabel>>> {
 268        self.adapter
 269            .clone()
 270            .labels_for_completions(completion_items, language)
 271            .await
 272    }
 273
 274    pub async fn labels_for_symbols(
 275        &self,
 276        symbols: &[(String, lsp::SymbolKind)],
 277        language: &Arc<Language>,
 278    ) -> Result<Vec<Option<CodeLabel>>> {
 279        self.adapter
 280            .clone()
 281            .labels_for_symbols(symbols, language)
 282            .await
 283    }
 284
 285    pub fn language_id(&self, language_name: &LanguageName) -> String {
 286        self.language_ids
 287            .get(language_name)
 288            .cloned()
 289            .unwrap_or_else(|| language_name.lsp_id())
 290    }
 291}
 292
 293/// [`LspAdapterDelegate`] allows [`LspAdapter]` implementations to interface with the application
 294// e.g. to display a notification or fetch data from the web.
 295#[async_trait]
 296pub trait LspAdapterDelegate: Send + Sync {
 297    fn show_notification(&self, message: &str, cx: &mut App);
 298    fn http_client(&self) -> Arc<dyn HttpClient>;
 299    fn worktree_id(&self) -> WorktreeId;
 300    fn worktree_root_path(&self) -> &Path;
 301    fn update_status(&self, language: LanguageServerName, status: BinaryStatus);
 302    fn registered_lsp_adapters(&self) -> Vec<Arc<dyn LspAdapter>>;
 303    async fn language_server_download_dir(&self, name: &LanguageServerName) -> Option<Arc<Path>>;
 304
 305    async fn npm_package_installed_version(
 306        &self,
 307        package_name: &str,
 308    ) -> Result<Option<(PathBuf, String)>>;
 309    async fn which(&self, command: &OsStr) -> Option<PathBuf>;
 310    async fn shell_env(&self) -> HashMap<String, String>;
 311    async fn read_text_file(&self, path: &RelPath) -> Result<String>;
 312    async fn try_exec(&self, binary: LanguageServerBinary) -> Result<()>;
 313}
 314
 315#[async_trait(?Send)]
 316pub trait LspAdapter: 'static + Send + Sync + DynLspInstaller {
 317    fn name(&self) -> LanguageServerName;
 318
 319    fn process_diagnostics(
 320        &self,
 321        _: &mut lsp::PublishDiagnosticsParams,
 322        _: LanguageServerId,
 323        _: Option<&'_ Buffer>,
 324    ) {
 325    }
 326
 327    /// When processing new `lsp::PublishDiagnosticsParams` diagnostics, whether to retain previous one(s) or not.
 328    fn retain_old_diagnostic(&self, _previous_diagnostic: &Diagnostic, _cx: &App) -> bool {
 329        false
 330    }
 331
 332    /// Whether to underline a given diagnostic or not, when rendering in the editor.
 333    ///
 334    /// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#diagnosticTag
 335    /// states that
 336    /// > Clients are allowed to render diagnostics with this tag faded out instead of having an error squiggle.
 337    /// for the unnecessary diagnostics, so do not underline them.
 338    fn underline_diagnostic(&self, _diagnostic: &lsp::Diagnostic) -> bool {
 339        true
 340    }
 341
 342    /// Post-processes completions provided by the language server.
 343    async fn process_completions(&self, _: &mut [lsp::CompletionItem]) {}
 344
 345    fn diagnostic_message_to_markdown(&self, _message: &str) -> Option<String> {
 346        None
 347    }
 348
 349    async fn labels_for_completions(
 350        self: Arc<Self>,
 351        completions: &[lsp::CompletionItem],
 352        language: &Arc<Language>,
 353    ) -> Result<Vec<Option<CodeLabel>>> {
 354        let mut labels = Vec::new();
 355        for (ix, completion) in completions.iter().enumerate() {
 356            let label = self.label_for_completion(completion, language).await;
 357            if let Some(label) = label {
 358                labels.resize(ix + 1, None);
 359                *labels.last_mut().unwrap() = Some(label);
 360            }
 361        }
 362        Ok(labels)
 363    }
 364
 365    async fn label_for_completion(
 366        &self,
 367        _: &lsp::CompletionItem,
 368        _: &Arc<Language>,
 369    ) -> Option<CodeLabel> {
 370        None
 371    }
 372
 373    async fn labels_for_symbols(
 374        self: Arc<Self>,
 375        symbols: &[(String, lsp::SymbolKind)],
 376        language: &Arc<Language>,
 377    ) -> Result<Vec<Option<CodeLabel>>> {
 378        let mut labels = Vec::new();
 379        for (ix, (name, kind)) in symbols.iter().enumerate() {
 380            let label = self.label_for_symbol(name, *kind, language).await;
 381            if let Some(label) = label {
 382                labels.resize(ix + 1, None);
 383                *labels.last_mut().unwrap() = Some(label);
 384            }
 385        }
 386        Ok(labels)
 387    }
 388
 389    async fn label_for_symbol(
 390        &self,
 391        _: &str,
 392        _: lsp::SymbolKind,
 393        _: &Arc<Language>,
 394    ) -> Option<CodeLabel> {
 395        None
 396    }
 397
 398    /// Returns initialization options that are going to be sent to a LSP server as a part of [`lsp::InitializeParams`]
 399    async fn initialization_options(
 400        self: Arc<Self>,
 401        _: &Arc<dyn LspAdapterDelegate>,
 402    ) -> Result<Option<Value>> {
 403        Ok(None)
 404    }
 405
 406    async fn workspace_configuration(
 407        self: Arc<Self>,
 408        _: &Arc<dyn LspAdapterDelegate>,
 409        _: Option<Toolchain>,
 410        _cx: &mut AsyncApp,
 411    ) -> Result<Value> {
 412        Ok(serde_json::json!({}))
 413    }
 414
 415    async fn additional_initialization_options(
 416        self: Arc<Self>,
 417        _target_language_server_id: LanguageServerName,
 418        _: &Arc<dyn LspAdapterDelegate>,
 419    ) -> Result<Option<Value>> {
 420        Ok(None)
 421    }
 422
 423    async fn additional_workspace_configuration(
 424        self: Arc<Self>,
 425        _target_language_server_id: LanguageServerName,
 426        _: &Arc<dyn LspAdapterDelegate>,
 427        _cx: &mut AsyncApp,
 428    ) -> Result<Option<Value>> {
 429        Ok(None)
 430    }
 431
 432    /// Returns a list of code actions supported by a given LspAdapter
 433    fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
 434        None
 435    }
 436
 437    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
 438        Default::default()
 439    }
 440
 441    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
 442        None
 443    }
 444
 445    fn language_ids(&self) -> HashMap<LanguageName, String> {
 446        HashMap::default()
 447    }
 448
 449    /// Support custom initialize params.
 450    fn prepare_initialize_params(
 451        &self,
 452        original: InitializeParams,
 453        _: &App,
 454    ) -> Result<InitializeParams> {
 455        Ok(original)
 456    }
 457
 458    /// Method only implemented by the default JSON language server adapter.
 459    /// Used to provide dynamic reloading of the JSON schemas used to
 460    /// provide autocompletion and diagnostics in Zed setting and keybind
 461    /// files
 462    fn is_primary_zed_json_schema_adapter(&self) -> bool {
 463        false
 464    }
 465
 466    /// True for the extension adapter and false otherwise.
 467    fn is_extension(&self) -> bool {
 468        false
 469    }
 470}
 471
 472pub trait LspInstaller {
 473    type BinaryVersion;
 474    fn check_if_user_installed(
 475        &self,
 476        _: &dyn LspAdapterDelegate,
 477        _: Option<Toolchain>,
 478        _: &AsyncApp,
 479    ) -> impl Future<Output = Option<LanguageServerBinary>> {
 480        async { None }
 481    }
 482
 483    fn fetch_latest_server_version(
 484        &self,
 485        delegate: &dyn LspAdapterDelegate,
 486        pre_release: bool,
 487        cx: &mut AsyncApp,
 488    ) -> impl Future<Output = Result<Self::BinaryVersion>>;
 489
 490    fn check_if_version_installed(
 491        &self,
 492        _version: &Self::BinaryVersion,
 493        _container_dir: &PathBuf,
 494        _delegate: &dyn LspAdapterDelegate,
 495    ) -> impl Future<Output = Option<LanguageServerBinary>> {
 496        async { None }
 497    }
 498
 499    fn fetch_server_binary(
 500        &self,
 501        latest_version: Self::BinaryVersion,
 502        container_dir: PathBuf,
 503        delegate: &dyn LspAdapterDelegate,
 504    ) -> impl Future<Output = Result<LanguageServerBinary>>;
 505
 506    fn cached_server_binary(
 507        &self,
 508        container_dir: PathBuf,
 509        delegate: &dyn LspAdapterDelegate,
 510    ) -> impl Future<Output = Option<LanguageServerBinary>>;
 511}
 512
 513#[async_trait(?Send)]
 514pub trait DynLspInstaller {
 515    async fn try_fetch_server_binary(
 516        &self,
 517        delegate: &Arc<dyn LspAdapterDelegate>,
 518        container_dir: PathBuf,
 519        pre_release: bool,
 520        cx: &mut AsyncApp,
 521    ) -> Result<LanguageServerBinary>;
 522    fn get_language_server_command<'a>(
 523        self: Arc<Self>,
 524        delegate: Arc<dyn LspAdapterDelegate>,
 525        toolchains: Option<Toolchain>,
 526        binary_options: LanguageServerBinaryOptions,
 527        cached_binary: &'a mut Option<(bool, LanguageServerBinary)>,
 528        cx: &'a mut AsyncApp,
 529    ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>>;
 530}
 531
 532#[async_trait(?Send)]
 533impl<LI, BinaryVersion> DynLspInstaller for LI
 534where
 535    LI: LspInstaller<BinaryVersion = BinaryVersion> + LspAdapter,
 536{
 537    async fn try_fetch_server_binary(
 538        &self,
 539        delegate: &Arc<dyn LspAdapterDelegate>,
 540        container_dir: PathBuf,
 541        pre_release: bool,
 542        cx: &mut AsyncApp,
 543    ) -> Result<LanguageServerBinary> {
 544        let name = self.name();
 545
 546        log::debug!("fetching latest version of language server {:?}", name.0);
 547        delegate.update_status(name.clone(), BinaryStatus::CheckingForUpdate);
 548
 549        let latest_version = self
 550            .fetch_latest_server_version(delegate.as_ref(), pre_release, cx)
 551            .await?;
 552
 553        if let Some(binary) = self
 554            .check_if_version_installed(&latest_version, &container_dir, delegate.as_ref())
 555            .await
 556        {
 557            log::debug!("language server {:?} is already installed", name.0);
 558            delegate.update_status(name.clone(), BinaryStatus::None);
 559            Ok(binary)
 560        } else {
 561            log::debug!("downloading language server {:?}", name.0);
 562            delegate.update_status(name.clone(), BinaryStatus::Downloading);
 563            let binary = self
 564                .fetch_server_binary(latest_version, container_dir, delegate.as_ref())
 565                .await;
 566
 567            delegate.update_status(name.clone(), BinaryStatus::None);
 568            binary
 569        }
 570    }
 571    fn get_language_server_command<'a>(
 572        self: Arc<Self>,
 573        delegate: Arc<dyn LspAdapterDelegate>,
 574        toolchain: Option<Toolchain>,
 575        binary_options: LanguageServerBinaryOptions,
 576        cached_binary: &'a mut Option<(bool, LanguageServerBinary)>,
 577        cx: &'a mut AsyncApp,
 578    ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
 579        async move {
 580            // First we check whether the adapter can give us a user-installed binary.
 581            // If so, we do *not* want to cache that, because each worktree might give us a different
 582            // binary:
 583            //
 584            //      worktree 1: user-installed at `.bin/gopls`
 585            //      worktree 2: user-installed at `~/bin/gopls`
 586            //      worktree 3: no gopls found in PATH -> fallback to Zed installation
 587            //
 588            // We only want to cache when we fall back to the global one,
 589            // because we don't want to download and overwrite our global one
 590            // for each worktree we might have open.
 591            if binary_options.allow_path_lookup
 592                && let Some(binary) = self
 593                    .check_if_user_installed(delegate.as_ref(), toolchain, cx)
 594                    .await
 595            {
 596                log::info!(
 597                    "found user-installed language server for {}. path: {:?}, arguments: {:?}",
 598                    self.name().0,
 599                    binary.path,
 600                    binary.arguments
 601                );
 602                return Ok(binary);
 603            }
 604
 605            anyhow::ensure!(
 606                binary_options.allow_binary_download,
 607                "downloading language servers disabled"
 608            );
 609
 610            if let Some((pre_release, cached_binary)) = cached_binary
 611                && *pre_release == binary_options.pre_release
 612            {
 613                return Ok(cached_binary.clone());
 614            }
 615
 616            let Some(container_dir) = delegate.language_server_download_dir(&self.name()).await
 617            else {
 618                anyhow::bail!("no language server download dir defined")
 619            };
 620
 621            let mut binary = self
 622                .try_fetch_server_binary(
 623                    &delegate,
 624                    container_dir.to_path_buf(),
 625                    binary_options.pre_release,
 626                    cx,
 627                )
 628                .await;
 629
 630            if let Err(error) = binary.as_ref() {
 631                if let Some(prev_downloaded_binary) = self
 632                    .cached_server_binary(container_dir.to_path_buf(), delegate.as_ref())
 633                    .await
 634                {
 635                    log::info!(
 636                        "failed to fetch newest version of language server {:?}. \
 637                        error: {:?}, falling back to using {:?}",
 638                        self.name(),
 639                        error,
 640                        prev_downloaded_binary.path
 641                    );
 642                    binary = Ok(prev_downloaded_binary);
 643                } else {
 644                    delegate.update_status(
 645                        self.name(),
 646                        BinaryStatus::Failed {
 647                            error: format!("{error:?}"),
 648                        },
 649                    );
 650                }
 651            }
 652
 653            if let Ok(binary) = &binary {
 654                *cached_binary = Some((binary_options.pre_release, binary.clone()));
 655            }
 656
 657            binary
 658        }
 659        .boxed_local()
 660    }
 661}
 662
 663#[derive(Clone, Debug, Default, PartialEq, Eq)]
 664pub struct CodeLabel {
 665    /// The text to display.
 666    pub text: String,
 667    /// Syntax highlighting runs.
 668    pub runs: Vec<(Range<usize>, HighlightId)>,
 669    /// The portion of the text that should be used in fuzzy filtering.
 670    pub filter_range: Range<usize>,
 671}
 672
 673#[derive(Clone, Debug, Default, PartialEq, Eq)]
 674pub struct CodeLabelBuilder {
 675    /// The text to display.
 676    text: String,
 677    /// Syntax highlighting runs.
 678    runs: Vec<(Range<usize>, HighlightId)>,
 679    /// The portion of the text that should be used in fuzzy filtering.
 680    filter_range: Range<usize>,
 681}
 682
 683#[derive(Clone, Deserialize, JsonSchema)]
 684pub struct LanguageConfig {
 685    /// Human-readable name of the language.
 686    pub name: LanguageName,
 687    /// The name of this language for a Markdown code fence block
 688    pub code_fence_block_name: Option<Arc<str>>,
 689    // The name of the grammar in a WASM bundle (experimental).
 690    pub grammar: Option<Arc<str>>,
 691    /// The criteria for matching this language to a given file.
 692    #[serde(flatten)]
 693    pub matcher: LanguageMatcher,
 694    /// List of bracket types in a language.
 695    #[serde(default)]
 696    pub brackets: BracketPairConfig,
 697    /// If set to true, auto indentation uses last non empty line to determine
 698    /// the indentation level for a new line.
 699    #[serde(default = "auto_indent_using_last_non_empty_line_default")]
 700    pub auto_indent_using_last_non_empty_line: bool,
 701    // Whether indentation of pasted content should be adjusted based on the context.
 702    #[serde(default)]
 703    pub auto_indent_on_paste: Option<bool>,
 704    /// A regex that is used to determine whether the indentation level should be
 705    /// increased in the following line.
 706    #[serde(default, deserialize_with = "deserialize_regex")]
 707    #[schemars(schema_with = "regex_json_schema")]
 708    pub increase_indent_pattern: Option<Regex>,
 709    /// A regex that is used to determine whether the indentation level should be
 710    /// decreased in the following line.
 711    #[serde(default, deserialize_with = "deserialize_regex")]
 712    #[schemars(schema_with = "regex_json_schema")]
 713    pub decrease_indent_pattern: Option<Regex>,
 714    /// A list of rules for decreasing indentation. Each rule pairs a regex with a set of valid
 715    /// "block-starting" tokens. When a line matches a pattern, its indentation is aligned with
 716    /// the most recent line that began with a corresponding token. This enables context-aware
 717    /// outdenting, like aligning an `else` with its `if`.
 718    #[serde(default)]
 719    pub decrease_indent_patterns: Vec<DecreaseIndentConfig>,
 720    /// A list of characters that trigger the automatic insertion of a closing
 721    /// bracket when they immediately precede the point where an opening
 722    /// bracket is inserted.
 723    #[serde(default)]
 724    pub autoclose_before: String,
 725    /// A placeholder used internally by Semantic Index.
 726    #[serde(default)]
 727    pub collapsed_placeholder: String,
 728    /// A line comment string that is inserted in e.g. `toggle comments` action.
 729    /// A language can have multiple flavours of line comments. All of the provided line comments are
 730    /// used for comment continuations on the next line, but only the first one is used for Editor::ToggleComments.
 731    #[serde(default)]
 732    pub line_comments: Vec<Arc<str>>,
 733    /// Delimiters and configuration for recognizing and formatting block comments.
 734    #[serde(default)]
 735    pub block_comment: Option<BlockCommentConfig>,
 736    /// Delimiters and configuration for recognizing and formatting documentation comments.
 737    #[serde(default, alias = "documentation")]
 738    pub documentation_comment: Option<BlockCommentConfig>,
 739    /// A list of additional regex patterns that should be treated as prefixes
 740    /// for creating boundaries during rewrapping, ensuring content from one
 741    /// prefixed section doesn't merge with another (e.g., markdown list items).
 742    /// By default, Zed treats as paragraph and comment prefixes as boundaries.
 743    #[serde(default, deserialize_with = "deserialize_regex_vec")]
 744    #[schemars(schema_with = "regex_vec_json_schema")]
 745    pub rewrap_prefixes: Vec<Regex>,
 746    /// A list of language servers that are allowed to run on subranges of a given language.
 747    #[serde(default)]
 748    pub scope_opt_in_language_servers: Vec<LanguageServerName>,
 749    #[serde(default)]
 750    pub overrides: HashMap<String, LanguageConfigOverride>,
 751    /// A list of characters that Zed should treat as word characters for the
 752    /// purpose of features that operate on word boundaries, like 'move to next word end'
 753    /// or a whole-word search in buffer search.
 754    #[serde(default)]
 755    pub word_characters: HashSet<char>,
 756    /// Whether to indent lines using tab characters, as opposed to multiple
 757    /// spaces.
 758    #[serde(default)]
 759    pub hard_tabs: Option<bool>,
 760    /// How many columns a tab should occupy.
 761    #[serde(default)]
 762    #[schemars(range(min = 1, max = 128))]
 763    pub tab_size: Option<NonZeroU32>,
 764    /// How to soft-wrap long lines of text.
 765    #[serde(default)]
 766    pub soft_wrap: Option<SoftWrap>,
 767    /// When set, selections can be wrapped using prefix/suffix pairs on both sides.
 768    #[serde(default)]
 769    pub wrap_characters: Option<WrapCharactersConfig>,
 770    /// The name of a Prettier parser that will be used for this language when no file path is available.
 771    /// If there's a parser name in the language settings, that will be used instead.
 772    #[serde(default)]
 773    pub prettier_parser_name: Option<String>,
 774    /// If true, this language is only for syntax highlighting via an injection into other
 775    /// languages, but should not appear to the user as a distinct language.
 776    #[serde(default)]
 777    pub hidden: bool,
 778    /// If configured, this language contains JSX style tags, and should support auto-closing of those tags.
 779    #[serde(default)]
 780    pub jsx_tag_auto_close: Option<JsxTagAutoCloseConfig>,
 781    /// A list of characters that Zed should treat as word characters for completion queries.
 782    #[serde(default)]
 783    pub completion_query_characters: HashSet<char>,
 784    /// A list of characters that Zed should treat as word characters for linked edit operations.
 785    #[serde(default)]
 786    pub linked_edit_characters: HashSet<char>,
 787    /// A list of preferred debuggers for this language.
 788    #[serde(default)]
 789    pub debuggers: IndexSet<SharedString>,
 790    /// A list of import namespace segments that aren't expected to appear in file paths. For
 791    /// example, "super" and "crate" in Rust.
 792    #[serde(default)]
 793    pub ignored_import_segments: HashSet<Arc<str>>,
 794    /// Regular expression that matches substrings to omit from import paths, to make the paths more
 795    /// similar to how they are specified when imported. For example, "/mod\.rs$" or "/__init__\.py$".
 796    #[serde(default, deserialize_with = "deserialize_regex")]
 797    #[schemars(schema_with = "regex_json_schema")]
 798    pub import_path_strip_regex: Option<Regex>,
 799}
 800
 801#[derive(Clone, Debug, Deserialize, Default, JsonSchema)]
 802pub struct DecreaseIndentConfig {
 803    #[serde(default, deserialize_with = "deserialize_regex")]
 804    #[schemars(schema_with = "regex_json_schema")]
 805    pub pattern: Option<Regex>,
 806    #[serde(default)]
 807    pub valid_after: Vec<String>,
 808}
 809
 810#[derive(Clone, Debug, Serialize, Deserialize, Default, JsonSchema)]
 811pub struct LanguageMatcher {
 812    /// Given a list of `LanguageConfig`'s, the language of a file can be determined based on the path extension matching any of the `path_suffixes`.
 813    #[serde(default)]
 814    pub path_suffixes: Vec<String>,
 815    /// A regex pattern that determines whether the language should be assigned to a file or not.
 816    #[serde(
 817        default,
 818        serialize_with = "serialize_regex",
 819        deserialize_with = "deserialize_regex"
 820    )]
 821    #[schemars(schema_with = "regex_json_schema")]
 822    pub first_line_pattern: Option<Regex>,
 823}
 824
 825/// The configuration for JSX tag auto-closing.
 826#[derive(Clone, Deserialize, JsonSchema)]
 827pub struct JsxTagAutoCloseConfig {
 828    /// The name of the node for a opening tag
 829    pub open_tag_node_name: String,
 830    /// The name of the node for an closing tag
 831    pub close_tag_node_name: String,
 832    /// The name of the node for a complete element with children for open and close tags
 833    pub jsx_element_node_name: String,
 834    /// The name of the node found within both opening and closing
 835    /// tags that describes the tag name
 836    pub tag_name_node_name: String,
 837    /// Alternate Node names for tag names.
 838    /// Specifically needed as TSX represents the name in `<Foo.Bar>`
 839    /// as `member_expression` rather than `identifier` as usual
 840    #[serde(default)]
 841    pub tag_name_node_name_alternates: Vec<String>,
 842    /// Some grammars are smart enough to detect a closing tag
 843    /// that is not valid i.e. doesn't match it's corresponding
 844    /// opening tag or does not have a corresponding opening tag
 845    /// This should be set to the name of the node for invalid
 846    /// closing tags if the grammar contains such a node, otherwise
 847    /// detecting already closed tags will not work properly
 848    #[serde(default)]
 849    pub erroneous_close_tag_node_name: Option<String>,
 850    /// See above for erroneous_close_tag_node_name for details
 851    /// This should be set if the node used for the tag name
 852    /// within erroneous closing tags is different from the
 853    /// normal tag name node name
 854    #[serde(default)]
 855    pub erroneous_close_tag_name_node_name: Option<String>,
 856}
 857
 858/// The configuration for block comments for this language.
 859#[derive(Clone, Debug, JsonSchema, PartialEq)]
 860pub struct BlockCommentConfig {
 861    /// A start tag of block comment.
 862    pub start: Arc<str>,
 863    /// A end tag of block comment.
 864    pub end: Arc<str>,
 865    /// A character to add as a prefix when a new line is added to a block comment.
 866    pub prefix: Arc<str>,
 867    /// A indent to add for prefix and end line upon new line.
 868    #[schemars(range(min = 1, max = 128))]
 869    pub tab_size: u32,
 870}
 871
 872impl<'de> Deserialize<'de> for BlockCommentConfig {
 873    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
 874    where
 875        D: Deserializer<'de>,
 876    {
 877        #[derive(Deserialize)]
 878        #[serde(untagged)]
 879        enum BlockCommentConfigHelper {
 880            New {
 881                start: Arc<str>,
 882                end: Arc<str>,
 883                prefix: Arc<str>,
 884                tab_size: u32,
 885            },
 886            Old([Arc<str>; 2]),
 887        }
 888
 889        match BlockCommentConfigHelper::deserialize(deserializer)? {
 890            BlockCommentConfigHelper::New {
 891                start,
 892                end,
 893                prefix,
 894                tab_size,
 895            } => Ok(BlockCommentConfig {
 896                start,
 897                end,
 898                prefix,
 899                tab_size,
 900            }),
 901            BlockCommentConfigHelper::Old([start, end]) => Ok(BlockCommentConfig {
 902                start,
 903                end,
 904                prefix: "".into(),
 905                tab_size: 0,
 906            }),
 907        }
 908    }
 909}
 910
 911/// Represents a language for the given range. Some languages (e.g. HTML)
 912/// interleave several languages together, thus a single buffer might actually contain
 913/// several nested scopes.
 914#[derive(Clone, Debug)]
 915pub struct LanguageScope {
 916    language: Arc<Language>,
 917    override_id: Option<u32>,
 918}
 919
 920#[derive(Clone, Deserialize, Default, Debug, JsonSchema)]
 921pub struct LanguageConfigOverride {
 922    #[serde(default)]
 923    pub line_comments: Override<Vec<Arc<str>>>,
 924    #[serde(default)]
 925    pub block_comment: Override<BlockCommentConfig>,
 926    #[serde(skip)]
 927    pub disabled_bracket_ixs: Vec<u16>,
 928    #[serde(default)]
 929    pub word_characters: Override<HashSet<char>>,
 930    #[serde(default)]
 931    pub completion_query_characters: Override<HashSet<char>>,
 932    #[serde(default)]
 933    pub linked_edit_characters: Override<HashSet<char>>,
 934    #[serde(default)]
 935    pub opt_into_language_servers: Vec<LanguageServerName>,
 936    #[serde(default)]
 937    pub prefer_label_for_snippet: Option<bool>,
 938}
 939
 940#[derive(Clone, Deserialize, Debug, Serialize, JsonSchema)]
 941#[serde(untagged)]
 942pub enum Override<T> {
 943    Remove { remove: bool },
 944    Set(T),
 945}
 946
 947impl<T> Default for Override<T> {
 948    fn default() -> Self {
 949        Override::Remove { remove: false }
 950    }
 951}
 952
 953impl<T> Override<T> {
 954    const fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
 955        match this {
 956            Some(Self::Set(value)) => Some(value),
 957            Some(Self::Remove { remove: true }) => None,
 958            Some(Self::Remove { remove: false }) | None => original,
 959        }
 960    }
 961}
 962
 963impl Default for LanguageConfig {
 964    fn default() -> Self {
 965        Self {
 966            name: LanguageName::new(""),
 967            code_fence_block_name: None,
 968            grammar: None,
 969            matcher: LanguageMatcher::default(),
 970            brackets: Default::default(),
 971            auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
 972            auto_indent_on_paste: None,
 973            increase_indent_pattern: Default::default(),
 974            decrease_indent_pattern: Default::default(),
 975            decrease_indent_patterns: Default::default(),
 976            autoclose_before: Default::default(),
 977            line_comments: Default::default(),
 978            block_comment: Default::default(),
 979            documentation_comment: Default::default(),
 980            rewrap_prefixes: Default::default(),
 981            scope_opt_in_language_servers: Default::default(),
 982            overrides: Default::default(),
 983            word_characters: Default::default(),
 984            collapsed_placeholder: Default::default(),
 985            hard_tabs: None,
 986            tab_size: None,
 987            soft_wrap: None,
 988            wrap_characters: None,
 989            prettier_parser_name: None,
 990            hidden: false,
 991            jsx_tag_auto_close: None,
 992            completion_query_characters: Default::default(),
 993            linked_edit_characters: Default::default(),
 994            debuggers: Default::default(),
 995            ignored_import_segments: Default::default(),
 996            import_path_strip_regex: None,
 997        }
 998    }
 999}
1000
1001#[derive(Clone, Debug, Deserialize, JsonSchema)]
1002pub struct WrapCharactersConfig {
1003    /// Opening token split into a prefix and suffix. The first caret goes
1004    /// after the prefix (i.e., between prefix and suffix).
1005    pub start_prefix: String,
1006    pub start_suffix: String,
1007    /// Closing token split into a prefix and suffix. The second caret goes
1008    /// after the prefix (i.e., between prefix and suffix).
1009    pub end_prefix: String,
1010    pub end_suffix: String,
1011}
1012
1013const fn auto_indent_using_last_non_empty_line_default() -> bool {
1014    true
1015}
1016
1017fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
1018    let source = Option::<String>::deserialize(d)?;
1019    if let Some(source) = source {
1020        Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
1021    } else {
1022        Ok(None)
1023    }
1024}
1025
1026fn regex_json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1027    json_schema!({
1028        "type": "string"
1029    })
1030}
1031
1032fn serialize_regex<S>(regex: &Option<Regex>, serializer: S) -> Result<S::Ok, S::Error>
1033where
1034    S: Serializer,
1035{
1036    match regex {
1037        Some(regex) => serializer.serialize_str(regex.as_str()),
1038        None => serializer.serialize_none(),
1039    }
1040}
1041
1042fn deserialize_regex_vec<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<Regex>, D::Error> {
1043    let sources = Vec::<String>::deserialize(d)?;
1044    sources
1045        .into_iter()
1046        .map(|source| regex::Regex::new(&source))
1047        .collect::<Result<_, _>>()
1048        .map_err(de::Error::custom)
1049}
1050
1051fn regex_vec_json_schema(_: &mut SchemaGenerator) -> schemars::Schema {
1052    json_schema!({
1053        "type": "array",
1054        "items": { "type": "string" }
1055    })
1056}
1057
1058#[doc(hidden)]
1059#[cfg(any(test, feature = "test-support"))]
1060pub struct FakeLspAdapter {
1061    pub name: &'static str,
1062    pub initialization_options: Option<Value>,
1063    pub prettier_plugins: Vec<&'static str>,
1064    pub disk_based_diagnostics_progress_token: Option<String>,
1065    pub disk_based_diagnostics_sources: Vec<String>,
1066    pub language_server_binary: LanguageServerBinary,
1067
1068    pub capabilities: lsp::ServerCapabilities,
1069    pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
1070    pub label_for_completion: Option<
1071        Box<
1072            dyn 'static
1073                + Send
1074                + Sync
1075                + Fn(&lsp::CompletionItem, &Arc<Language>) -> Option<CodeLabel>,
1076        >,
1077    >,
1078}
1079
1080/// Configuration of handling bracket pairs for a given language.
1081///
1082/// This struct includes settings for defining which pairs of characters are considered brackets and
1083/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
1084#[derive(Clone, Debug, Default, JsonSchema)]
1085#[schemars(with = "Vec::<BracketPairContent>")]
1086pub struct BracketPairConfig {
1087    /// A list of character pairs that should be treated as brackets in the context of a given language.
1088    pub pairs: Vec<BracketPair>,
1089    /// A list of tree-sitter scopes for which a given bracket should not be active.
1090    /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
1091    pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
1092}
1093
1094impl BracketPairConfig {
1095    pub fn is_closing_brace(&self, c: char) -> bool {
1096        self.pairs.iter().any(|pair| pair.end.starts_with(c))
1097    }
1098}
1099
1100#[derive(Deserialize, JsonSchema)]
1101pub struct BracketPairContent {
1102    #[serde(flatten)]
1103    pub bracket_pair: BracketPair,
1104    #[serde(default)]
1105    pub not_in: Vec<String>,
1106}
1107
1108impl<'de> Deserialize<'de> for BracketPairConfig {
1109    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1110    where
1111        D: Deserializer<'de>,
1112    {
1113        let result = Vec::<BracketPairContent>::deserialize(deserializer)?;
1114        let (brackets, disabled_scopes_by_bracket_ix) = result
1115            .into_iter()
1116            .map(|entry| (entry.bracket_pair, entry.not_in))
1117            .unzip();
1118
1119        Ok(BracketPairConfig {
1120            pairs: brackets,
1121            disabled_scopes_by_bracket_ix,
1122        })
1123    }
1124}
1125
1126/// Describes a single bracket pair and how an editor should react to e.g. inserting
1127/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
1128#[derive(Clone, Debug, Default, Deserialize, PartialEq, JsonSchema)]
1129pub struct BracketPair {
1130    /// Starting substring for a bracket.
1131    pub start: String,
1132    /// Ending substring for a bracket.
1133    pub end: String,
1134    /// True if `end` should be automatically inserted right after `start` characters.
1135    pub close: bool,
1136    /// True if selected text should be surrounded by `start` and `end` characters.
1137    #[serde(default = "default_true")]
1138    pub surround: bool,
1139    /// True if an extra newline should be inserted while the cursor is in the middle
1140    /// of that bracket pair.
1141    pub newline: bool,
1142}
1143
1144#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
1145pub struct LanguageId(usize);
1146
1147impl LanguageId {
1148    pub(crate) fn new() -> Self {
1149        Self(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst))
1150    }
1151}
1152
1153pub struct Language {
1154    pub(crate) id: LanguageId,
1155    pub(crate) config: LanguageConfig,
1156    pub(crate) grammar: Option<Arc<Grammar>>,
1157    pub(crate) context_provider: Option<Arc<dyn ContextProvider>>,
1158    pub(crate) toolchain: Option<Arc<dyn ToolchainLister>>,
1159    pub(crate) manifest_name: Option<ManifestName>,
1160}
1161
1162#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
1163pub struct GrammarId(pub usize);
1164
1165impl GrammarId {
1166    pub(crate) fn new() -> Self {
1167        Self(NEXT_GRAMMAR_ID.fetch_add(1, SeqCst))
1168    }
1169}
1170
1171pub struct Grammar {
1172    id: GrammarId,
1173    pub ts_language: tree_sitter::Language,
1174    pub(crate) error_query: Option<Query>,
1175    pub highlights_config: Option<HighlightsConfig>,
1176    pub(crate) brackets_config: Option<BracketsConfig>,
1177    pub(crate) redactions_config: Option<RedactionConfig>,
1178    pub(crate) runnable_config: Option<RunnableConfig>,
1179    pub(crate) indents_config: Option<IndentConfig>,
1180    pub outline_config: Option<OutlineConfig>,
1181    pub text_object_config: Option<TextObjectConfig>,
1182    pub embedding_config: Option<EmbeddingConfig>,
1183    pub(crate) injection_config: Option<InjectionConfig>,
1184    pub(crate) override_config: Option<OverrideConfig>,
1185    pub(crate) debug_variables_config: Option<DebugVariablesConfig>,
1186    pub(crate) imports_config: Option<ImportsConfig>,
1187    pub(crate) highlight_map: Mutex<HighlightMap>,
1188}
1189
1190pub struct HighlightsConfig {
1191    pub query: Query,
1192    pub identifier_capture_indices: Vec<u32>,
1193}
1194
1195struct IndentConfig {
1196    query: Query,
1197    indent_capture_ix: u32,
1198    start_capture_ix: Option<u32>,
1199    end_capture_ix: Option<u32>,
1200    outdent_capture_ix: Option<u32>,
1201    suffixed_start_captures: HashMap<u32, SharedString>,
1202}
1203
1204pub struct OutlineConfig {
1205    pub query: Query,
1206    pub item_capture_ix: u32,
1207    pub name_capture_ix: u32,
1208    pub context_capture_ix: Option<u32>,
1209    pub extra_context_capture_ix: Option<u32>,
1210    pub open_capture_ix: Option<u32>,
1211    pub close_capture_ix: Option<u32>,
1212    pub annotation_capture_ix: Option<u32>,
1213}
1214
1215#[derive(Debug, Clone, Copy, PartialEq)]
1216pub enum DebuggerTextObject {
1217    Variable,
1218    Scope,
1219}
1220
1221impl DebuggerTextObject {
1222    pub fn from_capture_name(name: &str) -> Option<DebuggerTextObject> {
1223        match name {
1224            "debug-variable" => Some(DebuggerTextObject::Variable),
1225            "debug-scope" => Some(DebuggerTextObject::Scope),
1226            _ => None,
1227        }
1228    }
1229}
1230
1231#[derive(Debug, Clone, Copy, PartialEq)]
1232pub enum TextObject {
1233    InsideFunction,
1234    AroundFunction,
1235    InsideClass,
1236    AroundClass,
1237    InsideComment,
1238    AroundComment,
1239}
1240
1241impl TextObject {
1242    pub fn from_capture_name(name: &str) -> Option<TextObject> {
1243        match name {
1244            "function.inside" => Some(TextObject::InsideFunction),
1245            "function.around" => Some(TextObject::AroundFunction),
1246            "class.inside" => Some(TextObject::InsideClass),
1247            "class.around" => Some(TextObject::AroundClass),
1248            "comment.inside" => Some(TextObject::InsideComment),
1249            "comment.around" => Some(TextObject::AroundComment),
1250            _ => None,
1251        }
1252    }
1253
1254    pub const fn around(&self) -> Option<Self> {
1255        match self {
1256            TextObject::InsideFunction => Some(TextObject::AroundFunction),
1257            TextObject::InsideClass => Some(TextObject::AroundClass),
1258            TextObject::InsideComment => Some(TextObject::AroundComment),
1259            _ => None,
1260        }
1261    }
1262}
1263
1264pub struct TextObjectConfig {
1265    pub query: Query,
1266    pub text_objects_by_capture_ix: Vec<(u32, TextObject)>,
1267}
1268
1269#[derive(Debug)]
1270pub struct EmbeddingConfig {
1271    pub query: Query,
1272    pub item_capture_ix: u32,
1273    pub name_capture_ix: Option<u32>,
1274    pub context_capture_ix: Option<u32>,
1275    pub collapse_capture_ix: Option<u32>,
1276    pub keep_capture_ix: Option<u32>,
1277}
1278
1279struct InjectionConfig {
1280    query: Query,
1281    content_capture_ix: u32,
1282    language_capture_ix: Option<u32>,
1283    patterns: Vec<InjectionPatternConfig>,
1284}
1285
1286struct RedactionConfig {
1287    pub query: Query,
1288    pub redaction_capture_ix: u32,
1289}
1290
1291#[derive(Clone, Debug, PartialEq)]
1292enum RunnableCapture {
1293    Named(SharedString),
1294    Run,
1295}
1296
1297struct RunnableConfig {
1298    pub query: Query,
1299    /// A mapping from capture indice to capture kind
1300    pub extra_captures: Vec<RunnableCapture>,
1301}
1302
1303struct OverrideConfig {
1304    query: Query,
1305    values: HashMap<u32, OverrideEntry>,
1306}
1307
1308#[derive(Debug)]
1309struct OverrideEntry {
1310    name: String,
1311    range_is_inclusive: bool,
1312    value: LanguageConfigOverride,
1313}
1314
1315#[derive(Default, Clone)]
1316struct InjectionPatternConfig {
1317    language: Option<Box<str>>,
1318    combined: bool,
1319}
1320
1321#[derive(Debug)]
1322struct BracketsConfig {
1323    query: Query,
1324    open_capture_ix: u32,
1325    close_capture_ix: u32,
1326    patterns: Vec<BracketsPatternConfig>,
1327}
1328
1329#[derive(Clone, Debug, Default)]
1330struct BracketsPatternConfig {
1331    newline_only: bool,
1332}
1333
1334pub struct DebugVariablesConfig {
1335    pub query: Query,
1336    pub objects_by_capture_ix: Vec<(u32, DebuggerTextObject)>,
1337}
1338
1339pub struct ImportsConfig {
1340    pub query: Query,
1341    pub import_ix: u32,
1342    pub name_ix: Option<u32>,
1343    pub namespace_ix: Option<u32>,
1344    pub source_ix: Option<u32>,
1345    pub list_ix: Option<u32>,
1346    pub wildcard_ix: Option<u32>,
1347    pub alias_ix: Option<u32>,
1348}
1349
1350impl Language {
1351    pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
1352        Self::new_with_id(LanguageId::new(), config, ts_language)
1353    }
1354
1355    pub const fn id(&self) -> LanguageId {
1356        self.id
1357    }
1358
1359    fn new_with_id(
1360        id: LanguageId,
1361        config: LanguageConfig,
1362        ts_language: Option<tree_sitter::Language>,
1363    ) -> Self {
1364        Self {
1365            id,
1366            config,
1367            grammar: ts_language.map(|ts_language| {
1368                Arc::new(Grammar {
1369                    id: GrammarId::new(),
1370                    highlights_config: None,
1371                    brackets_config: None,
1372                    outline_config: None,
1373                    text_object_config: None,
1374                    embedding_config: None,
1375                    indents_config: None,
1376                    injection_config: None,
1377                    override_config: None,
1378                    redactions_config: None,
1379                    runnable_config: None,
1380                    error_query: Query::new(&ts_language, "(ERROR) @error").ok(),
1381                    debug_variables_config: None,
1382                    imports_config: None,
1383                    ts_language,
1384                    highlight_map: Default::default(),
1385                })
1386            }),
1387            context_provider: None,
1388            toolchain: None,
1389            manifest_name: None,
1390        }
1391    }
1392
1393    pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
1394        self.context_provider = provider;
1395        self
1396    }
1397
1398    pub fn with_toolchain_lister(mut self, provider: Option<Arc<dyn ToolchainLister>>) -> Self {
1399        self.toolchain = provider;
1400        self
1401    }
1402
1403    pub fn with_manifest(mut self, name: Option<ManifestName>) -> Self {
1404        self.manifest_name = name;
1405        self
1406    }
1407
1408    pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
1409        if let Some(query) = queries.highlights {
1410            self = self
1411                .with_highlights_query(query.as_ref())
1412                .context("Error loading highlights query")?;
1413        }
1414        if let Some(query) = queries.brackets {
1415            self = self
1416                .with_brackets_query(query.as_ref())
1417                .context("Error loading brackets query")?;
1418        }
1419        if let Some(query) = queries.indents {
1420            self = self
1421                .with_indents_query(query.as_ref())
1422                .context("Error loading indents query")?;
1423        }
1424        if let Some(query) = queries.outline {
1425            self = self
1426                .with_outline_query(query.as_ref())
1427                .context("Error loading outline query")?;
1428        }
1429        if let Some(query) = queries.embedding {
1430            self = self
1431                .with_embedding_query(query.as_ref())
1432                .context("Error loading embedding query")?;
1433        }
1434        if let Some(query) = queries.injections {
1435            self = self
1436                .with_injection_query(query.as_ref())
1437                .context("Error loading injection query")?;
1438        }
1439        if let Some(query) = queries.overrides {
1440            self = self
1441                .with_override_query(query.as_ref())
1442                .context("Error loading override query")?;
1443        }
1444        if let Some(query) = queries.redactions {
1445            self = self
1446                .with_redaction_query(query.as_ref())
1447                .context("Error loading redaction query")?;
1448        }
1449        if let Some(query) = queries.runnables {
1450            self = self
1451                .with_runnable_query(query.as_ref())
1452                .context("Error loading runnables query")?;
1453        }
1454        if let Some(query) = queries.text_objects {
1455            self = self
1456                .with_text_object_query(query.as_ref())
1457                .context("Error loading textobject query")?;
1458        }
1459        if let Some(query) = queries.debugger {
1460            self = self
1461                .with_debug_variables_query(query.as_ref())
1462                .context("Error loading debug variables query")?;
1463        }
1464        if let Some(query) = queries.imports {
1465            self = self
1466                .with_imports_query(query.as_ref())
1467                .context("Error loading imports query")?;
1468        }
1469        Ok(self)
1470    }
1471
1472    pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1473        let grammar = self.grammar_mut()?;
1474        let query = Query::new(&grammar.ts_language, source)?;
1475
1476        let mut identifier_capture_indices = Vec::new();
1477        for name in [
1478            "variable",
1479            "constant",
1480            "constructor",
1481            "function",
1482            "function.method",
1483            "function.method.call",
1484            "function.special",
1485            "property",
1486            "type",
1487            "type.interface",
1488        ] {
1489            identifier_capture_indices.extend(query.capture_index_for_name(name));
1490        }
1491
1492        grammar.highlights_config = Some(HighlightsConfig {
1493            query,
1494            identifier_capture_indices,
1495        });
1496
1497        Ok(self)
1498    }
1499
1500    pub fn with_runnable_query(mut self, source: &str) -> Result<Self> {
1501        let grammar = self.grammar_mut()?;
1502
1503        let query = Query::new(&grammar.ts_language, source)?;
1504        let extra_captures: Vec<_> = query
1505            .capture_names()
1506            .iter()
1507            .map(|&name| match name {
1508                "run" => RunnableCapture::Run,
1509                name => RunnableCapture::Named(name.to_string().into()),
1510            })
1511            .collect();
1512
1513        grammar.runnable_config = Some(RunnableConfig {
1514            extra_captures,
1515            query,
1516        });
1517
1518        Ok(self)
1519    }
1520
1521    pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1522        let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1523        let mut item_capture_ix = 0;
1524        let mut name_capture_ix = 0;
1525        let mut context_capture_ix = None;
1526        let mut extra_context_capture_ix = None;
1527        let mut open_capture_ix = None;
1528        let mut close_capture_ix = None;
1529        let mut annotation_capture_ix = None;
1530        if populate_capture_indices(
1531            &query,
1532            &self.config.name,
1533            "outline",
1534            &[],
1535            &mut [
1536                Capture::Required("item", &mut item_capture_ix),
1537                Capture::Required("name", &mut name_capture_ix),
1538                Capture::Optional("context", &mut context_capture_ix),
1539                Capture::Optional("context.extra", &mut extra_context_capture_ix),
1540                Capture::Optional("open", &mut open_capture_ix),
1541                Capture::Optional("close", &mut close_capture_ix),
1542                Capture::Optional("annotation", &mut annotation_capture_ix),
1543            ],
1544        ) {
1545            self.grammar_mut()?.outline_config = Some(OutlineConfig {
1546                query,
1547                item_capture_ix,
1548                name_capture_ix,
1549                context_capture_ix,
1550                extra_context_capture_ix,
1551                open_capture_ix,
1552                close_capture_ix,
1553                annotation_capture_ix,
1554            });
1555        }
1556        Ok(self)
1557    }
1558
1559    pub fn with_text_object_query(mut self, source: &str) -> Result<Self> {
1560        let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1561
1562        let mut text_objects_by_capture_ix = Vec::new();
1563        for (ix, name) in query.capture_names().iter().enumerate() {
1564            if let Some(text_object) = TextObject::from_capture_name(name) {
1565                text_objects_by_capture_ix.push((ix as u32, text_object));
1566            } else {
1567                log::warn!(
1568                    "unrecognized capture name '{}' in {} textobjects TreeSitter query",
1569                    name,
1570                    self.config.name,
1571                );
1572            }
1573        }
1574
1575        self.grammar_mut()?.text_object_config = Some(TextObjectConfig {
1576            query,
1577            text_objects_by_capture_ix,
1578        });
1579        Ok(self)
1580    }
1581
1582    pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
1583        let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1584        let mut item_capture_ix = 0;
1585        let mut name_capture_ix = None;
1586        let mut context_capture_ix = None;
1587        let mut collapse_capture_ix = None;
1588        let mut keep_capture_ix = None;
1589        if populate_capture_indices(
1590            &query,
1591            &self.config.name,
1592            "embedding",
1593            &[],
1594            &mut [
1595                Capture::Required("item", &mut item_capture_ix),
1596                Capture::Optional("name", &mut name_capture_ix),
1597                Capture::Optional("context", &mut context_capture_ix),
1598                Capture::Optional("keep", &mut keep_capture_ix),
1599                Capture::Optional("collapse", &mut collapse_capture_ix),
1600            ],
1601        ) {
1602            self.grammar_mut()?.embedding_config = Some(EmbeddingConfig {
1603                query,
1604                item_capture_ix,
1605                name_capture_ix,
1606                context_capture_ix,
1607                collapse_capture_ix,
1608                keep_capture_ix,
1609            });
1610        }
1611        Ok(self)
1612    }
1613
1614    pub fn with_debug_variables_query(mut self, source: &str) -> Result<Self> {
1615        let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1616
1617        let mut objects_by_capture_ix = Vec::new();
1618        for (ix, name) in query.capture_names().iter().enumerate() {
1619            if let Some(text_object) = DebuggerTextObject::from_capture_name(name) {
1620                objects_by_capture_ix.push((ix as u32, text_object));
1621            } else {
1622                log::warn!(
1623                    "unrecognized capture name '{}' in {} debugger TreeSitter query",
1624                    name,
1625                    self.config.name,
1626                );
1627            }
1628        }
1629
1630        self.grammar_mut()?.debug_variables_config = Some(DebugVariablesConfig {
1631            query,
1632            objects_by_capture_ix,
1633        });
1634        Ok(self)
1635    }
1636
1637    pub fn with_imports_query(mut self, source: &str) -> Result<Self> {
1638        let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1639
1640        let mut import_ix = 0;
1641        let mut name_ix = None;
1642        let mut namespace_ix = None;
1643        let mut source_ix = None;
1644        let mut list_ix = None;
1645        let mut wildcard_ix = None;
1646        let mut alias_ix = None;
1647        if populate_capture_indices(
1648            &query,
1649            &self.config.name,
1650            "imports",
1651            &[],
1652            &mut [
1653                Capture::Required("import", &mut import_ix),
1654                Capture::Optional("name", &mut name_ix),
1655                Capture::Optional("namespace", &mut namespace_ix),
1656                Capture::Optional("source", &mut source_ix),
1657                Capture::Optional("list", &mut list_ix),
1658                Capture::Optional("wildcard", &mut wildcard_ix),
1659                Capture::Optional("alias", &mut alias_ix),
1660            ],
1661        ) {
1662            self.grammar_mut()?.imports_config = Some(ImportsConfig {
1663                query,
1664                import_ix,
1665                name_ix,
1666                namespace_ix,
1667                source_ix,
1668                list_ix,
1669                wildcard_ix,
1670                alias_ix,
1671            });
1672        }
1673        return Ok(self);
1674    }
1675
1676    pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1677        let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1678        let mut open_capture_ix = 0;
1679        let mut close_capture_ix = 0;
1680        if populate_capture_indices(
1681            &query,
1682            &self.config.name,
1683            "brackets",
1684            &[],
1685            &mut [
1686                Capture::Required("open", &mut open_capture_ix),
1687                Capture::Required("close", &mut close_capture_ix),
1688            ],
1689        ) {
1690            let patterns = (0..query.pattern_count())
1691                .map(|ix| {
1692                    let mut config = BracketsPatternConfig::default();
1693                    for setting in query.property_settings(ix) {
1694                        if setting.key.as_ref() == "newline.only" {
1695                            config.newline_only = true
1696                        }
1697                    }
1698                    config
1699                })
1700                .collect();
1701            self.grammar_mut()?.brackets_config = Some(BracketsConfig {
1702                query,
1703                open_capture_ix,
1704                close_capture_ix,
1705                patterns,
1706            });
1707        }
1708        Ok(self)
1709    }
1710
1711    pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1712        let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1713        let mut indent_capture_ix = 0;
1714        let mut start_capture_ix = None;
1715        let mut end_capture_ix = None;
1716        let mut outdent_capture_ix = None;
1717        if populate_capture_indices(
1718            &query,
1719            &self.config.name,
1720            "indents",
1721            &["start."],
1722            &mut [
1723                Capture::Required("indent", &mut indent_capture_ix),
1724                Capture::Optional("start", &mut start_capture_ix),
1725                Capture::Optional("end", &mut end_capture_ix),
1726                Capture::Optional("outdent", &mut outdent_capture_ix),
1727            ],
1728        ) {
1729            let mut suffixed_start_captures = HashMap::default();
1730            for (ix, name) in query.capture_names().iter().enumerate() {
1731                if let Some(suffix) = name.strip_prefix("start.") {
1732                    suffixed_start_captures.insert(ix as u32, suffix.to_owned().into());
1733                }
1734            }
1735
1736            self.grammar_mut()?.indents_config = Some(IndentConfig {
1737                query,
1738                indent_capture_ix,
1739                start_capture_ix,
1740                end_capture_ix,
1741                outdent_capture_ix,
1742                suffixed_start_captures,
1743            });
1744        }
1745        Ok(self)
1746    }
1747
1748    pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1749        let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1750        let mut language_capture_ix = None;
1751        let mut injection_language_capture_ix = None;
1752        let mut content_capture_ix = None;
1753        let mut injection_content_capture_ix = None;
1754        if populate_capture_indices(
1755            &query,
1756            &self.config.name,
1757            "injections",
1758            &[],
1759            &mut [
1760                Capture::Optional("language", &mut language_capture_ix),
1761                Capture::Optional("injection.language", &mut injection_language_capture_ix),
1762                Capture::Optional("content", &mut content_capture_ix),
1763                Capture::Optional("injection.content", &mut injection_content_capture_ix),
1764            ],
1765        ) {
1766            language_capture_ix = match (language_capture_ix, injection_language_capture_ix) {
1767                (None, Some(ix)) => Some(ix),
1768                (Some(_), Some(_)) => {
1769                    anyhow::bail!("both language and injection.language captures are present");
1770                }
1771                _ => language_capture_ix,
1772            };
1773            content_capture_ix = match (content_capture_ix, injection_content_capture_ix) {
1774                (None, Some(ix)) => Some(ix),
1775                (Some(_), Some(_)) => {
1776                    anyhow::bail!("both content and injection.content captures are present")
1777                }
1778                _ => content_capture_ix,
1779            };
1780            let patterns = (0..query.pattern_count())
1781                .map(|ix| {
1782                    let mut config = InjectionPatternConfig::default();
1783                    for setting in query.property_settings(ix) {
1784                        match setting.key.as_ref() {
1785                            "language" | "injection.language" => {
1786                                config.language.clone_from(&setting.value);
1787                            }
1788                            "combined" | "injection.combined" => {
1789                                config.combined = true;
1790                            }
1791                            _ => {}
1792                        }
1793                    }
1794                    config
1795                })
1796                .collect();
1797            if let Some(content_capture_ix) = content_capture_ix {
1798                self.grammar_mut()?.injection_config = Some(InjectionConfig {
1799                    query,
1800                    language_capture_ix,
1801                    content_capture_ix,
1802                    patterns,
1803                });
1804            } else {
1805                log::error!(
1806                    "missing required capture in injections {} TreeSitter query: \
1807                    content or injection.content",
1808                    &self.config.name,
1809                );
1810            }
1811        }
1812        Ok(self)
1813    }
1814
1815    pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1816        let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1817
1818        let mut override_configs_by_id = HashMap::default();
1819        for (ix, mut name) in query.capture_names().iter().copied().enumerate() {
1820            let mut range_is_inclusive = false;
1821            if name.starts_with('_') {
1822                continue;
1823            }
1824            if let Some(prefix) = name.strip_suffix(".inclusive") {
1825                name = prefix;
1826                range_is_inclusive = true;
1827            }
1828
1829            let value = self.config.overrides.get(name).cloned().unwrap_or_default();
1830            for server_name in &value.opt_into_language_servers {
1831                if !self
1832                    .config
1833                    .scope_opt_in_language_servers
1834                    .contains(server_name)
1835                {
1836                    util::debug_panic!(
1837                        "Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server"
1838                    );
1839                }
1840            }
1841
1842            override_configs_by_id.insert(
1843                ix as u32,
1844                OverrideEntry {
1845                    name: name.to_string(),
1846                    range_is_inclusive,
1847                    value,
1848                },
1849            );
1850        }
1851
1852        let referenced_override_names = self.config.overrides.keys().chain(
1853            self.config
1854                .brackets
1855                .disabled_scopes_by_bracket_ix
1856                .iter()
1857                .flatten(),
1858        );
1859
1860        for referenced_name in referenced_override_names {
1861            if !override_configs_by_id
1862                .values()
1863                .any(|entry| entry.name == *referenced_name)
1864            {
1865                anyhow::bail!(
1866                    "language {:?} has overrides in config not in query: {referenced_name:?}",
1867                    self.config.name
1868                );
1869            }
1870        }
1871
1872        for entry in override_configs_by_id.values_mut() {
1873            entry.value.disabled_bracket_ixs = self
1874                .config
1875                .brackets
1876                .disabled_scopes_by_bracket_ix
1877                .iter()
1878                .enumerate()
1879                .filter_map(|(ix, disabled_scope_names)| {
1880                    if disabled_scope_names.contains(&entry.name) {
1881                        Some(ix as u16)
1882                    } else {
1883                        None
1884                    }
1885                })
1886                .collect();
1887        }
1888
1889        self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1890
1891        let grammar = self.grammar_mut()?;
1892        grammar.override_config = Some(OverrideConfig {
1893            query,
1894            values: override_configs_by_id,
1895        });
1896        Ok(self)
1897    }
1898
1899    pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1900        let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1901        let mut redaction_capture_ix = 0;
1902        if populate_capture_indices(
1903            &query,
1904            &self.config.name,
1905            "redactions",
1906            &[],
1907            &mut [Capture::Required("redact", &mut redaction_capture_ix)],
1908        ) {
1909            self.grammar_mut()?.redactions_config = Some(RedactionConfig {
1910                query,
1911                redaction_capture_ix,
1912            });
1913        }
1914        Ok(self)
1915    }
1916
1917    fn expect_grammar(&self) -> Result<&Grammar> {
1918        self.grammar
1919            .as_ref()
1920            .map(|grammar| grammar.as_ref())
1921            .context("no grammar for language")
1922    }
1923
1924    fn grammar_mut(&mut self) -> Result<&mut Grammar> {
1925        Arc::get_mut(self.grammar.as_mut().context("no grammar for language")?)
1926            .context("cannot mutate grammar")
1927    }
1928
1929    pub fn name(&self) -> LanguageName {
1930        self.config.name.clone()
1931    }
1932    pub const fn manifest(&self) -> Option<&ManifestName> {
1933        self.manifest_name.as_ref()
1934    }
1935
1936    pub fn code_fence_block_name(&self) -> Arc<str> {
1937        self.config
1938            .code_fence_block_name
1939            .clone()
1940            .unwrap_or_else(|| self.config.name.as_ref().to_lowercase().into())
1941    }
1942
1943    pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1944        self.context_provider.clone()
1945    }
1946
1947    pub fn toolchain_lister(&self) -> Option<Arc<dyn ToolchainLister>> {
1948        self.toolchain.clone()
1949    }
1950
1951    pub fn highlight_text<'a>(
1952        self: &'a Arc<Self>,
1953        text: &'a Rope,
1954        range: Range<usize>,
1955    ) -> Vec<(Range<usize>, HighlightId)> {
1956        let mut result = Vec::new();
1957        if let Some(grammar) = &self.grammar {
1958            let tree = grammar.parse_text(text, None);
1959            let captures =
1960                SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1961                    grammar
1962                        .highlights_config
1963                        .as_ref()
1964                        .map(|config| &config.query)
1965                });
1966            let highlight_maps = vec![grammar.highlight_map()];
1967            let mut offset = 0;
1968            for chunk in
1969                BufferChunks::new(text, range, Some((captures, highlight_maps)), false, None)
1970            {
1971                let end_offset = offset + chunk.text.len();
1972                if let Some(highlight_id) = chunk.syntax_highlight_id
1973                    && !highlight_id.is_default()
1974                {
1975                    result.push((offset..end_offset, highlight_id));
1976                }
1977                offset = end_offset;
1978            }
1979        }
1980        result
1981    }
1982
1983    pub fn path_suffixes(&self) -> &[String] {
1984        &self.config.matcher.path_suffixes
1985    }
1986
1987    pub fn should_autoclose_before(&self, c: char) -> bool {
1988        c.is_whitespace() || self.config.autoclose_before.contains(c)
1989    }
1990
1991    pub fn set_theme(&self, theme: &SyntaxTheme) {
1992        if let Some(grammar) = self.grammar.as_ref()
1993            && let Some(highlights_config) = &grammar.highlights_config
1994        {
1995            *grammar.highlight_map.lock() =
1996                HighlightMap::new(highlights_config.query.capture_names(), theme);
1997        }
1998    }
1999
2000    pub const fn grammar(&self) -> Option<&Arc<Grammar>> {
2001        self.grammar.as_ref()
2002    }
2003
2004    pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
2005        LanguageScope {
2006            language: self.clone(),
2007            override_id: None,
2008        }
2009    }
2010
2011    pub fn lsp_id(&self) -> String {
2012        self.config.name.lsp_id()
2013    }
2014
2015    pub fn prettier_parser_name(&self) -> Option<&str> {
2016        self.config.prettier_parser_name.as_deref()
2017    }
2018
2019    pub const fn config(&self) -> &LanguageConfig {
2020        &self.config
2021    }
2022}
2023
2024impl LanguageScope {
2025    pub fn path_suffixes(&self) -> &[String] {
2026        self.language.path_suffixes()
2027    }
2028
2029    pub fn language_name(&self) -> LanguageName {
2030        self.language.config.name.clone()
2031    }
2032
2033    pub fn collapsed_placeholder(&self) -> &str {
2034        self.language.config.collapsed_placeholder.as_ref()
2035    }
2036
2037    /// Returns line prefix that is inserted in e.g. line continuations or
2038    /// in `toggle comments` action.
2039    pub fn line_comment_prefixes(&self) -> &[Arc<str>] {
2040        Override::as_option(
2041            self.config_override().map(|o| &o.line_comments),
2042            Some(&self.language.config.line_comments),
2043        )
2044        .map_or([].as_slice(), |e| e.as_slice())
2045    }
2046
2047    /// Config for block comments for this language.
2048    pub fn block_comment(&self) -> Option<&BlockCommentConfig> {
2049        Override::as_option(
2050            self.config_override().map(|o| &o.block_comment),
2051            self.language.config.block_comment.as_ref(),
2052        )
2053    }
2054
2055    /// Config for documentation-style block comments for this language.
2056    pub fn documentation_comment(&self) -> Option<&BlockCommentConfig> {
2057        self.language.config.documentation_comment.as_ref()
2058    }
2059
2060    /// Returns additional regex patterns that act as prefix markers for creating
2061    /// boundaries during rewrapping.
2062    ///
2063    /// By default, Zed treats as paragraph and comment prefixes as boundaries.
2064    pub fn rewrap_prefixes(&self) -> &[Regex] {
2065        &self.language.config.rewrap_prefixes
2066    }
2067
2068    /// Returns a list of language-specific word characters.
2069    ///
2070    /// By default, Zed treats alphanumeric characters (and '_') as word characters for
2071    /// the purpose of actions like 'move to next word end` or whole-word search.
2072    /// It additionally accounts for language's additional word characters.
2073    pub fn word_characters(&self) -> Option<&HashSet<char>> {
2074        Override::as_option(
2075            self.config_override().map(|o| &o.word_characters),
2076            Some(&self.language.config.word_characters),
2077        )
2078    }
2079
2080    /// Returns a list of language-specific characters that are considered part of
2081    /// a completion query.
2082    pub fn completion_query_characters(&self) -> Option<&HashSet<char>> {
2083        Override::as_option(
2084            self.config_override()
2085                .map(|o| &o.completion_query_characters),
2086            Some(&self.language.config.completion_query_characters),
2087        )
2088    }
2089
2090    /// Returns a list of language-specific characters that are considered part of
2091    /// identifiers during linked editing operations.
2092    pub fn linked_edit_characters(&self) -> Option<&HashSet<char>> {
2093        Override::as_option(
2094            self.config_override().map(|o| &o.linked_edit_characters),
2095            Some(&self.language.config.linked_edit_characters),
2096        )
2097    }
2098
2099    /// Returns whether to prefer snippet `label` over `new_text` to replace text when
2100    /// completion is accepted.
2101    ///
2102    /// In cases like when cursor is in string or renaming existing function,
2103    /// you don't want to expand function signature instead just want function name
2104    /// to replace existing one.
2105    pub fn prefers_label_for_snippet_in_completion(&self) -> bool {
2106        self.config_override()
2107            .and_then(|o| o.prefer_label_for_snippet)
2108            .unwrap_or(false)
2109    }
2110
2111    /// Returns a list of bracket pairs for a given language with an additional
2112    /// piece of information about whether the particular bracket pair is currently active for a given language.
2113    pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
2114        let mut disabled_ids = self
2115            .config_override()
2116            .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
2117        self.language
2118            .config
2119            .brackets
2120            .pairs
2121            .iter()
2122            .enumerate()
2123            .map(move |(ix, bracket)| {
2124                let mut is_enabled = true;
2125                if let Some(next_disabled_ix) = disabled_ids.first()
2126                    && ix == *next_disabled_ix as usize
2127                {
2128                    disabled_ids = &disabled_ids[1..];
2129                    is_enabled = false;
2130                }
2131                (bracket, is_enabled)
2132            })
2133    }
2134
2135    pub fn should_autoclose_before(&self, c: char) -> bool {
2136        c.is_whitespace() || self.language.config.autoclose_before.contains(c)
2137    }
2138
2139    pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
2140        let config = &self.language.config;
2141        let opt_in_servers = &config.scope_opt_in_language_servers;
2142        if opt_in_servers.contains(name) {
2143            if let Some(over) = self.config_override() {
2144                over.opt_into_language_servers.contains(name)
2145            } else {
2146                false
2147            }
2148        } else {
2149            true
2150        }
2151    }
2152
2153    pub fn override_name(&self) -> Option<&str> {
2154        let id = self.override_id?;
2155        let grammar = self.language.grammar.as_ref()?;
2156        let override_config = grammar.override_config.as_ref()?;
2157        override_config.values.get(&id).map(|e| e.name.as_str())
2158    }
2159
2160    fn config_override(&self) -> Option<&LanguageConfigOverride> {
2161        let id = self.override_id?;
2162        let grammar = self.language.grammar.as_ref()?;
2163        let override_config = grammar.override_config.as_ref()?;
2164        override_config.values.get(&id).map(|e| &e.value)
2165    }
2166}
2167
2168impl Hash for Language {
2169    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
2170        self.id.hash(state)
2171    }
2172}
2173
2174impl PartialEq for Language {
2175    fn eq(&self, other: &Self) -> bool {
2176        self.id.eq(&other.id)
2177    }
2178}
2179
2180impl Eq for Language {}
2181
2182impl Debug for Language {
2183    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2184        f.debug_struct("Language")
2185            .field("name", &self.config.name)
2186            .finish()
2187    }
2188}
2189
2190impl Grammar {
2191    pub const fn id(&self) -> GrammarId {
2192        self.id
2193    }
2194
2195    fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
2196        with_parser(|parser| {
2197            parser
2198                .set_language(&self.ts_language)
2199                .expect("incompatible grammar");
2200            let mut chunks = text.chunks_in_range(0..text.len());
2201            parser
2202                .parse_with_options(
2203                    &mut move |offset, _| {
2204                        chunks.seek(offset);
2205                        chunks.next().unwrap_or("").as_bytes()
2206                    },
2207                    old_tree.as_ref(),
2208                    None,
2209                )
2210                .unwrap()
2211        })
2212    }
2213
2214    pub fn highlight_map(&self) -> HighlightMap {
2215        self.highlight_map.lock().clone()
2216    }
2217
2218    pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
2219        let capture_id = self
2220            .highlights_config
2221            .as_ref()?
2222            .query
2223            .capture_index_for_name(name)?;
2224        Some(self.highlight_map.lock().get(capture_id))
2225    }
2226
2227    pub const fn debug_variables_config(&self) -> Option<&DebugVariablesConfig> {
2228        self.debug_variables_config.as_ref()
2229    }
2230
2231    pub const fn imports_config(&self) -> Option<&ImportsConfig> {
2232        self.imports_config.as_ref()
2233    }
2234}
2235
2236impl CodeLabelBuilder {
2237    pub fn respan_filter_range(&mut self, filter_text: Option<&str>) {
2238        self.filter_range = filter_text
2239            .and_then(|filter| self.text.find(filter).map(|ix| ix..ix + filter.len()))
2240            .unwrap_or(0..self.text.len());
2241    }
2242
2243    pub fn push_str(&mut self, text: &str, highlight: Option<HighlightId>) {
2244        let start_ix = self.text.len();
2245        self.text.push_str(text);
2246        if let Some(highlight) = highlight {
2247            let end_ix = self.text.len();
2248            self.runs.push((start_ix..end_ix, highlight));
2249        }
2250    }
2251
2252    pub fn build(mut self) -> CodeLabel {
2253        if self.filter_range.end == 0 {
2254            self.respan_filter_range(None);
2255        }
2256        CodeLabel {
2257            text: self.text,
2258            runs: self.runs,
2259            filter_range: self.filter_range,
2260        }
2261    }
2262}
2263
2264impl CodeLabel {
2265    pub fn fallback_for_completion(
2266        item: &lsp::CompletionItem,
2267        language: Option<&Language>,
2268    ) -> Self {
2269        let highlight_id = item.kind.and_then(|kind| {
2270            let grammar = language?.grammar()?;
2271            use lsp::CompletionItemKind as Kind;
2272            match kind {
2273                Kind::CLASS => grammar.highlight_id_for_name("type"),
2274                Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
2275                Kind::CONSTRUCTOR => grammar.highlight_id_for_name("constructor"),
2276                Kind::ENUM => grammar
2277                    .highlight_id_for_name("enum")
2278                    .or_else(|| grammar.highlight_id_for_name("type")),
2279                Kind::ENUM_MEMBER => grammar
2280                    .highlight_id_for_name("variant")
2281                    .or_else(|| grammar.highlight_id_for_name("property")),
2282                Kind::FIELD => grammar.highlight_id_for_name("property"),
2283                Kind::FUNCTION => grammar.highlight_id_for_name("function"),
2284                Kind::INTERFACE => grammar.highlight_id_for_name("type"),
2285                Kind::METHOD => grammar
2286                    .highlight_id_for_name("function.method")
2287                    .or_else(|| grammar.highlight_id_for_name("function")),
2288                Kind::OPERATOR => grammar.highlight_id_for_name("operator"),
2289                Kind::PROPERTY => grammar.highlight_id_for_name("property"),
2290                Kind::STRUCT => grammar.highlight_id_for_name("type"),
2291                Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
2292                Kind::KEYWORD => grammar.highlight_id_for_name("keyword"),
2293                _ => None,
2294            }
2295        });
2296
2297        let label = &item.label;
2298        let label_length = label.len();
2299        let runs = highlight_id
2300            .map(|highlight_id| vec![(0..label_length, highlight_id)])
2301            .unwrap_or_default();
2302        let text = if let Some(detail) = item.detail.as_deref().filter(|detail| detail != label) {
2303            format!("{label} {detail}")
2304        } else if let Some(description) = item
2305            .label_details
2306            .as_ref()
2307            .and_then(|label_details| label_details.description.as_deref())
2308            .filter(|description| description != label)
2309        {
2310            format!("{label} {description}")
2311        } else {
2312            label.clone()
2313        };
2314        let filter_range = item
2315            .filter_text
2316            .as_deref()
2317            .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
2318            .unwrap_or(0..label_length);
2319        Self {
2320            text,
2321            runs,
2322            filter_range,
2323        }
2324    }
2325
2326    pub fn plain(text: String, filter_text: Option<&str>) -> Self {
2327        Self::filtered(text, filter_text, Vec::new())
2328    }
2329
2330    pub fn filtered(
2331        text: String,
2332        filter_text: Option<&str>,
2333        runs: Vec<(Range<usize>, HighlightId)>,
2334    ) -> Self {
2335        let filter_range = filter_text
2336            .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
2337            .unwrap_or(0..text.len());
2338        Self::new(text, filter_range, runs)
2339    }
2340
2341    pub fn new(
2342        text: String,
2343        filter_range: Range<usize>,
2344        runs: Vec<(Range<usize>, HighlightId)>,
2345    ) -> Self {
2346        assert!(
2347            text.get(filter_range.clone()).is_some(),
2348            "invalid filter range"
2349        );
2350        runs.iter().for_each(|(range, _)| {
2351            assert!(text.get(range.clone()).is_some(), "invalid run range");
2352        });
2353        Self {
2354            runs,
2355            filter_range,
2356            text,
2357        }
2358    }
2359
2360    pub const fn text(&self) -> &str {
2361        self.text.as_str()
2362    }
2363
2364    pub fn filter_text(&self) -> &str {
2365        &self.text[self.filter_range.clone()]
2366    }
2367}
2368
2369impl From<String> for CodeLabel {
2370    fn from(value: String) -> Self {
2371        Self::plain(value, None)
2372    }
2373}
2374
2375impl From<&str> for CodeLabel {
2376    fn from(value: &str) -> Self {
2377        Self::plain(value.to_string(), None)
2378    }
2379}
2380
2381impl Ord for LanguageMatcher {
2382    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
2383        self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
2384            self.first_line_pattern
2385                .as_ref()
2386                .map(Regex::as_str)
2387                .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
2388        })
2389    }
2390}
2391
2392impl PartialOrd for LanguageMatcher {
2393    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2394        Some(self.cmp(other))
2395    }
2396}
2397
2398impl Eq for LanguageMatcher {}
2399
2400impl PartialEq for LanguageMatcher {
2401    fn eq(&self, other: &Self) -> bool {
2402        self.path_suffixes == other.path_suffixes
2403            && self.first_line_pattern.as_ref().map(Regex::as_str)
2404                == other.first_line_pattern.as_ref().map(Regex::as_str)
2405    }
2406}
2407
2408#[cfg(any(test, feature = "test-support"))]
2409impl Default for FakeLspAdapter {
2410    fn default() -> Self {
2411        Self {
2412            name: "the-fake-language-server",
2413            capabilities: lsp::LanguageServer::full_capabilities(),
2414            initializer: None,
2415            disk_based_diagnostics_progress_token: None,
2416            initialization_options: None,
2417            disk_based_diagnostics_sources: Vec::new(),
2418            prettier_plugins: Vec::new(),
2419            language_server_binary: LanguageServerBinary {
2420                path: "/the/fake/lsp/path".into(),
2421                arguments: vec![],
2422                env: Default::default(),
2423            },
2424            label_for_completion: None,
2425        }
2426    }
2427}
2428
2429#[cfg(any(test, feature = "test-support"))]
2430impl LspInstaller for FakeLspAdapter {
2431    type BinaryVersion = ();
2432
2433    async fn fetch_latest_server_version(
2434        &self,
2435        _: &dyn LspAdapterDelegate,
2436        _: bool,
2437        _: &mut AsyncApp,
2438    ) -> Result<Self::BinaryVersion> {
2439        unreachable!()
2440    }
2441
2442    async fn check_if_user_installed(
2443        &self,
2444        _: &dyn LspAdapterDelegate,
2445        _: Option<Toolchain>,
2446        _: &AsyncApp,
2447    ) -> Option<LanguageServerBinary> {
2448        Some(self.language_server_binary.clone())
2449    }
2450
2451    async fn fetch_server_binary(
2452        &self,
2453        _: (),
2454        _: PathBuf,
2455        _: &dyn LspAdapterDelegate,
2456    ) -> Result<LanguageServerBinary> {
2457        unreachable!();
2458    }
2459
2460    async fn cached_server_binary(
2461        &self,
2462        _: PathBuf,
2463        _: &dyn LspAdapterDelegate,
2464    ) -> Option<LanguageServerBinary> {
2465        unreachable!();
2466    }
2467}
2468
2469#[cfg(any(test, feature = "test-support"))]
2470#[async_trait(?Send)]
2471impl LspAdapter for FakeLspAdapter {
2472    fn name(&self) -> LanguageServerName {
2473        LanguageServerName(self.name.into())
2474    }
2475
2476    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
2477        self.disk_based_diagnostics_sources.clone()
2478    }
2479
2480    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
2481        self.disk_based_diagnostics_progress_token.clone()
2482    }
2483
2484    async fn initialization_options(
2485        self: Arc<Self>,
2486        _: &Arc<dyn LspAdapterDelegate>,
2487    ) -> Result<Option<Value>> {
2488        Ok(self.initialization_options.clone())
2489    }
2490
2491    async fn label_for_completion(
2492        &self,
2493        item: &lsp::CompletionItem,
2494        language: &Arc<Language>,
2495    ) -> Option<CodeLabel> {
2496        let label_for_completion = self.label_for_completion.as_ref()?;
2497        label_for_completion(item, language)
2498    }
2499
2500    fn is_extension(&self) -> bool {
2501        false
2502    }
2503}
2504
2505enum Capture<'a> {
2506    Required(&'static str, &'a mut u32),
2507    Optional(&'static str, &'a mut Option<u32>),
2508}
2509
2510fn populate_capture_indices(
2511    query: &Query,
2512    language_name: &LanguageName,
2513    query_type: &str,
2514    expected_prefixes: &[&str],
2515    captures: &mut [Capture<'_>],
2516) -> bool {
2517    let mut found_required_indices = Vec::new();
2518    'outer: for (ix, name) in query.capture_names().iter().enumerate() {
2519        for (required_ix, capture) in captures.iter_mut().enumerate() {
2520            match capture {
2521                Capture::Required(capture_name, index) if capture_name == name => {
2522                    **index = ix as u32;
2523                    found_required_indices.push(required_ix);
2524                    continue 'outer;
2525                }
2526                Capture::Optional(capture_name, index) if capture_name == name => {
2527                    **index = Some(ix as u32);
2528                    continue 'outer;
2529                }
2530                _ => {}
2531            }
2532        }
2533        if !name.starts_with("_")
2534            && !expected_prefixes
2535                .iter()
2536                .any(|&prefix| name.starts_with(prefix))
2537        {
2538            log::warn!(
2539                "unrecognized capture name '{}' in {} {} TreeSitter query \
2540                (suppress this warning by prefixing with '_')",
2541                name,
2542                language_name,
2543                query_type
2544            );
2545        }
2546    }
2547    let mut missing_required_captures = Vec::new();
2548    for (capture_ix, capture) in captures.iter().enumerate() {
2549        if let Capture::Required(capture_name, _) = capture
2550            && !found_required_indices.contains(&capture_ix)
2551        {
2552            missing_required_captures.push(*capture_name);
2553        }
2554    }
2555    let success = missing_required_captures.is_empty();
2556    if !success {
2557        log::error!(
2558            "missing required capture(s) in {} {} TreeSitter query: {}",
2559            language_name,
2560            query_type,
2561            missing_required_captures.join(", ")
2562        );
2563    }
2564    success
2565}
2566
2567pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
2568    lsp::Position::new(point.row, point.column)
2569}
2570
2571pub const fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
2572    Unclipped(PointUtf16::new(point.line, point.character))
2573}
2574
2575pub fn range_to_lsp(range: Range<PointUtf16>) -> Result<lsp::Range> {
2576    anyhow::ensure!(
2577        range.start <= range.end,
2578        "Inverted range provided to an LSP request: {:?}-{:?}",
2579        range.start,
2580        range.end
2581    );
2582    Ok(lsp::Range {
2583        start: point_to_lsp(range.start),
2584        end: point_to_lsp(range.end),
2585    })
2586}
2587
2588pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
2589    let mut start = point_from_lsp(range.start);
2590    let mut end = point_from_lsp(range.end);
2591    if start > end {
2592        log::warn!("range_from_lsp called with inverted range {start:?}-{end:?}");
2593        mem::swap(&mut start, &mut end);
2594    }
2595    start..end
2596}
2597
2598#[cfg(test)]
2599mod tests {
2600    use super::*;
2601    use gpui::TestAppContext;
2602    use pretty_assertions::assert_matches;
2603
2604    #[gpui::test(iterations = 10)]
2605    async fn test_language_loading(cx: &mut TestAppContext) {
2606        let languages = LanguageRegistry::test(cx.executor());
2607        let languages = Arc::new(languages);
2608        languages.register_native_grammars([
2609            ("json", tree_sitter_json::LANGUAGE),
2610            ("rust", tree_sitter_rust::LANGUAGE),
2611        ]);
2612        languages.register_test_language(LanguageConfig {
2613            name: "JSON".into(),
2614            grammar: Some("json".into()),
2615            matcher: LanguageMatcher {
2616                path_suffixes: vec!["json".into()],
2617                ..Default::default()
2618            },
2619            ..Default::default()
2620        });
2621        languages.register_test_language(LanguageConfig {
2622            name: "Rust".into(),
2623            grammar: Some("rust".into()),
2624            matcher: LanguageMatcher {
2625                path_suffixes: vec!["rs".into()],
2626                ..Default::default()
2627            },
2628            ..Default::default()
2629        });
2630        assert_eq!(
2631            languages.language_names(),
2632            &[
2633                LanguageName::new("JSON"),
2634                LanguageName::new("Plain Text"),
2635                LanguageName::new("Rust"),
2636            ]
2637        );
2638
2639        let rust1 = languages.language_for_name("Rust");
2640        let rust2 = languages.language_for_name("Rust");
2641
2642        // Ensure language is still listed even if it's being loaded.
2643        assert_eq!(
2644            languages.language_names(),
2645            &[
2646                LanguageName::new("JSON"),
2647                LanguageName::new("Plain Text"),
2648                LanguageName::new("Rust"),
2649            ]
2650        );
2651
2652        let (rust1, rust2) = futures::join!(rust1, rust2);
2653        assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
2654
2655        // Ensure language is still listed even after loading it.
2656        assert_eq!(
2657            languages.language_names(),
2658            &[
2659                LanguageName::new("JSON"),
2660                LanguageName::new("Plain Text"),
2661                LanguageName::new("Rust"),
2662            ]
2663        );
2664
2665        // Loading an unknown language returns an error.
2666        assert!(languages.language_for_name("Unknown").await.is_err());
2667    }
2668
2669    #[gpui::test]
2670    async fn test_completion_label_omits_duplicate_data() {
2671        let regular_completion_item_1 = lsp::CompletionItem {
2672            label: "regular1".to_string(),
2673            detail: Some("detail1".to_string()),
2674            label_details: Some(lsp::CompletionItemLabelDetails {
2675                detail: None,
2676                description: Some("description 1".to_string()),
2677            }),
2678            ..lsp::CompletionItem::default()
2679        };
2680
2681        let regular_completion_item_2 = lsp::CompletionItem {
2682            label: "regular2".to_string(),
2683            label_details: Some(lsp::CompletionItemLabelDetails {
2684                detail: None,
2685                description: Some("description 2".to_string()),
2686            }),
2687            ..lsp::CompletionItem::default()
2688        };
2689
2690        let completion_item_with_duplicate_detail_and_proper_description = lsp::CompletionItem {
2691            detail: Some(regular_completion_item_1.label.clone()),
2692            ..regular_completion_item_1.clone()
2693        };
2694
2695        let completion_item_with_duplicate_detail = lsp::CompletionItem {
2696            detail: Some(regular_completion_item_1.label.clone()),
2697            label_details: None,
2698            ..regular_completion_item_1.clone()
2699        };
2700
2701        let completion_item_with_duplicate_description = lsp::CompletionItem {
2702            label_details: Some(lsp::CompletionItemLabelDetails {
2703                detail: None,
2704                description: Some(regular_completion_item_2.label.clone()),
2705            }),
2706            ..regular_completion_item_2.clone()
2707        };
2708
2709        assert_eq!(
2710            CodeLabel::fallback_for_completion(&regular_completion_item_1, None).text,
2711            format!(
2712                "{} {}",
2713                regular_completion_item_1.label,
2714                regular_completion_item_1.detail.unwrap()
2715            ),
2716            "LSP completion items with both detail and label_details.description should prefer detail"
2717        );
2718        assert_eq!(
2719            CodeLabel::fallback_for_completion(&regular_completion_item_2, None).text,
2720            format!(
2721                "{} {}",
2722                regular_completion_item_2.label,
2723                regular_completion_item_2
2724                    .label_details
2725                    .as_ref()
2726                    .unwrap()
2727                    .description
2728                    .as_ref()
2729                    .unwrap()
2730            ),
2731            "LSP completion items without detail but with label_details.description should use that"
2732        );
2733        assert_eq!(
2734            CodeLabel::fallback_for_completion(
2735                &completion_item_with_duplicate_detail_and_proper_description,
2736                None
2737            )
2738            .text,
2739            format!(
2740                "{} {}",
2741                regular_completion_item_1.label,
2742                regular_completion_item_1
2743                    .label_details
2744                    .as_ref()
2745                    .unwrap()
2746                    .description
2747                    .as_ref()
2748                    .unwrap()
2749            ),
2750            "LSP completion items with both detail and label_details.description should prefer description only if the detail duplicates the completion label"
2751        );
2752        assert_eq!(
2753            CodeLabel::fallback_for_completion(&completion_item_with_duplicate_detail, None).text,
2754            regular_completion_item_1.label,
2755            "LSP completion items with duplicate label and detail, should omit the detail"
2756        );
2757        assert_eq!(
2758            CodeLabel::fallback_for_completion(&completion_item_with_duplicate_description, None)
2759                .text,
2760            regular_completion_item_2.label,
2761            "LSP completion items with duplicate label and detail, should omit the detail"
2762        );
2763    }
2764
2765    #[test]
2766    fn test_deserializing_comments_backwards_compat() {
2767        // current version of `block_comment` and `documentation_comment` work
2768        {
2769            let config: LanguageConfig = ::toml::from_str(
2770                r#"
2771                name = "Foo"
2772                block_comment = { start = "a", end = "b", prefix = "c", tab_size = 1 }
2773                documentation_comment = { start = "d", end = "e", prefix = "f", tab_size = 2 }
2774                "#,
2775            )
2776            .unwrap();
2777            assert_matches!(config.block_comment, Some(BlockCommentConfig { .. }));
2778            assert_matches!(
2779                config.documentation_comment,
2780                Some(BlockCommentConfig { .. })
2781            );
2782
2783            let block_config = config.block_comment.unwrap();
2784            assert_eq!(block_config.start.as_ref(), "a");
2785            assert_eq!(block_config.end.as_ref(), "b");
2786            assert_eq!(block_config.prefix.as_ref(), "c");
2787            assert_eq!(block_config.tab_size, 1);
2788
2789            let doc_config = config.documentation_comment.unwrap();
2790            assert_eq!(doc_config.start.as_ref(), "d");
2791            assert_eq!(doc_config.end.as_ref(), "e");
2792            assert_eq!(doc_config.prefix.as_ref(), "f");
2793            assert_eq!(doc_config.tab_size, 2);
2794        }
2795
2796        // former `documentation` setting is read into `documentation_comment`
2797        {
2798            let config: LanguageConfig = ::toml::from_str(
2799                r#"
2800                name = "Foo"
2801                documentation = { start = "a", end = "b", prefix = "c", tab_size = 1}
2802                "#,
2803            )
2804            .unwrap();
2805            assert_matches!(
2806                config.documentation_comment,
2807                Some(BlockCommentConfig { .. })
2808            );
2809
2810            let config = config.documentation_comment.unwrap();
2811            assert_eq!(config.start.as_ref(), "a");
2812            assert_eq!(config.end.as_ref(), "b");
2813            assert_eq!(config.prefix.as_ref(), "c");
2814            assert_eq!(config.tab_size, 1);
2815        }
2816
2817        // old block_comment format is read into BlockCommentConfig
2818        {
2819            let config: LanguageConfig = ::toml::from_str(
2820                r#"
2821                name = "Foo"
2822                block_comment = ["a", "b"]
2823                "#,
2824            )
2825            .unwrap();
2826            assert_matches!(config.block_comment, Some(BlockCommentConfig { .. }));
2827
2828            let config = config.block_comment.unwrap();
2829            assert_eq!(config.start.as_ref(), "a");
2830            assert_eq!(config.end.as_ref(), "b");
2831            assert_eq!(config.prefix.as_ref(), "");
2832            assert_eq!(config.tab_size, 0);
2833        }
2834    }
2835}