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