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