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