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, auto indentation uses last non empty line to determine
 700    /// the indentation level for a new line.
 701    #[serde(default = "auto_indent_using_last_non_empty_line_default")]
 702    pub auto_indent_using_last_non_empty_line: bool,
 703    // Whether indentation of pasted content should be adjusted based on the context.
 704    #[serde(default)]
 705    pub auto_indent_on_paste: Option<bool>,
 706    /// A regex that is used to determine whether the indentation level should be
 707    /// increased in the following line.
 708    #[serde(default, deserialize_with = "deserialize_regex")]
 709    #[schemars(schema_with = "regex_json_schema")]
 710    pub increase_indent_pattern: Option<Regex>,
 711    /// A regex that is used to determine whether the indentation level should be
 712    /// decreased in the following line.
 713    #[serde(default, deserialize_with = "deserialize_regex")]
 714    #[schemars(schema_with = "regex_json_schema")]
 715    pub decrease_indent_pattern: Option<Regex>,
 716    /// A list of rules for decreasing indentation. Each rule pairs a regex with a set of valid
 717    /// "block-starting" tokens. When a line matches a pattern, its indentation is aligned with
 718    /// the most recent line that began with a corresponding token. This enables context-aware
 719    /// outdenting, like aligning an `else` with its `if`.
 720    #[serde(default)]
 721    pub decrease_indent_patterns: Vec<DecreaseIndentConfig>,
 722    /// A list of characters that trigger the automatic insertion of a closing
 723    /// bracket when they immediately precede the point where an opening
 724    /// bracket is inserted.
 725    #[serde(default)]
 726    pub autoclose_before: String,
 727    /// A placeholder used internally by Semantic Index.
 728    #[serde(default)]
 729    pub collapsed_placeholder: String,
 730    /// A line comment string that is inserted in e.g. `toggle comments` action.
 731    /// A language can have multiple flavours of line comments. All of the provided line comments are
 732    /// used for comment continuations on the next line, but only the first one is used for Editor::ToggleComments.
 733    #[serde(default)]
 734    pub line_comments: Vec<Arc<str>>,
 735    /// Starting and closing characters of a block comment.
 736    #[serde(default)]
 737    pub block_comment: Option<(Arc<str>, Arc<str>)>,
 738    /// A list of language servers that are allowed to run on subranges of a given language.
 739    #[serde(default)]
 740    pub scope_opt_in_language_servers: Vec<LanguageServerName>,
 741    #[serde(default)]
 742    pub overrides: HashMap<String, LanguageConfigOverride>,
 743    /// A list of characters that Zed should treat as word characters for the
 744    /// purpose of features that operate on word boundaries, like 'move to next word end'
 745    /// or a whole-word search in buffer search.
 746    #[serde(default)]
 747    pub word_characters: HashSet<char>,
 748    /// Whether to indent lines using tab characters, as opposed to multiple
 749    /// spaces.
 750    #[serde(default)]
 751    pub hard_tabs: Option<bool>,
 752    /// How many columns a tab should occupy.
 753    #[serde(default)]
 754    pub tab_size: Option<NonZeroU32>,
 755    /// How to soft-wrap long lines of text.
 756    #[serde(default)]
 757    pub soft_wrap: Option<SoftWrap>,
 758    /// The name of a Prettier parser that will be used for this language when no file path is available.
 759    /// If there's a parser name in the language settings, that will be used instead.
 760    #[serde(default)]
 761    pub prettier_parser_name: Option<String>,
 762    /// If true, this language is only for syntax highlighting via an injection into other
 763    /// languages, but should not appear to the user as a distinct language.
 764    #[serde(default)]
 765    pub hidden: bool,
 766    /// If configured, this language contains JSX style tags, and should support auto-closing of those tags.
 767    #[serde(default)]
 768    pub jsx_tag_auto_close: Option<JsxTagAutoCloseConfig>,
 769    /// A list of characters that Zed should treat as word characters for completion queries.
 770    #[serde(default)]
 771    pub completion_query_characters: HashSet<char>,
 772    /// A list of preferred debuggers for this language.
 773    #[serde(default)]
 774    pub debuggers: IndexSet<SharedString>,
 775    /// Whether to treat documentation comment of this language differently by
 776    /// auto adding prefix on new line, adjusting the indenting , etc.
 777    #[serde(default)]
 778    pub documentation: Option<DocumentationConfig>,
 779}
 780
 781#[derive(Clone, Debug, Deserialize, Default, JsonSchema)]
 782pub struct DecreaseIndentConfig {
 783    #[serde(default, deserialize_with = "deserialize_regex")]
 784    #[schemars(schema_with = "regex_json_schema")]
 785    pub pattern: Option<Regex>,
 786    #[serde(default)]
 787    pub valid_after: Vec<String>,
 788}
 789
 790#[derive(Clone, Debug, Serialize, Deserialize, Default, JsonSchema)]
 791pub struct LanguageMatcher {
 792    /// 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`.
 793    #[serde(default)]
 794    pub path_suffixes: Vec<String>,
 795    /// A regex pattern that determines whether the language should be assigned to a file or not.
 796    #[serde(
 797        default,
 798        serialize_with = "serialize_regex",
 799        deserialize_with = "deserialize_regex"
 800    )]
 801    #[schemars(schema_with = "regex_json_schema")]
 802    pub first_line_pattern: Option<Regex>,
 803}
 804
 805/// The configuration for JSX tag auto-closing.
 806#[derive(Clone, Deserialize, JsonSchema)]
 807pub struct JsxTagAutoCloseConfig {
 808    /// The name of the node for a opening tag
 809    pub open_tag_node_name: String,
 810    /// The name of the node for an closing tag
 811    pub close_tag_node_name: String,
 812    /// The name of the node for a complete element with children for open and close tags
 813    pub jsx_element_node_name: String,
 814    /// The name of the node found within both opening and closing
 815    /// tags that describes the tag name
 816    pub tag_name_node_name: String,
 817    /// Alternate Node names for tag names.
 818    /// Specifically needed as TSX represents the name in `<Foo.Bar>`
 819    /// as `member_expression` rather than `identifier` as usual
 820    #[serde(default)]
 821    pub tag_name_node_name_alternates: Vec<String>,
 822    /// Some grammars are smart enough to detect a closing tag
 823    /// that is not valid i.e. doesn't match it's corresponding
 824    /// opening tag or does not have a corresponding opening tag
 825    /// This should be set to the name of the node for invalid
 826    /// closing tags if the grammar contains such a node, otherwise
 827    /// detecting already closed tags will not work properly
 828    #[serde(default)]
 829    pub erroneous_close_tag_node_name: Option<String>,
 830    /// See above for erroneous_close_tag_node_name for details
 831    /// This should be set if the node used for the tag name
 832    /// within erroneous closing tags is different from the
 833    /// normal tag name node name
 834    #[serde(default)]
 835    pub erroneous_close_tag_name_node_name: Option<String>,
 836}
 837
 838/// The configuration for documentation block for this language.
 839#[derive(Clone, Deserialize, JsonSchema)]
 840pub struct DocumentationConfig {
 841    /// A start tag of documentation block.
 842    pub start: Arc<str>,
 843    /// A end tag of documentation block.
 844    pub end: Arc<str>,
 845    /// A character to add as a prefix when a new line is added to a documentation block.
 846    pub prefix: Arc<str>,
 847    /// A indent to add for prefix and end line upon new line.
 848    pub tab_size: NonZeroU32,
 849}
 850
 851/// Represents a language for the given range. Some languages (e.g. HTML)
 852/// interleave several languages together, thus a single buffer might actually contain
 853/// several nested scopes.
 854#[derive(Clone, Debug)]
 855pub struct LanguageScope {
 856    language: Arc<Language>,
 857    override_id: Option<u32>,
 858}
 859
 860#[derive(Clone, Deserialize, Default, Debug, JsonSchema)]
 861pub struct LanguageConfigOverride {
 862    #[serde(default)]
 863    pub line_comments: Override<Vec<Arc<str>>>,
 864    #[serde(default)]
 865    pub block_comment: Override<(Arc<str>, Arc<str>)>,
 866    #[serde(skip)]
 867    pub disabled_bracket_ixs: Vec<u16>,
 868    #[serde(default)]
 869    pub word_characters: Override<HashSet<char>>,
 870    #[serde(default)]
 871    pub completion_query_characters: Override<HashSet<char>>,
 872    #[serde(default)]
 873    pub opt_into_language_servers: Vec<LanguageServerName>,
 874    #[serde(default)]
 875    pub prefer_label_for_snippet: Option<bool>,
 876}
 877
 878#[derive(Clone, Deserialize, Debug, Serialize, JsonSchema)]
 879#[serde(untagged)]
 880pub enum Override<T> {
 881    Remove { remove: bool },
 882    Set(T),
 883}
 884
 885impl<T> Default for Override<T> {
 886    fn default() -> Self {
 887        Override::Remove { remove: false }
 888    }
 889}
 890
 891impl<T> Override<T> {
 892    fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
 893        match this {
 894            Some(Self::Set(value)) => Some(value),
 895            Some(Self::Remove { remove: true }) => None,
 896            Some(Self::Remove { remove: false }) | None => original,
 897        }
 898    }
 899}
 900
 901impl Default for LanguageConfig {
 902    fn default() -> Self {
 903        Self {
 904            name: LanguageName::new(""),
 905            code_fence_block_name: None,
 906            grammar: None,
 907            matcher: LanguageMatcher::default(),
 908            brackets: Default::default(),
 909            auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
 910            auto_indent_on_paste: None,
 911            increase_indent_pattern: Default::default(),
 912            decrease_indent_pattern: Default::default(),
 913            decrease_indent_patterns: Default::default(),
 914            autoclose_before: Default::default(),
 915            line_comments: Default::default(),
 916            block_comment: Default::default(),
 917            scope_opt_in_language_servers: Default::default(),
 918            overrides: Default::default(),
 919            word_characters: Default::default(),
 920            collapsed_placeholder: Default::default(),
 921            hard_tabs: None,
 922            tab_size: None,
 923            soft_wrap: None,
 924            prettier_parser_name: None,
 925            hidden: false,
 926            jsx_tag_auto_close: None,
 927            completion_query_characters: Default::default(),
 928            debuggers: Default::default(),
 929            documentation: None,
 930        }
 931    }
 932}
 933
 934fn auto_indent_using_last_non_empty_line_default() -> bool {
 935    true
 936}
 937
 938fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
 939    let source = Option::<String>::deserialize(d)?;
 940    if let Some(source) = source {
 941        Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
 942    } else {
 943        Ok(None)
 944    }
 945}
 946
 947fn regex_json_schema(_: &mut SchemaGenerator) -> Schema {
 948    Schema::Object(SchemaObject {
 949        instance_type: Some(InstanceType::String.into()),
 950        ..Default::default()
 951    })
 952}
 953
 954fn serialize_regex<S>(regex: &Option<Regex>, serializer: S) -> Result<S::Ok, S::Error>
 955where
 956    S: Serializer,
 957{
 958    match regex {
 959        Some(regex) => serializer.serialize_str(regex.as_str()),
 960        None => serializer.serialize_none(),
 961    }
 962}
 963
 964#[doc(hidden)]
 965#[cfg(any(test, feature = "test-support"))]
 966pub struct FakeLspAdapter {
 967    pub name: &'static str,
 968    pub initialization_options: Option<Value>,
 969    pub prettier_plugins: Vec<&'static str>,
 970    pub disk_based_diagnostics_progress_token: Option<String>,
 971    pub disk_based_diagnostics_sources: Vec<String>,
 972    pub language_server_binary: LanguageServerBinary,
 973
 974    pub capabilities: lsp::ServerCapabilities,
 975    pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
 976    pub label_for_completion: Option<
 977        Box<
 978            dyn 'static
 979                + Send
 980                + Sync
 981                + Fn(&lsp::CompletionItem, &Arc<Language>) -> Option<CodeLabel>,
 982        >,
 983    >,
 984}
 985
 986/// Configuration of handling bracket pairs for a given language.
 987///
 988/// This struct includes settings for defining which pairs of characters are considered brackets and
 989/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
 990#[derive(Clone, Debug, Default, JsonSchema)]
 991pub struct BracketPairConfig {
 992    /// A list of character pairs that should be treated as brackets in the context of a given language.
 993    pub pairs: Vec<BracketPair>,
 994    /// A list of tree-sitter scopes for which a given bracket should not be active.
 995    /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
 996    #[serde(skip)]
 997    pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
 998}
 999
1000impl BracketPairConfig {
1001    pub fn is_closing_brace(&self, c: char) -> bool {
1002        self.pairs.iter().any(|pair| pair.end.starts_with(c))
1003    }
1004}
1005
1006fn bracket_pair_config_json_schema(r#gen: &mut SchemaGenerator) -> Schema {
1007    Option::<Vec<BracketPairContent>>::json_schema(r#gen)
1008}
1009
1010#[derive(Deserialize, JsonSchema)]
1011pub struct BracketPairContent {
1012    #[serde(flatten)]
1013    pub bracket_pair: BracketPair,
1014    #[serde(default)]
1015    pub not_in: Vec<String>,
1016}
1017
1018impl<'de> Deserialize<'de> for BracketPairConfig {
1019    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1020    where
1021        D: Deserializer<'de>,
1022    {
1023        let result = Vec::<BracketPairContent>::deserialize(deserializer)?;
1024        let mut brackets = Vec::with_capacity(result.len());
1025        let mut disabled_scopes_by_bracket_ix = Vec::with_capacity(result.len());
1026        for entry in result {
1027            brackets.push(entry.bracket_pair);
1028            disabled_scopes_by_bracket_ix.push(entry.not_in);
1029        }
1030
1031        Ok(BracketPairConfig {
1032            pairs: brackets,
1033            disabled_scopes_by_bracket_ix,
1034        })
1035    }
1036}
1037
1038/// Describes a single bracket pair and how an editor should react to e.g. inserting
1039/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
1040#[derive(Clone, Debug, Default, Deserialize, PartialEq, JsonSchema)]
1041pub struct BracketPair {
1042    /// Starting substring for a bracket.
1043    pub start: String,
1044    /// Ending substring for a bracket.
1045    pub end: String,
1046    /// True if `end` should be automatically inserted right after `start` characters.
1047    pub close: bool,
1048    /// True if selected text should be surrounded by `start` and `end` characters.
1049    #[serde(default = "default_true")]
1050    pub surround: bool,
1051    /// True if an extra newline should be inserted while the cursor is in the middle
1052    /// of that bracket pair.
1053    pub newline: bool,
1054}
1055
1056#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
1057pub struct LanguageId(usize);
1058
1059impl LanguageId {
1060    pub(crate) fn new() -> Self {
1061        Self(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst))
1062    }
1063}
1064
1065pub struct Language {
1066    pub(crate) id: LanguageId,
1067    pub(crate) config: LanguageConfig,
1068    pub(crate) grammar: Option<Arc<Grammar>>,
1069    pub(crate) context_provider: Option<Arc<dyn ContextProvider>>,
1070    pub(crate) toolchain: Option<Arc<dyn ToolchainLister>>,
1071}
1072
1073#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
1074pub struct GrammarId(pub usize);
1075
1076impl GrammarId {
1077    pub(crate) fn new() -> Self {
1078        Self(NEXT_GRAMMAR_ID.fetch_add(1, SeqCst))
1079    }
1080}
1081
1082pub struct Grammar {
1083    id: GrammarId,
1084    pub ts_language: tree_sitter::Language,
1085    pub(crate) error_query: Option<Query>,
1086    pub(crate) highlights_query: Option<Query>,
1087    pub(crate) brackets_config: Option<BracketsConfig>,
1088    pub(crate) redactions_config: Option<RedactionConfig>,
1089    pub(crate) runnable_config: Option<RunnableConfig>,
1090    pub(crate) indents_config: Option<IndentConfig>,
1091    pub outline_config: Option<OutlineConfig>,
1092    pub text_object_config: Option<TextObjectConfig>,
1093    pub embedding_config: Option<EmbeddingConfig>,
1094    pub(crate) injection_config: Option<InjectionConfig>,
1095    pub(crate) override_config: Option<OverrideConfig>,
1096    pub(crate) debug_variables_config: Option<DebugVariablesConfig>,
1097    pub(crate) highlight_map: Mutex<HighlightMap>,
1098}
1099
1100struct IndentConfig {
1101    query: Query,
1102    indent_capture_ix: u32,
1103    start_capture_ix: Option<u32>,
1104    end_capture_ix: Option<u32>,
1105    outdent_capture_ix: Option<u32>,
1106    suffixed_start_captures: HashMap<u32, SharedString>,
1107}
1108
1109pub struct OutlineConfig {
1110    pub query: Query,
1111    pub item_capture_ix: u32,
1112    pub name_capture_ix: u32,
1113    pub context_capture_ix: Option<u32>,
1114    pub extra_context_capture_ix: Option<u32>,
1115    pub open_capture_ix: Option<u32>,
1116    pub close_capture_ix: Option<u32>,
1117    pub annotation_capture_ix: Option<u32>,
1118}
1119
1120#[derive(Debug, Clone, Copy, PartialEq)]
1121pub enum DebuggerTextObject {
1122    Variable,
1123    Scope,
1124}
1125
1126impl DebuggerTextObject {
1127    pub fn from_capture_name(name: &str) -> Option<DebuggerTextObject> {
1128        match name {
1129            "debug-variable" => Some(DebuggerTextObject::Variable),
1130            "debug-scope" => Some(DebuggerTextObject::Scope),
1131            _ => None,
1132        }
1133    }
1134}
1135
1136#[derive(Debug, Clone, Copy, PartialEq)]
1137pub enum TextObject {
1138    InsideFunction,
1139    AroundFunction,
1140    InsideClass,
1141    AroundClass,
1142    InsideComment,
1143    AroundComment,
1144}
1145
1146impl TextObject {
1147    pub fn from_capture_name(name: &str) -> Option<TextObject> {
1148        match name {
1149            "function.inside" => Some(TextObject::InsideFunction),
1150            "function.around" => Some(TextObject::AroundFunction),
1151            "class.inside" => Some(TextObject::InsideClass),
1152            "class.around" => Some(TextObject::AroundClass),
1153            "comment.inside" => Some(TextObject::InsideComment),
1154            "comment.around" => Some(TextObject::AroundComment),
1155            _ => None,
1156        }
1157    }
1158
1159    pub fn around(&self) -> Option<Self> {
1160        match self {
1161            TextObject::InsideFunction => Some(TextObject::AroundFunction),
1162            TextObject::InsideClass => Some(TextObject::AroundClass),
1163            TextObject::InsideComment => Some(TextObject::AroundComment),
1164            _ => None,
1165        }
1166    }
1167}
1168
1169pub struct TextObjectConfig {
1170    pub query: Query,
1171    pub text_objects_by_capture_ix: Vec<(u32, TextObject)>,
1172}
1173
1174#[derive(Debug)]
1175pub struct EmbeddingConfig {
1176    pub query: Query,
1177    pub item_capture_ix: u32,
1178    pub name_capture_ix: Option<u32>,
1179    pub context_capture_ix: Option<u32>,
1180    pub collapse_capture_ix: Option<u32>,
1181    pub keep_capture_ix: Option<u32>,
1182}
1183
1184struct InjectionConfig {
1185    query: Query,
1186    content_capture_ix: u32,
1187    language_capture_ix: Option<u32>,
1188    patterns: Vec<InjectionPatternConfig>,
1189}
1190
1191struct RedactionConfig {
1192    pub query: Query,
1193    pub redaction_capture_ix: u32,
1194}
1195
1196#[derive(Clone, Debug, PartialEq)]
1197enum RunnableCapture {
1198    Named(SharedString),
1199    Run,
1200}
1201
1202struct RunnableConfig {
1203    pub query: Query,
1204    /// A mapping from capture indice to capture kind
1205    pub extra_captures: Vec<RunnableCapture>,
1206}
1207
1208struct OverrideConfig {
1209    query: Query,
1210    values: HashMap<u32, OverrideEntry>,
1211}
1212
1213#[derive(Debug)]
1214struct OverrideEntry {
1215    name: String,
1216    range_is_inclusive: bool,
1217    value: LanguageConfigOverride,
1218}
1219
1220#[derive(Default, Clone)]
1221struct InjectionPatternConfig {
1222    language: Option<Box<str>>,
1223    combined: bool,
1224}
1225
1226struct BracketsConfig {
1227    query: Query,
1228    open_capture_ix: u32,
1229    close_capture_ix: u32,
1230    patterns: Vec<BracketsPatternConfig>,
1231}
1232
1233#[derive(Clone, Debug, Default)]
1234struct BracketsPatternConfig {
1235    newline_only: bool,
1236}
1237
1238pub struct DebugVariablesConfig {
1239    pub query: Query,
1240    pub objects_by_capture_ix: Vec<(u32, DebuggerTextObject)>,
1241}
1242
1243impl Language {
1244    pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
1245        Self::new_with_id(LanguageId::new(), config, ts_language)
1246    }
1247
1248    pub fn id(&self) -> LanguageId {
1249        self.id
1250    }
1251
1252    fn new_with_id(
1253        id: LanguageId,
1254        config: LanguageConfig,
1255        ts_language: Option<tree_sitter::Language>,
1256    ) -> Self {
1257        Self {
1258            id,
1259            config,
1260            grammar: ts_language.map(|ts_language| {
1261                Arc::new(Grammar {
1262                    id: GrammarId::new(),
1263                    highlights_query: None,
1264                    brackets_config: None,
1265                    outline_config: None,
1266                    text_object_config: None,
1267                    embedding_config: None,
1268                    indents_config: None,
1269                    injection_config: None,
1270                    override_config: None,
1271                    redactions_config: None,
1272                    runnable_config: None,
1273                    error_query: Query::new(&ts_language, "(ERROR) @error").ok(),
1274                    debug_variables_config: None,
1275                    ts_language,
1276                    highlight_map: Default::default(),
1277                })
1278            }),
1279            context_provider: None,
1280            toolchain: None,
1281        }
1282    }
1283
1284    pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
1285        self.context_provider = provider;
1286        self
1287    }
1288
1289    pub fn with_toolchain_lister(mut self, provider: Option<Arc<dyn ToolchainLister>>) -> Self {
1290        self.toolchain = provider;
1291        self
1292    }
1293
1294    pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
1295        if let Some(query) = queries.highlights {
1296            self = self
1297                .with_highlights_query(query.as_ref())
1298                .context("Error loading highlights query")?;
1299        }
1300        if let Some(query) = queries.brackets {
1301            self = self
1302                .with_brackets_query(query.as_ref())
1303                .context("Error loading brackets query")?;
1304        }
1305        if let Some(query) = queries.indents {
1306            self = self
1307                .with_indents_query(query.as_ref())
1308                .context("Error loading indents query")?;
1309        }
1310        if let Some(query) = queries.outline {
1311            self = self
1312                .with_outline_query(query.as_ref())
1313                .context("Error loading outline query")?;
1314        }
1315        if let Some(query) = queries.embedding {
1316            self = self
1317                .with_embedding_query(query.as_ref())
1318                .context("Error loading embedding query")?;
1319        }
1320        if let Some(query) = queries.injections {
1321            self = self
1322                .with_injection_query(query.as_ref())
1323                .context("Error loading injection query")?;
1324        }
1325        if let Some(query) = queries.overrides {
1326            self = self
1327                .with_override_query(query.as_ref())
1328                .context("Error loading override query")?;
1329        }
1330        if let Some(query) = queries.redactions {
1331            self = self
1332                .with_redaction_query(query.as_ref())
1333                .context("Error loading redaction query")?;
1334        }
1335        if let Some(query) = queries.runnables {
1336            self = self
1337                .with_runnable_query(query.as_ref())
1338                .context("Error loading runnables query")?;
1339        }
1340        if let Some(query) = queries.text_objects {
1341            self = self
1342                .with_text_object_query(query.as_ref())
1343                .context("Error loading textobject query")?;
1344        }
1345        if let Some(query) = queries.debugger {
1346            self = self
1347                .with_debug_variables_query(query.as_ref())
1348                .context("Error loading debug variables query")?;
1349        }
1350        Ok(self)
1351    }
1352
1353    pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1354        let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1355        grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
1356        Ok(self)
1357    }
1358
1359    pub fn with_runnable_query(mut self, source: &str) -> Result<Self> {
1360        let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1361
1362        let query = Query::new(&grammar.ts_language, source)?;
1363        let mut extra_captures = Vec::with_capacity(query.capture_names().len());
1364
1365        for name in query.capture_names().iter() {
1366            let kind = if *name == "run" {
1367                RunnableCapture::Run
1368            } else {
1369                RunnableCapture::Named(name.to_string().into())
1370            };
1371            extra_captures.push(kind);
1372        }
1373
1374        grammar.runnable_config = Some(RunnableConfig {
1375            extra_captures,
1376            query,
1377        });
1378
1379        Ok(self)
1380    }
1381
1382    pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1383        let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1384        let query = Query::new(&grammar.ts_language, source)?;
1385        let mut item_capture_ix = None;
1386        let mut name_capture_ix = None;
1387        let mut context_capture_ix = None;
1388        let mut extra_context_capture_ix = None;
1389        let mut open_capture_ix = None;
1390        let mut close_capture_ix = None;
1391        let mut annotation_capture_ix = None;
1392        get_capture_indices(
1393            &query,
1394            &mut [
1395                ("item", &mut item_capture_ix),
1396                ("name", &mut name_capture_ix),
1397                ("context", &mut context_capture_ix),
1398                ("context.extra", &mut extra_context_capture_ix),
1399                ("open", &mut open_capture_ix),
1400                ("close", &mut close_capture_ix),
1401                ("annotation", &mut annotation_capture_ix),
1402            ],
1403        );
1404        if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
1405            grammar.outline_config = Some(OutlineConfig {
1406                query,
1407                item_capture_ix,
1408                name_capture_ix,
1409                context_capture_ix,
1410                extra_context_capture_ix,
1411                open_capture_ix,
1412                close_capture_ix,
1413                annotation_capture_ix,
1414            });
1415        }
1416        Ok(self)
1417    }
1418
1419    pub fn with_text_object_query(mut self, source: &str) -> Result<Self> {
1420        let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1421        let query = Query::new(&grammar.ts_language, source)?;
1422
1423        let mut text_objects_by_capture_ix = Vec::new();
1424        for (ix, name) in query.capture_names().iter().enumerate() {
1425            if let Some(text_object) = TextObject::from_capture_name(name) {
1426                text_objects_by_capture_ix.push((ix as u32, text_object));
1427            }
1428        }
1429
1430        grammar.text_object_config = Some(TextObjectConfig {
1431            query,
1432            text_objects_by_capture_ix,
1433        });
1434        Ok(self)
1435    }
1436
1437    pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
1438        let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1439        let query = Query::new(&grammar.ts_language, source)?;
1440        let mut item_capture_ix = None;
1441        let mut name_capture_ix = None;
1442        let mut context_capture_ix = None;
1443        let mut collapse_capture_ix = None;
1444        let mut keep_capture_ix = None;
1445        get_capture_indices(
1446            &query,
1447            &mut [
1448                ("item", &mut item_capture_ix),
1449                ("name", &mut name_capture_ix),
1450                ("context", &mut context_capture_ix),
1451                ("keep", &mut keep_capture_ix),
1452                ("collapse", &mut collapse_capture_ix),
1453            ],
1454        );
1455        if let Some(item_capture_ix) = item_capture_ix {
1456            grammar.embedding_config = Some(EmbeddingConfig {
1457                query,
1458                item_capture_ix,
1459                name_capture_ix,
1460                context_capture_ix,
1461                collapse_capture_ix,
1462                keep_capture_ix,
1463            });
1464        }
1465        Ok(self)
1466    }
1467
1468    pub fn with_debug_variables_query(mut self, source: &str) -> Result<Self> {
1469        let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1470        let query = Query::new(&grammar.ts_language, source)?;
1471
1472        let mut objects_by_capture_ix = Vec::new();
1473        for (ix, name) in query.capture_names().iter().enumerate() {
1474            if let Some(text_object) = DebuggerTextObject::from_capture_name(name) {
1475                objects_by_capture_ix.push((ix as u32, text_object));
1476            }
1477        }
1478
1479        grammar.debug_variables_config = Some(DebugVariablesConfig {
1480            query,
1481            objects_by_capture_ix,
1482        });
1483        Ok(self)
1484    }
1485
1486    pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1487        let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1488        let query = Query::new(&grammar.ts_language, source)?;
1489        let mut open_capture_ix = None;
1490        let mut close_capture_ix = None;
1491        get_capture_indices(
1492            &query,
1493            &mut [
1494                ("open", &mut open_capture_ix),
1495                ("close", &mut close_capture_ix),
1496            ],
1497        );
1498        let patterns = (0..query.pattern_count())
1499            .map(|ix| {
1500                let mut config = BracketsPatternConfig::default();
1501                for setting in query.property_settings(ix) {
1502                    match setting.key.as_ref() {
1503                        "newline.only" => config.newline_only = true,
1504                        _ => {}
1505                    }
1506                }
1507                config
1508            })
1509            .collect();
1510        if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1511            grammar.brackets_config = Some(BracketsConfig {
1512                query,
1513                open_capture_ix,
1514                close_capture_ix,
1515                patterns,
1516            });
1517        }
1518        Ok(self)
1519    }
1520
1521    pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1522        let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1523        let query = Query::new(&grammar.ts_language, source)?;
1524        let mut indent_capture_ix = None;
1525        let mut start_capture_ix = None;
1526        let mut end_capture_ix = None;
1527        let mut outdent_capture_ix = None;
1528        get_capture_indices(
1529            &query,
1530            &mut [
1531                ("indent", &mut indent_capture_ix),
1532                ("start", &mut start_capture_ix),
1533                ("end", &mut end_capture_ix),
1534                ("outdent", &mut outdent_capture_ix),
1535            ],
1536        );
1537
1538        let mut suffixed_start_captures = HashMap::default();
1539        for (ix, name) in query.capture_names().iter().enumerate() {
1540            if let Some(suffix) = name.strip_prefix("start.") {
1541                suffixed_start_captures.insert(ix as u32, suffix.to_owned().into());
1542            }
1543        }
1544
1545        if let Some(indent_capture_ix) = indent_capture_ix {
1546            grammar.indents_config = Some(IndentConfig {
1547                query,
1548                indent_capture_ix,
1549                start_capture_ix,
1550                end_capture_ix,
1551                outdent_capture_ix,
1552                suffixed_start_captures,
1553            });
1554        }
1555        Ok(self)
1556    }
1557
1558    pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1559        let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1560        let query = Query::new(&grammar.ts_language, source)?;
1561        let mut language_capture_ix = None;
1562        let mut injection_language_capture_ix = None;
1563        let mut content_capture_ix = None;
1564        let mut injection_content_capture_ix = None;
1565        get_capture_indices(
1566            &query,
1567            &mut [
1568                ("language", &mut language_capture_ix),
1569                ("injection.language", &mut injection_language_capture_ix),
1570                ("content", &mut content_capture_ix),
1571                ("injection.content", &mut injection_content_capture_ix),
1572            ],
1573        );
1574        language_capture_ix = match (language_capture_ix, injection_language_capture_ix) {
1575            (None, Some(ix)) => Some(ix),
1576            (Some(_), Some(_)) => {
1577                anyhow::bail!("both language and injection.language captures are present");
1578            }
1579            _ => language_capture_ix,
1580        };
1581        content_capture_ix = match (content_capture_ix, injection_content_capture_ix) {
1582            (None, Some(ix)) => Some(ix),
1583            (Some(_), Some(_)) => {
1584                anyhow::bail!("both content and injection.content captures are present")
1585            }
1586            _ => content_capture_ix,
1587        };
1588        let patterns = (0..query.pattern_count())
1589            .map(|ix| {
1590                let mut config = InjectionPatternConfig::default();
1591                for setting in query.property_settings(ix) {
1592                    match setting.key.as_ref() {
1593                        "language" | "injection.language" => {
1594                            config.language.clone_from(&setting.value);
1595                        }
1596                        "combined" | "injection.combined" => {
1597                            config.combined = true;
1598                        }
1599                        _ => {}
1600                    }
1601                }
1602                config
1603            })
1604            .collect();
1605        if let Some(content_capture_ix) = content_capture_ix {
1606            grammar.injection_config = Some(InjectionConfig {
1607                query,
1608                language_capture_ix,
1609                content_capture_ix,
1610                patterns,
1611            });
1612        }
1613        Ok(self)
1614    }
1615
1616    pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1617        let query = {
1618            let grammar = self.grammar.as_ref().context("no grammar for language")?;
1619            Query::new(&grammar.ts_language, source)?
1620        };
1621
1622        let mut override_configs_by_id = HashMap::default();
1623        for (ix, mut name) in query.capture_names().iter().copied().enumerate() {
1624            let mut range_is_inclusive = false;
1625            if name.starts_with('_') {
1626                continue;
1627            }
1628            if let Some(prefix) = name.strip_suffix(".inclusive") {
1629                name = prefix;
1630                range_is_inclusive = true;
1631            }
1632
1633            let value = self.config.overrides.get(name).cloned().unwrap_or_default();
1634            for server_name in &value.opt_into_language_servers {
1635                if !self
1636                    .config
1637                    .scope_opt_in_language_servers
1638                    .contains(server_name)
1639                {
1640                    util::debug_panic!(
1641                        "Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server"
1642                    );
1643                }
1644            }
1645
1646            override_configs_by_id.insert(
1647                ix as u32,
1648                OverrideEntry {
1649                    name: name.to_string(),
1650                    range_is_inclusive,
1651                    value,
1652                },
1653            );
1654        }
1655
1656        let referenced_override_names = self.config.overrides.keys().chain(
1657            self.config
1658                .brackets
1659                .disabled_scopes_by_bracket_ix
1660                .iter()
1661                .flatten(),
1662        );
1663
1664        for referenced_name in referenced_override_names {
1665            if !override_configs_by_id
1666                .values()
1667                .any(|entry| entry.name == *referenced_name)
1668            {
1669                anyhow::bail!(
1670                    "language {:?} has overrides in config not in query: {referenced_name:?}",
1671                    self.config.name
1672                );
1673            }
1674        }
1675
1676        for entry in override_configs_by_id.values_mut() {
1677            entry.value.disabled_bracket_ixs = self
1678                .config
1679                .brackets
1680                .disabled_scopes_by_bracket_ix
1681                .iter()
1682                .enumerate()
1683                .filter_map(|(ix, disabled_scope_names)| {
1684                    if disabled_scope_names.contains(&entry.name) {
1685                        Some(ix as u16)
1686                    } else {
1687                        None
1688                    }
1689                })
1690                .collect();
1691        }
1692
1693        self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1694
1695        let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1696        grammar.override_config = Some(OverrideConfig {
1697            query,
1698            values: override_configs_by_id,
1699        });
1700        Ok(self)
1701    }
1702
1703    pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1704        let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1705
1706        let query = Query::new(&grammar.ts_language, source)?;
1707        let mut redaction_capture_ix = None;
1708        get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1709
1710        if let Some(redaction_capture_ix) = redaction_capture_ix {
1711            grammar.redactions_config = Some(RedactionConfig {
1712                query,
1713                redaction_capture_ix,
1714            });
1715        }
1716
1717        Ok(self)
1718    }
1719
1720    fn grammar_mut(&mut self) -> Option<&mut Grammar> {
1721        Arc::get_mut(self.grammar.as_mut()?)
1722    }
1723
1724    pub fn name(&self) -> LanguageName {
1725        self.config.name.clone()
1726    }
1727
1728    pub fn code_fence_block_name(&self) -> Arc<str> {
1729        self.config
1730            .code_fence_block_name
1731            .clone()
1732            .unwrap_or_else(|| self.config.name.as_ref().to_lowercase().into())
1733    }
1734
1735    pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1736        self.context_provider.clone()
1737    }
1738
1739    pub fn toolchain_lister(&self) -> Option<Arc<dyn ToolchainLister>> {
1740        self.toolchain.clone()
1741    }
1742
1743    pub fn highlight_text<'a>(
1744        self: &'a Arc<Self>,
1745        text: &'a Rope,
1746        range: Range<usize>,
1747    ) -> Vec<(Range<usize>, HighlightId)> {
1748        let mut result = Vec::new();
1749        if let Some(grammar) = &self.grammar {
1750            let tree = grammar.parse_text(text, None);
1751            let captures =
1752                SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1753                    grammar.highlights_query.as_ref()
1754                });
1755            let highlight_maps = vec![grammar.highlight_map()];
1756            let mut offset = 0;
1757            for chunk in
1758                BufferChunks::new(text, range, Some((captures, highlight_maps)), false, None)
1759            {
1760                let end_offset = offset + chunk.text.len();
1761                if let Some(highlight_id) = chunk.syntax_highlight_id {
1762                    if !highlight_id.is_default() {
1763                        result.push((offset..end_offset, highlight_id));
1764                    }
1765                }
1766                offset = end_offset;
1767            }
1768        }
1769        result
1770    }
1771
1772    pub fn path_suffixes(&self) -> &[String] {
1773        &self.config.matcher.path_suffixes
1774    }
1775
1776    pub fn should_autoclose_before(&self, c: char) -> bool {
1777        c.is_whitespace() || self.config.autoclose_before.contains(c)
1778    }
1779
1780    pub fn set_theme(&self, theme: &SyntaxTheme) {
1781        if let Some(grammar) = self.grammar.as_ref() {
1782            if let Some(highlights_query) = &grammar.highlights_query {
1783                *grammar.highlight_map.lock() =
1784                    HighlightMap::new(highlights_query.capture_names(), theme);
1785            }
1786        }
1787    }
1788
1789    pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1790        self.grammar.as_ref()
1791    }
1792
1793    pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1794        LanguageScope {
1795            language: self.clone(),
1796            override_id: None,
1797        }
1798    }
1799
1800    pub fn lsp_id(&self) -> String {
1801        self.config.name.lsp_id()
1802    }
1803
1804    pub fn prettier_parser_name(&self) -> Option<&str> {
1805        self.config.prettier_parser_name.as_deref()
1806    }
1807
1808    pub fn config(&self) -> &LanguageConfig {
1809        &self.config
1810    }
1811}
1812
1813impl LanguageScope {
1814    pub fn path_suffixes(&self) -> &[String] {
1815        &self.language.path_suffixes()
1816    }
1817
1818    pub fn language_name(&self) -> LanguageName {
1819        self.language.config.name.clone()
1820    }
1821
1822    pub fn collapsed_placeholder(&self) -> &str {
1823        self.language.config.collapsed_placeholder.as_ref()
1824    }
1825
1826    /// Returns line prefix that is inserted in e.g. line continuations or
1827    /// in `toggle comments` action.
1828    pub fn line_comment_prefixes(&self) -> &[Arc<str>] {
1829        Override::as_option(
1830            self.config_override().map(|o| &o.line_comments),
1831            Some(&self.language.config.line_comments),
1832        )
1833        .map_or([].as_slice(), |e| e.as_slice())
1834    }
1835
1836    pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1837        Override::as_option(
1838            self.config_override().map(|o| &o.block_comment),
1839            self.language.config.block_comment.as_ref(),
1840        )
1841        .map(|e| (&e.0, &e.1))
1842    }
1843
1844    /// Returns a list of language-specific word characters.
1845    ///
1846    /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1847    /// the purpose of actions like 'move to next word end` or whole-word search.
1848    /// It additionally accounts for language's additional word characters.
1849    pub fn word_characters(&self) -> Option<&HashSet<char>> {
1850        Override::as_option(
1851            self.config_override().map(|o| &o.word_characters),
1852            Some(&self.language.config.word_characters),
1853        )
1854    }
1855
1856    /// Returns a list of language-specific characters that are considered part of
1857    /// a completion query.
1858    pub fn completion_query_characters(&self) -> Option<&HashSet<char>> {
1859        Override::as_option(
1860            self.config_override()
1861                .map(|o| &o.completion_query_characters),
1862            Some(&self.language.config.completion_query_characters),
1863        )
1864    }
1865
1866    /// Returns whether to prefer snippet `label` over `new_text` to replace text when
1867    /// completion is accepted.
1868    ///
1869    /// In cases like when cursor is in string or renaming existing function,
1870    /// you don't want to expand function signature instead just want function name
1871    /// to replace existing one.
1872    pub fn prefers_label_for_snippet_in_completion(&self) -> bool {
1873        self.config_override()
1874            .and_then(|o| o.prefer_label_for_snippet)
1875            .unwrap_or(false)
1876    }
1877
1878    /// Returns config to documentation block for this language.
1879    ///
1880    /// Used for documentation styles that require a leading character on each line,
1881    /// such as the asterisk in JSDoc, Javadoc, etc.
1882    pub fn documentation(&self) -> Option<&DocumentationConfig> {
1883        self.language.config.documentation.as_ref()
1884    }
1885
1886    /// Returns a list of bracket pairs for a given language with an additional
1887    /// piece of information about whether the particular bracket pair is currently active for a given language.
1888    pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1889        let mut disabled_ids = self
1890            .config_override()
1891            .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1892        self.language
1893            .config
1894            .brackets
1895            .pairs
1896            .iter()
1897            .enumerate()
1898            .map(move |(ix, bracket)| {
1899                let mut is_enabled = true;
1900                if let Some(next_disabled_ix) = disabled_ids.first() {
1901                    if ix == *next_disabled_ix as usize {
1902                        disabled_ids = &disabled_ids[1..];
1903                        is_enabled = false;
1904                    }
1905                }
1906                (bracket, is_enabled)
1907            })
1908    }
1909
1910    pub fn should_autoclose_before(&self, c: char) -> bool {
1911        c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1912    }
1913
1914    pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1915        let config = &self.language.config;
1916        let opt_in_servers = &config.scope_opt_in_language_servers;
1917        if opt_in_servers.contains(name) {
1918            if let Some(over) = self.config_override() {
1919                over.opt_into_language_servers.contains(name)
1920            } else {
1921                false
1922            }
1923        } else {
1924            true
1925        }
1926    }
1927
1928    pub fn override_name(&self) -> Option<&str> {
1929        let id = self.override_id?;
1930        let grammar = self.language.grammar.as_ref()?;
1931        let override_config = grammar.override_config.as_ref()?;
1932        override_config.values.get(&id).map(|e| e.name.as_str())
1933    }
1934
1935    fn config_override(&self) -> Option<&LanguageConfigOverride> {
1936        let id = self.override_id?;
1937        let grammar = self.language.grammar.as_ref()?;
1938        let override_config = grammar.override_config.as_ref()?;
1939        override_config.values.get(&id).map(|e| &e.value)
1940    }
1941}
1942
1943impl Hash for Language {
1944    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1945        self.id.hash(state)
1946    }
1947}
1948
1949impl PartialEq for Language {
1950    fn eq(&self, other: &Self) -> bool {
1951        self.id.eq(&other.id)
1952    }
1953}
1954
1955impl Eq for Language {}
1956
1957impl Debug for Language {
1958    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1959        f.debug_struct("Language")
1960            .field("name", &self.config.name)
1961            .finish()
1962    }
1963}
1964
1965impl Grammar {
1966    pub fn id(&self) -> GrammarId {
1967        self.id
1968    }
1969
1970    fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1971        with_parser(|parser| {
1972            parser
1973                .set_language(&self.ts_language)
1974                .expect("incompatible grammar");
1975            let mut chunks = text.chunks_in_range(0..text.len());
1976            parser
1977                .parse_with_options(
1978                    &mut move |offset, _| {
1979                        chunks.seek(offset);
1980                        chunks.next().unwrap_or("").as_bytes()
1981                    },
1982                    old_tree.as_ref(),
1983                    None,
1984                )
1985                .unwrap()
1986        })
1987    }
1988
1989    pub fn highlight_map(&self) -> HighlightMap {
1990        self.highlight_map.lock().clone()
1991    }
1992
1993    pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1994        let capture_id = self
1995            .highlights_query
1996            .as_ref()?
1997            .capture_index_for_name(name)?;
1998        Some(self.highlight_map.lock().get(capture_id))
1999    }
2000
2001    pub fn debug_variables_config(&self) -> Option<&DebugVariablesConfig> {
2002        self.debug_variables_config.as_ref()
2003    }
2004}
2005
2006impl CodeLabel {
2007    pub fn fallback_for_completion(
2008        item: &lsp::CompletionItem,
2009        language: Option<&Language>,
2010    ) -> Self {
2011        let highlight_id = item.kind.and_then(|kind| {
2012            let grammar = language?.grammar()?;
2013            use lsp::CompletionItemKind as Kind;
2014            match kind {
2015                Kind::CLASS => grammar.highlight_id_for_name("type"),
2016                Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
2017                Kind::CONSTRUCTOR => grammar.highlight_id_for_name("constructor"),
2018                Kind::ENUM => grammar
2019                    .highlight_id_for_name("enum")
2020                    .or_else(|| grammar.highlight_id_for_name("type")),
2021                Kind::ENUM_MEMBER => grammar
2022                    .highlight_id_for_name("variant")
2023                    .or_else(|| grammar.highlight_id_for_name("property")),
2024                Kind::FIELD => grammar.highlight_id_for_name("property"),
2025                Kind::FUNCTION => grammar.highlight_id_for_name("function"),
2026                Kind::INTERFACE => grammar.highlight_id_for_name("type"),
2027                Kind::METHOD => grammar
2028                    .highlight_id_for_name("function.method")
2029                    .or_else(|| grammar.highlight_id_for_name("function")),
2030                Kind::OPERATOR => grammar.highlight_id_for_name("operator"),
2031                Kind::PROPERTY => grammar.highlight_id_for_name("property"),
2032                Kind::STRUCT => grammar.highlight_id_for_name("type"),
2033                Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
2034                Kind::KEYWORD => grammar.highlight_id_for_name("keyword"),
2035                _ => None,
2036            }
2037        });
2038
2039        let label = &item.label;
2040        let label_length = label.len();
2041        let runs = highlight_id
2042            .map(|highlight_id| vec![(0..label_length, highlight_id)])
2043            .unwrap_or_default();
2044        let text = if let Some(detail) = item.detail.as_deref().filter(|detail| detail != label) {
2045            format!("{label} {detail}")
2046        } else if let Some(description) = item
2047            .label_details
2048            .as_ref()
2049            .and_then(|label_details| label_details.description.as_deref())
2050            .filter(|description| description != label)
2051        {
2052            format!("{label} {description}")
2053        } else {
2054            label.clone()
2055        };
2056        let filter_range = item
2057            .filter_text
2058            .as_deref()
2059            .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
2060            .unwrap_or(0..label_length);
2061        Self {
2062            text,
2063            runs,
2064            filter_range,
2065        }
2066    }
2067
2068    pub fn plain(text: String, filter_text: Option<&str>) -> Self {
2069        let filter_range = filter_text
2070            .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
2071            .unwrap_or(0..text.len());
2072        Self {
2073            runs: Vec::new(),
2074            filter_range,
2075            text,
2076        }
2077    }
2078
2079    pub fn push_str(&mut self, text: &str, highlight: Option<HighlightId>) {
2080        let start_ix = self.text.len();
2081        self.text.push_str(text);
2082        let end_ix = self.text.len();
2083        if let Some(highlight) = highlight {
2084            self.runs.push((start_ix..end_ix, highlight));
2085        }
2086    }
2087
2088    pub fn text(&self) -> &str {
2089        self.text.as_str()
2090    }
2091
2092    pub fn filter_text(&self) -> &str {
2093        &self.text[self.filter_range.clone()]
2094    }
2095}
2096
2097impl From<String> for CodeLabel {
2098    fn from(value: String) -> Self {
2099        Self::plain(value, None)
2100    }
2101}
2102
2103impl From<&str> for CodeLabel {
2104    fn from(value: &str) -> Self {
2105        Self::plain(value.to_string(), None)
2106    }
2107}
2108
2109impl Ord for LanguageMatcher {
2110    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
2111        self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
2112            self.first_line_pattern
2113                .as_ref()
2114                .map(Regex::as_str)
2115                .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
2116        })
2117    }
2118}
2119
2120impl PartialOrd for LanguageMatcher {
2121    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2122        Some(self.cmp(other))
2123    }
2124}
2125
2126impl Eq for LanguageMatcher {}
2127
2128impl PartialEq for LanguageMatcher {
2129    fn eq(&self, other: &Self) -> bool {
2130        self.path_suffixes == other.path_suffixes
2131            && self.first_line_pattern.as_ref().map(Regex::as_str)
2132                == other.first_line_pattern.as_ref().map(Regex::as_str)
2133    }
2134}
2135
2136#[cfg(any(test, feature = "test-support"))]
2137impl Default for FakeLspAdapter {
2138    fn default() -> Self {
2139        Self {
2140            name: "the-fake-language-server",
2141            capabilities: lsp::LanguageServer::full_capabilities(),
2142            initializer: None,
2143            disk_based_diagnostics_progress_token: None,
2144            initialization_options: None,
2145            disk_based_diagnostics_sources: Vec::new(),
2146            prettier_plugins: Vec::new(),
2147            language_server_binary: LanguageServerBinary {
2148                path: "/the/fake/lsp/path".into(),
2149                arguments: vec![],
2150                env: Default::default(),
2151            },
2152            label_for_completion: None,
2153        }
2154    }
2155}
2156
2157#[cfg(any(test, feature = "test-support"))]
2158#[async_trait(?Send)]
2159impl LspAdapter for FakeLspAdapter {
2160    fn name(&self) -> LanguageServerName {
2161        LanguageServerName(self.name.into())
2162    }
2163
2164    async fn check_if_user_installed(
2165        &self,
2166        _: &dyn LspAdapterDelegate,
2167        _: Arc<dyn LanguageToolchainStore>,
2168        _: &AsyncApp,
2169    ) -> Option<LanguageServerBinary> {
2170        Some(self.language_server_binary.clone())
2171    }
2172
2173    fn get_language_server_command<'a>(
2174        self: Arc<Self>,
2175        _: Arc<dyn LspAdapterDelegate>,
2176        _: Arc<dyn LanguageToolchainStore>,
2177        _: LanguageServerBinaryOptions,
2178        _: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
2179        _: &'a mut AsyncApp,
2180    ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
2181        async move { Ok(self.language_server_binary.clone()) }.boxed_local()
2182    }
2183
2184    async fn fetch_latest_server_version(
2185        &self,
2186        _: &dyn LspAdapterDelegate,
2187    ) -> Result<Box<dyn 'static + Send + Any>> {
2188        unreachable!();
2189    }
2190
2191    async fn fetch_server_binary(
2192        &self,
2193        _: Box<dyn 'static + Send + Any>,
2194        _: PathBuf,
2195        _: &dyn LspAdapterDelegate,
2196    ) -> Result<LanguageServerBinary> {
2197        unreachable!();
2198    }
2199
2200    async fn cached_server_binary(
2201        &self,
2202        _: PathBuf,
2203        _: &dyn LspAdapterDelegate,
2204    ) -> Option<LanguageServerBinary> {
2205        unreachable!();
2206    }
2207
2208    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
2209        self.disk_based_diagnostics_sources.clone()
2210    }
2211
2212    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
2213        self.disk_based_diagnostics_progress_token.clone()
2214    }
2215
2216    async fn initialization_options(
2217        self: Arc<Self>,
2218        _: &dyn Fs,
2219        _: &Arc<dyn LspAdapterDelegate>,
2220    ) -> Result<Option<Value>> {
2221        Ok(self.initialization_options.clone())
2222    }
2223
2224    async fn label_for_completion(
2225        &self,
2226        item: &lsp::CompletionItem,
2227        language: &Arc<Language>,
2228    ) -> Option<CodeLabel> {
2229        let label_for_completion = self.label_for_completion.as_ref()?;
2230        label_for_completion(item, language)
2231    }
2232}
2233
2234fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
2235    for (ix, name) in query.capture_names().iter().enumerate() {
2236        for (capture_name, index) in captures.iter_mut() {
2237            if capture_name == name {
2238                **index = Some(ix as u32);
2239                break;
2240            }
2241        }
2242    }
2243}
2244
2245pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
2246    lsp::Position::new(point.row, point.column)
2247}
2248
2249pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
2250    Unclipped(PointUtf16::new(point.line, point.character))
2251}
2252
2253pub fn range_to_lsp(range: Range<PointUtf16>) -> Result<lsp::Range> {
2254    anyhow::ensure!(
2255        range.start <= range.end,
2256        "Inverted range provided to an LSP request: {:?}-{:?}",
2257        range.start,
2258        range.end
2259    );
2260    Ok(lsp::Range {
2261        start: point_to_lsp(range.start),
2262        end: point_to_lsp(range.end),
2263    })
2264}
2265
2266pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
2267    let mut start = point_from_lsp(range.start);
2268    let mut end = point_from_lsp(range.end);
2269    if start > end {
2270        log::warn!("range_from_lsp called with inverted range {start:?}-{end:?}");
2271        mem::swap(&mut start, &mut end);
2272    }
2273    start..end
2274}
2275
2276#[cfg(test)]
2277mod tests {
2278    use super::*;
2279    use gpui::TestAppContext;
2280
2281    #[gpui::test(iterations = 10)]
2282    async fn test_language_loading(cx: &mut TestAppContext) {
2283        let languages = LanguageRegistry::test(cx.executor());
2284        let languages = Arc::new(languages);
2285        languages.register_native_grammars([
2286            ("json", tree_sitter_json::LANGUAGE),
2287            ("rust", tree_sitter_rust::LANGUAGE),
2288        ]);
2289        languages.register_test_language(LanguageConfig {
2290            name: "JSON".into(),
2291            grammar: Some("json".into()),
2292            matcher: LanguageMatcher {
2293                path_suffixes: vec!["json".into()],
2294                ..Default::default()
2295            },
2296            ..Default::default()
2297        });
2298        languages.register_test_language(LanguageConfig {
2299            name: "Rust".into(),
2300            grammar: Some("rust".into()),
2301            matcher: LanguageMatcher {
2302                path_suffixes: vec!["rs".into()],
2303                ..Default::default()
2304            },
2305            ..Default::default()
2306        });
2307        assert_eq!(
2308            languages.language_names(),
2309            &[
2310                "JSON".to_string(),
2311                "Plain Text".to_string(),
2312                "Rust".to_string(),
2313            ]
2314        );
2315
2316        let rust1 = languages.language_for_name("Rust");
2317        let rust2 = languages.language_for_name("Rust");
2318
2319        // Ensure language is still listed even if it's being loaded.
2320        assert_eq!(
2321            languages.language_names(),
2322            &[
2323                "JSON".to_string(),
2324                "Plain Text".to_string(),
2325                "Rust".to_string(),
2326            ]
2327        );
2328
2329        let (rust1, rust2) = futures::join!(rust1, rust2);
2330        assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
2331
2332        // Ensure language is still listed even after loading it.
2333        assert_eq!(
2334            languages.language_names(),
2335            &[
2336                "JSON".to_string(),
2337                "Plain Text".to_string(),
2338                "Rust".to_string(),
2339            ]
2340        );
2341
2342        // Loading an unknown language returns an error.
2343        assert!(languages.language_for_name("Unknown").await.is_err());
2344    }
2345
2346    #[gpui::test]
2347    async fn test_completion_label_omits_duplicate_data() {
2348        let regular_completion_item_1 = lsp::CompletionItem {
2349            label: "regular1".to_string(),
2350            detail: Some("detail1".to_string()),
2351            label_details: Some(lsp::CompletionItemLabelDetails {
2352                detail: None,
2353                description: Some("description 1".to_string()),
2354            }),
2355            ..lsp::CompletionItem::default()
2356        };
2357
2358        let regular_completion_item_2 = lsp::CompletionItem {
2359            label: "regular2".to_string(),
2360            label_details: Some(lsp::CompletionItemLabelDetails {
2361                detail: None,
2362                description: Some("description 2".to_string()),
2363            }),
2364            ..lsp::CompletionItem::default()
2365        };
2366
2367        let completion_item_with_duplicate_detail_and_proper_description = lsp::CompletionItem {
2368            detail: Some(regular_completion_item_1.label.clone()),
2369            ..regular_completion_item_1.clone()
2370        };
2371
2372        let completion_item_with_duplicate_detail = lsp::CompletionItem {
2373            detail: Some(regular_completion_item_1.label.clone()),
2374            label_details: None,
2375            ..regular_completion_item_1.clone()
2376        };
2377
2378        let completion_item_with_duplicate_description = lsp::CompletionItem {
2379            label_details: Some(lsp::CompletionItemLabelDetails {
2380                detail: None,
2381                description: Some(regular_completion_item_2.label.clone()),
2382            }),
2383            ..regular_completion_item_2.clone()
2384        };
2385
2386        assert_eq!(
2387            CodeLabel::fallback_for_completion(&regular_completion_item_1, None).text,
2388            format!(
2389                "{} {}",
2390                regular_completion_item_1.label,
2391                regular_completion_item_1.detail.unwrap()
2392            ),
2393            "LSP completion items with both detail and label_details.description should prefer detail"
2394        );
2395        assert_eq!(
2396            CodeLabel::fallback_for_completion(&regular_completion_item_2, None).text,
2397            format!(
2398                "{} {}",
2399                regular_completion_item_2.label,
2400                regular_completion_item_2
2401                    .label_details
2402                    .as_ref()
2403                    .unwrap()
2404                    .description
2405                    .as_ref()
2406                    .unwrap()
2407            ),
2408            "LSP completion items without detail but with label_details.description should use that"
2409        );
2410        assert_eq!(
2411            CodeLabel::fallback_for_completion(
2412                &completion_item_with_duplicate_detail_and_proper_description,
2413                None
2414            )
2415            .text,
2416            format!(
2417                "{} {}",
2418                regular_completion_item_1.label,
2419                regular_completion_item_1
2420                    .label_details
2421                    .as_ref()
2422                    .unwrap()
2423                    .description
2424                    .as_ref()
2425                    .unwrap()
2426            ),
2427            "LSP completion items with both detail and label_details.description should prefer description only if the detail duplicates the completion label"
2428        );
2429        assert_eq!(
2430            CodeLabel::fallback_for_completion(&completion_item_with_duplicate_detail, None).text,
2431            regular_completion_item_1.label,
2432            "LSP completion items with duplicate label and detail, should omit the detail"
2433        );
2434        assert_eq!(
2435            CodeLabel::fallback_for_completion(&completion_item_with_duplicate_description, None)
2436                .text,
2437            regular_completion_item_2.label,
2438            "LSP completion items with duplicate label and detail, should omit the detail"
2439        );
2440    }
2441}