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 outline;
  15pub mod proto;
  16mod syntax_map;
  17mod task_context;
  18
  19#[cfg(test)]
  20mod buffer_tests;
  21pub mod markdown;
  22
  23use anyhow::{anyhow, Context, Result};
  24use async_trait::async_trait;
  25use collections::{HashMap, HashSet};
  26use futures::Future;
  27use gpui::{AppContext, AsyncAppContext, Model, Task};
  28pub use highlight_map::HighlightMap;
  29use lazy_static::lazy_static;
  30use lsp::{CodeActionKind, LanguageServerBinary};
  31use parking_lot::Mutex;
  32use regex::Regex;
  33use schemars::{
  34    gen::SchemaGenerator,
  35    schema::{InstanceType, Schema, SchemaObject},
  36    JsonSchema,
  37};
  38use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
  39use serde_json::Value;
  40use smol::future::FutureExt as _;
  41use std::{
  42    any::Any,
  43    cell::RefCell,
  44    ffi::OsStr,
  45    fmt::Debug,
  46    hash::Hash,
  47    mem,
  48    ops::Range,
  49    path::{Path, PathBuf},
  50    pin::Pin,
  51    str,
  52    sync::{
  53        atomic::{AtomicU64, AtomicUsize, Ordering::SeqCst},
  54        Arc,
  55    },
  56};
  57use syntax_map::SyntaxSnapshot;
  58pub use task_context::{
  59    ContextProvider, ContextProviderWithTasks, LanguageSource, SymbolContextProvider,
  60};
  61use theme::SyntaxTheme;
  62use tree_sitter::{self, wasmtime, Query, WasmStore};
  63use util::http::HttpClient;
  64
  65pub use buffer::Operation;
  66pub use buffer::*;
  67pub use diagnostic_set::DiagnosticEntry;
  68pub use language_registry::{
  69    LanguageNotFound, LanguageQueries, LanguageRegistry, LanguageServerBinaryStatus,
  70    PendingLanguageServer, QUERY_FILENAME_PREFIXES,
  71};
  72pub use lsp::LanguageServerId;
  73pub use outline::{Outline, OutlineItem};
  74pub use syntax_map::{OwnedSyntaxLayer, SyntaxLayer};
  75pub use text::LineEnding;
  76pub use tree_sitter::{Parser, Tree};
  77
  78/// Initializes the `language` crate.
  79///
  80/// This should be called before making use of items from the create.
  81pub fn init(cx: &mut AppContext) {
  82    language_settings::init(cx);
  83}
  84
  85thread_local! {
  86    static PARSER: RefCell<Parser> = {
  87        let mut parser = Parser::new();
  88        parser.set_wasm_store(WasmStore::new(WASM_ENGINE.clone()).unwrap()).unwrap();
  89        RefCell::new(parser)
  90    };
  91}
  92
  93lazy_static! {
  94    static ref NEXT_LANGUAGE_ID: AtomicUsize = Default::default();
  95    static ref NEXT_GRAMMAR_ID: AtomicUsize = Default::default();
  96    static ref WASM_ENGINE: wasmtime::Engine = {
  97        wasmtime::Engine::new(&wasmtime::Config::new()).unwrap()
  98    };
  99
 100    /// A shared grammar for plain text, exposed for reuse by downstream crates.
 101    pub static ref PLAIN_TEXT: Arc<Language> = Arc::new(Language::new(
 102        LanguageConfig {
 103            name: "Plain Text".into(),
 104            ..Default::default()
 105        },
 106        None,
 107    ));
 108}
 109
 110/// Types that represent a position in a buffer, and can be converted into
 111/// an LSP position, to send to a language server.
 112pub trait ToLspPosition {
 113    /// Converts the value into an LSP position.
 114    fn to_lsp_position(self) -> lsp::Position;
 115}
 116
 117/// A name of a language server.
 118#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
 119pub struct LanguageServerName(pub Arc<str>);
 120
 121#[derive(Debug, Clone, PartialEq, Eq, Hash)]
 122pub struct Location {
 123    pub buffer: Model<Buffer>,
 124    pub range: Range<Anchor>,
 125}
 126
 127/// Represents a Language Server, with certain cached sync properties.
 128/// Uses [`LspAdapter`] under the hood, but calls all 'static' methods
 129/// once at startup, and caches the results.
 130pub struct CachedLspAdapter {
 131    pub name: LanguageServerName,
 132    pub disk_based_diagnostic_sources: Vec<String>,
 133    pub disk_based_diagnostics_progress_token: Option<String>,
 134    pub language_ids: HashMap<String, String>,
 135    pub adapter: Arc<dyn LspAdapter>,
 136    pub reinstall_attempt_count: AtomicU64,
 137    /// Indicates whether this language server is the primary language server
 138    /// for a given language. Currently, most LSP-backed features only work
 139    /// with one language server, so one server needs to be primary.
 140    pub is_primary: bool,
 141    cached_binary: futures::lock::Mutex<Option<LanguageServerBinary>>,
 142}
 143
 144impl CachedLspAdapter {
 145    pub fn new(adapter: Arc<dyn LspAdapter>, is_primary: bool) -> Arc<Self> {
 146        let name = adapter.name();
 147        let disk_based_diagnostic_sources = adapter.disk_based_diagnostic_sources();
 148        let disk_based_diagnostics_progress_token = adapter.disk_based_diagnostics_progress_token();
 149        let language_ids = adapter.language_ids();
 150
 151        Arc::new(CachedLspAdapter {
 152            name,
 153            disk_based_diagnostic_sources,
 154            disk_based_diagnostics_progress_token,
 155            language_ids,
 156            adapter,
 157            is_primary,
 158            cached_binary: Default::default(),
 159            reinstall_attempt_count: AtomicU64::new(0),
 160        })
 161    }
 162
 163    pub async fn get_language_server_command(
 164        self: Arc<Self>,
 165        language: Arc<Language>,
 166        container_dir: Arc<Path>,
 167        delegate: Arc<dyn LspAdapterDelegate>,
 168        cx: &mut AsyncAppContext,
 169    ) -> Result<LanguageServerBinary> {
 170        let cached_binary = self.cached_binary.lock().await;
 171        self.adapter
 172            .clone()
 173            .get_language_server_command(language, container_dir, delegate, cached_binary, cx)
 174            .await
 175    }
 176
 177    pub fn will_start_server(
 178        &self,
 179        delegate: &Arc<dyn LspAdapterDelegate>,
 180        cx: &mut AsyncAppContext,
 181    ) -> Option<Task<Result<()>>> {
 182        self.adapter.will_start_server(delegate, cx)
 183    }
 184
 185    pub fn can_be_reinstalled(&self) -> bool {
 186        self.adapter.can_be_reinstalled()
 187    }
 188
 189    pub async fn installation_test_binary(
 190        &self,
 191        container_dir: PathBuf,
 192    ) -> Option<LanguageServerBinary> {
 193        self.adapter.installation_test_binary(container_dir).await
 194    }
 195
 196    pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
 197        self.adapter.code_action_kinds()
 198    }
 199
 200    pub fn workspace_configuration(&self, workspace_root: &Path, cx: &mut AppContext) -> Value {
 201        self.adapter.workspace_configuration(workspace_root, cx)
 202    }
 203
 204    pub fn process_diagnostics(&self, params: &mut lsp::PublishDiagnosticsParams) {
 205        self.adapter.process_diagnostics(params)
 206    }
 207
 208    pub async fn process_completions(&self, completion_items: &mut [lsp::CompletionItem]) {
 209        self.adapter.process_completions(completion_items).await
 210    }
 211
 212    pub async fn labels_for_completions(
 213        &self,
 214        completion_items: &[lsp::CompletionItem],
 215        language: &Arc<Language>,
 216    ) -> Result<Vec<Option<CodeLabel>>> {
 217        self.adapter
 218            .clone()
 219            .labels_for_completions(completion_items, language)
 220            .await
 221    }
 222
 223    pub async fn labels_for_symbols(
 224        &self,
 225        symbols: &[(String, lsp::SymbolKind)],
 226        language: &Arc<Language>,
 227    ) -> Result<Vec<Option<CodeLabel>>> {
 228        self.adapter
 229            .clone()
 230            .labels_for_symbols(symbols, language)
 231            .await
 232    }
 233
 234    #[cfg(any(test, feature = "test-support"))]
 235    fn as_fake(&self) -> Option<&FakeLspAdapter> {
 236        self.adapter.as_fake()
 237    }
 238}
 239
 240/// [`LspAdapterDelegate`] allows [`LspAdapter]` implementations to interface with the application
 241// e.g. to display a notification or fetch data from the web.
 242#[async_trait]
 243pub trait LspAdapterDelegate: Send + Sync {
 244    fn show_notification(&self, message: &str, cx: &mut AppContext);
 245    fn http_client(&self) -> Arc<dyn HttpClient>;
 246    fn update_status(&self, language: LanguageServerName, status: LanguageServerBinaryStatus);
 247
 248    async fn which(&self, command: &OsStr) -> Option<PathBuf>;
 249    async fn shell_env(&self) -> HashMap<String, String>;
 250    async fn read_text_file(&self, path: PathBuf) -> Result<String>;
 251}
 252
 253#[async_trait(?Send)]
 254pub trait LspAdapter: 'static + Send + Sync {
 255    fn name(&self) -> LanguageServerName;
 256
 257    fn get_language_server_command<'a>(
 258        self: Arc<Self>,
 259        language: Arc<Language>,
 260        container_dir: Arc<Path>,
 261        delegate: Arc<dyn LspAdapterDelegate>,
 262        mut cached_binary: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
 263        cx: &'a mut AsyncAppContext,
 264    ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
 265        async move {
 266            // First we check whether the adapter can give us a user-installed binary.
 267            // If so, we do *not* want to cache that, because each worktree might give us a different
 268            // binary:
 269            //
 270            //      worktree 1: user-installed at `.bin/gopls`
 271            //      worktree 2: user-installed at `~/bin/gopls`
 272            //      worktree 3: no gopls found in PATH -> fallback to Zed installation
 273            //
 274            // We only want to cache when we fall back to the global one,
 275            // because we don't want to download and overwrite our global one
 276            // for each worktree we might have open.
 277            if let Some(binary) = self.check_if_user_installed(delegate.as_ref(), cx).await {
 278                log::info!(
 279                    "found user-installed language server for {}. path: {:?}, arguments: {:?}",
 280                    language.name(),
 281                    binary.path,
 282                    binary.arguments
 283                );
 284                return Ok(binary);
 285            }
 286
 287            if let Some(cached_binary) = cached_binary.as_ref() {
 288                return Ok(cached_binary.clone());
 289            }
 290
 291            if !container_dir.exists() {
 292                smol::fs::create_dir_all(&container_dir)
 293                    .await
 294                    .context("failed to create container directory")?;
 295            }
 296
 297            let mut binary = try_fetch_server_binary(self.as_ref(), &delegate, container_dir.to_path_buf(), cx).await;
 298
 299            if let Err(error) = binary.as_ref() {
 300                if let Some(prev_downloaded_binary) = self
 301                    .cached_server_binary(container_dir.to_path_buf(), delegate.as_ref())
 302                    .await
 303                {
 304                    log::info!(
 305                        "failed to fetch newest version of language server {:?}. falling back to using {:?}",
 306                        self.name(),
 307                        prev_downloaded_binary.path
 308                    );
 309                    binary = Ok(prev_downloaded_binary);
 310                } else {
 311                    delegate.update_status(
 312                        self.name(),
 313                        LanguageServerBinaryStatus::Failed {
 314                            error: format!("{error:?}"),
 315                        },
 316                    );
 317                }
 318            }
 319
 320            if let Ok(binary) = &binary {
 321                *cached_binary = Some(binary.clone());
 322            }
 323
 324            binary
 325        }
 326        .boxed_local()
 327    }
 328
 329    async fn check_if_user_installed(
 330        &self,
 331        _: &dyn LspAdapterDelegate,
 332        _: &AsyncAppContext,
 333    ) -> Option<LanguageServerBinary> {
 334        None
 335    }
 336
 337    async fn fetch_latest_server_version(
 338        &self,
 339        delegate: &dyn LspAdapterDelegate,
 340    ) -> Result<Box<dyn 'static + Send + Any>>;
 341
 342    fn will_fetch_server(
 343        &self,
 344        _: &Arc<dyn LspAdapterDelegate>,
 345        _: &mut AsyncAppContext,
 346    ) -> Option<Task<Result<()>>> {
 347        None
 348    }
 349
 350    fn will_start_server(
 351        &self,
 352        _: &Arc<dyn LspAdapterDelegate>,
 353        _: &mut AsyncAppContext,
 354    ) -> Option<Task<Result<()>>> {
 355        None
 356    }
 357
 358    async fn fetch_server_binary(
 359        &self,
 360        latest_version: Box<dyn 'static + Send + Any>,
 361        container_dir: PathBuf,
 362        delegate: &dyn LspAdapterDelegate,
 363    ) -> Result<LanguageServerBinary>;
 364
 365    async fn cached_server_binary(
 366        &self,
 367        container_dir: PathBuf,
 368        delegate: &dyn LspAdapterDelegate,
 369    ) -> Option<LanguageServerBinary>;
 370
 371    /// Returns `true` if a language server can be reinstalled.
 372    ///
 373    /// If language server initialization fails, a reinstallation will be attempted unless the value returned from this method is `false`.
 374    ///
 375    /// Implementations that rely on software already installed on user's system
 376    /// should have [`can_be_reinstalled`](Self::can_be_reinstalled) return `false`.
 377    fn can_be_reinstalled(&self) -> bool {
 378        true
 379    }
 380
 381    async fn installation_test_binary(
 382        &self,
 383        container_dir: PathBuf,
 384    ) -> Option<LanguageServerBinary>;
 385
 386    fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
 387
 388    /// Post-processes completions provided by the language server.
 389    async fn process_completions(&self, _: &mut [lsp::CompletionItem]) {}
 390
 391    async fn labels_for_completions(
 392        self: Arc<Self>,
 393        completions: &[lsp::CompletionItem],
 394        language: &Arc<Language>,
 395    ) -> Result<Vec<Option<CodeLabel>>> {
 396        let mut labels = Vec::new();
 397        for (ix, completion) in completions.into_iter().enumerate() {
 398            let label = self.label_for_completion(completion, language).await;
 399            if let Some(label) = label {
 400                labels.resize(ix + 1, None);
 401                *labels.last_mut().unwrap() = Some(label);
 402            }
 403        }
 404        Ok(labels)
 405    }
 406
 407    async fn label_for_completion(
 408        &self,
 409        _: &lsp::CompletionItem,
 410        _: &Arc<Language>,
 411    ) -> Option<CodeLabel> {
 412        None
 413    }
 414
 415    async fn labels_for_symbols(
 416        self: Arc<Self>,
 417        symbols: &[(String, lsp::SymbolKind)],
 418        language: &Arc<Language>,
 419    ) -> Result<Vec<Option<CodeLabel>>> {
 420        let mut labels = Vec::new();
 421        for (ix, (name, kind)) in symbols.into_iter().enumerate() {
 422            let label = self.label_for_symbol(name, *kind, language).await;
 423            if let Some(label) = label {
 424                labels.resize(ix + 1, None);
 425                *labels.last_mut().unwrap() = Some(label);
 426            }
 427        }
 428        Ok(labels)
 429    }
 430
 431    async fn label_for_symbol(
 432        &self,
 433        _: &str,
 434        _: lsp::SymbolKind,
 435        _: &Arc<Language>,
 436    ) -> Option<CodeLabel> {
 437        None
 438    }
 439
 440    /// Returns initialization options that are going to be sent to a LSP server as a part of [`lsp::InitializeParams`]
 441    async fn initialization_options(
 442        self: Arc<Self>,
 443        _: &Arc<dyn LspAdapterDelegate>,
 444    ) -> Result<Option<Value>> {
 445        Ok(None)
 446    }
 447
 448    fn workspace_configuration(&self, _workspace_root: &Path, _cx: &mut AppContext) -> Value {
 449        serde_json::json!({})
 450    }
 451
 452    /// Returns a list of code actions supported by a given LspAdapter
 453    fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
 454        Some(vec![
 455            CodeActionKind::EMPTY,
 456            CodeActionKind::QUICKFIX,
 457            CodeActionKind::REFACTOR,
 458            CodeActionKind::REFACTOR_EXTRACT,
 459            CodeActionKind::SOURCE,
 460        ])
 461    }
 462
 463    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
 464        Default::default()
 465    }
 466
 467    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
 468        None
 469    }
 470
 471    fn language_ids(&self) -> HashMap<String, String> {
 472        Default::default()
 473    }
 474
 475    #[cfg(any(test, feature = "test-support"))]
 476    fn as_fake(&self) -> Option<&FakeLspAdapter> {
 477        None
 478    }
 479}
 480
 481async fn try_fetch_server_binary<L: LspAdapter + 'static + Send + Sync + ?Sized>(
 482    adapter: &L,
 483    delegate: &Arc<dyn LspAdapterDelegate>,
 484    container_dir: PathBuf,
 485    cx: &mut AsyncAppContext,
 486) -> Result<LanguageServerBinary> {
 487    if let Some(task) = adapter.will_fetch_server(delegate, cx) {
 488        task.await?;
 489    }
 490
 491    let name = adapter.name();
 492    log::info!("fetching latest version of language server {:?}", name.0);
 493    delegate.update_status(name.clone(), LanguageServerBinaryStatus::CheckingForUpdate);
 494    let latest_version = adapter
 495        .fetch_latest_server_version(delegate.as_ref())
 496        .await?;
 497
 498    log::info!("downloading language server {:?}", name.0);
 499    delegate.update_status(adapter.name(), LanguageServerBinaryStatus::Downloading);
 500    let binary = adapter
 501        .fetch_server_binary(latest_version, container_dir, delegate.as_ref())
 502        .await;
 503
 504    delegate.update_status(name.clone(), LanguageServerBinaryStatus::None);
 505    binary
 506}
 507
 508#[derive(Clone, Debug, PartialEq, Eq)]
 509pub struct CodeLabel {
 510    /// The text to display.
 511    pub text: String,
 512    /// Syntax highlighting runs.
 513    pub runs: Vec<(Range<usize>, HighlightId)>,
 514    /// The portion of the text that should be used in fuzzy filtering.
 515    pub filter_range: Range<usize>,
 516}
 517
 518#[derive(Clone, Deserialize, JsonSchema)]
 519pub struct LanguageConfig {
 520    /// Human-readable name of the language.
 521    pub name: Arc<str>,
 522    /// The name of this language for a Markdown code fence block
 523    pub code_fence_block_name: Option<Arc<str>>,
 524    // The name of the grammar in a WASM bundle (experimental).
 525    pub grammar: Option<Arc<str>>,
 526    /// The criteria for matching this language to a given file.
 527    #[serde(flatten)]
 528    pub matcher: LanguageMatcher,
 529    /// List of bracket types in a language.
 530    #[serde(default)]
 531    #[schemars(schema_with = "bracket_pair_config_json_schema")]
 532    pub brackets: BracketPairConfig,
 533    /// If set to true, auto indentation uses last non empty line to determine
 534    /// the indentation level for a new line.
 535    #[serde(default = "auto_indent_using_last_non_empty_line_default")]
 536    pub auto_indent_using_last_non_empty_line: bool,
 537    /// A regex that is used to determine whether the indentation level should be
 538    /// increased in the following line.
 539    #[serde(default, deserialize_with = "deserialize_regex")]
 540    #[schemars(schema_with = "regex_json_schema")]
 541    pub increase_indent_pattern: Option<Regex>,
 542    /// A regex that is used to determine whether the indentation level should be
 543    /// decreased in the following line.
 544    #[serde(default, deserialize_with = "deserialize_regex")]
 545    #[schemars(schema_with = "regex_json_schema")]
 546    pub decrease_indent_pattern: Option<Regex>,
 547    /// A list of characters that trigger the automatic insertion of a closing
 548    /// bracket when they immediately precede the point where an opening
 549    /// bracket is inserted.
 550    #[serde(default)]
 551    pub autoclose_before: String,
 552    /// A placeholder used internally by Semantic Index.
 553    #[serde(default)]
 554    pub collapsed_placeholder: String,
 555    /// A line comment string that is inserted in e.g. `toggle comments` action.
 556    /// A language can have multiple flavours of line comments. All of the provided line comments are
 557    /// used for comment continuations on the next line, but only the first one is used for Editor::ToggleComments.
 558    #[serde(default)]
 559    pub line_comments: Vec<Arc<str>>,
 560    /// Starting and closing characters of a block comment.
 561    #[serde(default)]
 562    pub block_comment: Option<(Arc<str>, Arc<str>)>,
 563    /// A list of language servers that are allowed to run on subranges of a given language.
 564    #[serde(default)]
 565    pub scope_opt_in_language_servers: Vec<String>,
 566    #[serde(default)]
 567    pub overrides: HashMap<String, LanguageConfigOverride>,
 568    /// A list of characters that Zed should treat as word characters for the
 569    /// purpose of features that operate on word boundaries, like 'move to next word end'
 570    /// or a whole-word search in buffer search.
 571    #[serde(default)]
 572    pub word_characters: HashSet<char>,
 573    /// The name of a Prettier parser that should be used for this language.
 574    #[serde(default)]
 575    pub prettier_parser_name: Option<String>,
 576    /// The names of any Prettier plugins that should be used for this language.
 577    #[serde(default)]
 578    pub prettier_plugins: Vec<Arc<str>>,
 579}
 580
 581#[derive(Clone, Debug, Serialize, Deserialize, Default, JsonSchema)]
 582pub struct LanguageMatcher {
 583    /// 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`.
 584    #[serde(default)]
 585    pub path_suffixes: Vec<String>,
 586    /// A regex pattern that determines whether the language should be assigned to a file or not.
 587    #[serde(
 588        default,
 589        serialize_with = "serialize_regex",
 590        deserialize_with = "deserialize_regex"
 591    )]
 592    #[schemars(schema_with = "regex_json_schema")]
 593    pub first_line_pattern: Option<Regex>,
 594}
 595
 596/// Represents a language for the given range. Some languages (e.g. HTML)
 597/// interleave several languages together, thus a single buffer might actually contain
 598/// several nested scopes.
 599#[derive(Clone, Debug)]
 600pub struct LanguageScope {
 601    language: Arc<Language>,
 602    override_id: Option<u32>,
 603}
 604
 605#[derive(Clone, Deserialize, Default, Debug, JsonSchema)]
 606pub struct LanguageConfigOverride {
 607    #[serde(default)]
 608    pub line_comments: Override<Vec<Arc<str>>>,
 609    #[serde(default)]
 610    pub block_comment: Override<(Arc<str>, Arc<str>)>,
 611    #[serde(skip_deserializing)]
 612    #[schemars(skip)]
 613    pub disabled_bracket_ixs: Vec<u16>,
 614    #[serde(default)]
 615    pub word_characters: Override<HashSet<char>>,
 616    #[serde(default)]
 617    pub opt_into_language_servers: Vec<String>,
 618}
 619
 620#[derive(Clone, Deserialize, Debug, Serialize, JsonSchema)]
 621#[serde(untagged)]
 622pub enum Override<T> {
 623    Remove { remove: bool },
 624    Set(T),
 625}
 626
 627impl<T> Default for Override<T> {
 628    fn default() -> Self {
 629        Override::Remove { remove: false }
 630    }
 631}
 632
 633impl<T> Override<T> {
 634    fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
 635        match this {
 636            Some(Self::Set(value)) => Some(value),
 637            Some(Self::Remove { remove: true }) => None,
 638            Some(Self::Remove { remove: false }) | None => original,
 639        }
 640    }
 641}
 642
 643impl Default for LanguageConfig {
 644    fn default() -> Self {
 645        Self {
 646            name: "".into(),
 647            code_fence_block_name: None,
 648            grammar: None,
 649            matcher: LanguageMatcher::default(),
 650            brackets: Default::default(),
 651            auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
 652            increase_indent_pattern: Default::default(),
 653            decrease_indent_pattern: Default::default(),
 654            autoclose_before: Default::default(),
 655            line_comments: Default::default(),
 656            block_comment: Default::default(),
 657            scope_opt_in_language_servers: Default::default(),
 658            overrides: Default::default(),
 659            word_characters: Default::default(),
 660            prettier_parser_name: None,
 661            prettier_plugins: Default::default(),
 662            collapsed_placeholder: Default::default(),
 663        }
 664    }
 665}
 666
 667fn auto_indent_using_last_non_empty_line_default() -> bool {
 668    true
 669}
 670
 671fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
 672    let source = Option::<String>::deserialize(d)?;
 673    if let Some(source) = source {
 674        Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
 675    } else {
 676        Ok(None)
 677    }
 678}
 679
 680fn regex_json_schema(_: &mut SchemaGenerator) -> Schema {
 681    Schema::Object(SchemaObject {
 682        instance_type: Some(InstanceType::String.into()),
 683        ..Default::default()
 684    })
 685}
 686
 687fn serialize_regex<S>(regex: &Option<Regex>, serializer: S) -> Result<S::Ok, S::Error>
 688where
 689    S: Serializer,
 690{
 691    match regex {
 692        Some(regex) => serializer.serialize_str(regex.as_str()),
 693        None => serializer.serialize_none(),
 694    }
 695}
 696
 697#[doc(hidden)]
 698#[cfg(any(test, feature = "test-support"))]
 699pub struct FakeLspAdapter {
 700    pub name: &'static str,
 701    pub initialization_options: Option<Value>,
 702    pub capabilities: lsp::ServerCapabilities,
 703    pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
 704    pub disk_based_diagnostics_progress_token: Option<String>,
 705    pub disk_based_diagnostics_sources: Vec<String>,
 706    pub prettier_plugins: Vec<&'static str>,
 707    pub language_server_binary: LanguageServerBinary,
 708}
 709
 710/// Configuration of handling bracket pairs for a given language.
 711///
 712/// This struct includes settings for defining which pairs of characters are considered brackets and
 713/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
 714#[derive(Clone, Debug, Default, JsonSchema)]
 715pub struct BracketPairConfig {
 716    /// A list of character pairs that should be treated as brackets in the context of a given language.
 717    pub pairs: Vec<BracketPair>,
 718    /// A list of tree-sitter scopes for which a given bracket should not be active.
 719    /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
 720    #[schemars(skip)]
 721    pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
 722}
 723
 724fn bracket_pair_config_json_schema(gen: &mut SchemaGenerator) -> Schema {
 725    Option::<Vec<BracketPairContent>>::json_schema(gen)
 726}
 727
 728#[derive(Deserialize, JsonSchema)]
 729pub struct BracketPairContent {
 730    #[serde(flatten)]
 731    pub bracket_pair: BracketPair,
 732    #[serde(default)]
 733    pub not_in: Vec<String>,
 734}
 735
 736impl<'de> Deserialize<'de> for BracketPairConfig {
 737    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
 738    where
 739        D: Deserializer<'de>,
 740    {
 741        let result = Vec::<BracketPairContent>::deserialize(deserializer)?;
 742        let mut brackets = Vec::with_capacity(result.len());
 743        let mut disabled_scopes_by_bracket_ix = Vec::with_capacity(result.len());
 744        for entry in result {
 745            brackets.push(entry.bracket_pair);
 746            disabled_scopes_by_bracket_ix.push(entry.not_in);
 747        }
 748
 749        Ok(BracketPairConfig {
 750            pairs: brackets,
 751            disabled_scopes_by_bracket_ix,
 752        })
 753    }
 754}
 755
 756/// Describes a single bracket pair and how an editor should react to e.g. inserting
 757/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
 758#[derive(Clone, Debug, Default, Deserialize, PartialEq, JsonSchema)]
 759pub struct BracketPair {
 760    /// Starting substring for a bracket.
 761    pub start: String,
 762    /// Ending substring for a bracket.
 763    pub end: String,
 764    /// True if `end` should be automatically inserted right after `start` characters.
 765    pub close: bool,
 766    /// True if an extra newline should be inserted while the cursor is in the middle
 767    /// of that bracket pair.
 768    pub newline: bool,
 769}
 770
 771#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
 772pub(crate) struct LanguageId(usize);
 773
 774impl LanguageId {
 775    pub(crate) fn new() -> Self {
 776        Self(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst))
 777    }
 778}
 779
 780pub struct Language {
 781    pub(crate) id: LanguageId,
 782    pub(crate) config: LanguageConfig,
 783    pub(crate) grammar: Option<Arc<Grammar>>,
 784    pub(crate) context_provider: Option<Arc<dyn ContextProvider>>,
 785}
 786
 787#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
 788pub struct GrammarId(pub usize);
 789
 790impl GrammarId {
 791    pub(crate) fn new() -> Self {
 792        Self(NEXT_GRAMMAR_ID.fetch_add(1, SeqCst))
 793    }
 794}
 795
 796pub struct Grammar {
 797    id: GrammarId,
 798    pub ts_language: tree_sitter::Language,
 799    pub(crate) error_query: Query,
 800    pub(crate) highlights_query: Option<Query>,
 801    pub(crate) brackets_config: Option<BracketConfig>,
 802    pub(crate) redactions_config: Option<RedactionConfig>,
 803    pub(crate) indents_config: Option<IndentConfig>,
 804    pub outline_config: Option<OutlineConfig>,
 805    pub embedding_config: Option<EmbeddingConfig>,
 806    pub(crate) injection_config: Option<InjectionConfig>,
 807    pub(crate) override_config: Option<OverrideConfig>,
 808    pub(crate) highlight_map: Mutex<HighlightMap>,
 809}
 810
 811struct IndentConfig {
 812    query: Query,
 813    indent_capture_ix: u32,
 814    start_capture_ix: Option<u32>,
 815    end_capture_ix: Option<u32>,
 816    outdent_capture_ix: Option<u32>,
 817}
 818
 819pub struct OutlineConfig {
 820    pub query: Query,
 821    pub item_capture_ix: u32,
 822    pub name_capture_ix: u32,
 823    pub context_capture_ix: Option<u32>,
 824    pub extra_context_capture_ix: Option<u32>,
 825}
 826
 827#[derive(Debug)]
 828pub struct EmbeddingConfig {
 829    pub query: Query,
 830    pub item_capture_ix: u32,
 831    pub name_capture_ix: Option<u32>,
 832    pub context_capture_ix: Option<u32>,
 833    pub collapse_capture_ix: Option<u32>,
 834    pub keep_capture_ix: Option<u32>,
 835}
 836
 837struct InjectionConfig {
 838    query: Query,
 839    content_capture_ix: u32,
 840    language_capture_ix: Option<u32>,
 841    patterns: Vec<InjectionPatternConfig>,
 842}
 843
 844struct RedactionConfig {
 845    pub query: Query,
 846    pub redaction_capture_ix: u32,
 847}
 848
 849struct OverrideConfig {
 850    query: Query,
 851    values: HashMap<u32, (String, LanguageConfigOverride)>,
 852}
 853
 854#[derive(Default, Clone)]
 855struct InjectionPatternConfig {
 856    language: Option<Box<str>>,
 857    combined: bool,
 858}
 859
 860struct BracketConfig {
 861    query: Query,
 862    open_capture_ix: u32,
 863    close_capture_ix: u32,
 864}
 865
 866impl Language {
 867    pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
 868        Self::new_with_id(LanguageId::new(), config, ts_language)
 869    }
 870
 871    fn new_with_id(
 872        id: LanguageId,
 873        config: LanguageConfig,
 874        ts_language: Option<tree_sitter::Language>,
 875    ) -> Self {
 876        Self {
 877            id,
 878            config,
 879            grammar: ts_language.map(|ts_language| {
 880                Arc::new(Grammar {
 881                    id: GrammarId::new(),
 882                    highlights_query: None,
 883                    brackets_config: None,
 884                    outline_config: None,
 885                    embedding_config: None,
 886                    indents_config: None,
 887                    injection_config: None,
 888                    override_config: None,
 889                    redactions_config: None,
 890                    error_query: Query::new(&ts_language, "(ERROR) @error").unwrap(),
 891                    ts_language,
 892                    highlight_map: Default::default(),
 893                })
 894            }),
 895            context_provider: None,
 896        }
 897    }
 898
 899    pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
 900        self.context_provider = provider;
 901        self
 902    }
 903
 904    pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
 905        if let Some(query) = queries.highlights {
 906            self = self
 907                .with_highlights_query(query.as_ref())
 908                .context("Error loading highlights query")?;
 909        }
 910        if let Some(query) = queries.brackets {
 911            self = self
 912                .with_brackets_query(query.as_ref())
 913                .context("Error loading brackets query")?;
 914        }
 915        if let Some(query) = queries.indents {
 916            self = self
 917                .with_indents_query(query.as_ref())
 918                .context("Error loading indents query")?;
 919        }
 920        if let Some(query) = queries.outline {
 921            self = self
 922                .with_outline_query(query.as_ref())
 923                .context("Error loading outline query")?;
 924        }
 925        if let Some(query) = queries.embedding {
 926            self = self
 927                .with_embedding_query(query.as_ref())
 928                .context("Error loading embedding query")?;
 929        }
 930        if let Some(query) = queries.injections {
 931            self = self
 932                .with_injection_query(query.as_ref())
 933                .context("Error loading injection query")?;
 934        }
 935        if let Some(query) = queries.overrides {
 936            self = self
 937                .with_override_query(query.as_ref())
 938                .context("Error loading override query")?;
 939        }
 940        if let Some(query) = queries.redactions {
 941            self = self
 942                .with_redaction_query(query.as_ref())
 943                .context("Error loading redaction query")?;
 944        }
 945        Ok(self)
 946    }
 947
 948    pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
 949        let grammar = self
 950            .grammar_mut()
 951            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
 952        grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
 953        Ok(self)
 954    }
 955
 956    pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
 957        let grammar = self
 958            .grammar_mut()
 959            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
 960        let query = Query::new(&grammar.ts_language, source)?;
 961        let mut item_capture_ix = None;
 962        let mut name_capture_ix = None;
 963        let mut context_capture_ix = None;
 964        let mut extra_context_capture_ix = None;
 965        get_capture_indices(
 966            &query,
 967            &mut [
 968                ("item", &mut item_capture_ix),
 969                ("name", &mut name_capture_ix),
 970                ("context", &mut context_capture_ix),
 971                ("context.extra", &mut extra_context_capture_ix),
 972            ],
 973        );
 974        if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
 975            grammar.outline_config = Some(OutlineConfig {
 976                query,
 977                item_capture_ix,
 978                name_capture_ix,
 979                context_capture_ix,
 980                extra_context_capture_ix,
 981            });
 982        }
 983        Ok(self)
 984    }
 985
 986    pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
 987        let grammar = self
 988            .grammar_mut()
 989            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
 990        let query = Query::new(&grammar.ts_language, source)?;
 991        let mut item_capture_ix = None;
 992        let mut name_capture_ix = None;
 993        let mut context_capture_ix = None;
 994        let mut collapse_capture_ix = None;
 995        let mut keep_capture_ix = None;
 996        get_capture_indices(
 997            &query,
 998            &mut [
 999                ("item", &mut item_capture_ix),
1000                ("name", &mut name_capture_ix),
1001                ("context", &mut context_capture_ix),
1002                ("keep", &mut keep_capture_ix),
1003                ("collapse", &mut collapse_capture_ix),
1004            ],
1005        );
1006        if let Some(item_capture_ix) = item_capture_ix {
1007            grammar.embedding_config = Some(EmbeddingConfig {
1008                query,
1009                item_capture_ix,
1010                name_capture_ix,
1011                context_capture_ix,
1012                collapse_capture_ix,
1013                keep_capture_ix,
1014            });
1015        }
1016        Ok(self)
1017    }
1018
1019    pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1020        let grammar = self
1021            .grammar_mut()
1022            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1023        let query = Query::new(&grammar.ts_language, source)?;
1024        let mut open_capture_ix = None;
1025        let mut close_capture_ix = None;
1026        get_capture_indices(
1027            &query,
1028            &mut [
1029                ("open", &mut open_capture_ix),
1030                ("close", &mut close_capture_ix),
1031            ],
1032        );
1033        if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1034            grammar.brackets_config = Some(BracketConfig {
1035                query,
1036                open_capture_ix,
1037                close_capture_ix,
1038            });
1039        }
1040        Ok(self)
1041    }
1042
1043    pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1044        let grammar = self
1045            .grammar_mut()
1046            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1047        let query = Query::new(&grammar.ts_language, source)?;
1048        let mut indent_capture_ix = None;
1049        let mut start_capture_ix = None;
1050        let mut end_capture_ix = None;
1051        let mut outdent_capture_ix = None;
1052        get_capture_indices(
1053            &query,
1054            &mut [
1055                ("indent", &mut indent_capture_ix),
1056                ("start", &mut start_capture_ix),
1057                ("end", &mut end_capture_ix),
1058                ("outdent", &mut outdent_capture_ix),
1059            ],
1060        );
1061        if let Some(indent_capture_ix) = indent_capture_ix {
1062            grammar.indents_config = Some(IndentConfig {
1063                query,
1064                indent_capture_ix,
1065                start_capture_ix,
1066                end_capture_ix,
1067                outdent_capture_ix,
1068            });
1069        }
1070        Ok(self)
1071    }
1072
1073    pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1074        let grammar = self
1075            .grammar_mut()
1076            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1077        let query = Query::new(&grammar.ts_language, source)?;
1078        let mut language_capture_ix = None;
1079        let mut content_capture_ix = None;
1080        get_capture_indices(
1081            &query,
1082            &mut [
1083                ("language", &mut language_capture_ix),
1084                ("content", &mut content_capture_ix),
1085            ],
1086        );
1087        let patterns = (0..query.pattern_count())
1088            .map(|ix| {
1089                let mut config = InjectionPatternConfig::default();
1090                for setting in query.property_settings(ix) {
1091                    match setting.key.as_ref() {
1092                        "language" => {
1093                            config.language = setting.value.clone();
1094                        }
1095                        "combined" => {
1096                            config.combined = true;
1097                        }
1098                        _ => {}
1099                    }
1100                }
1101                config
1102            })
1103            .collect();
1104        if let Some(content_capture_ix) = content_capture_ix {
1105            grammar.injection_config = Some(InjectionConfig {
1106                query,
1107                language_capture_ix,
1108                content_capture_ix,
1109                patterns,
1110            });
1111        }
1112        Ok(self)
1113    }
1114
1115    pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1116        let query = {
1117            let grammar = self
1118                .grammar
1119                .as_ref()
1120                .ok_or_else(|| anyhow!("no grammar for language"))?;
1121            Query::new(&grammar.ts_language, source)?
1122        };
1123
1124        let mut override_configs_by_id = HashMap::default();
1125        for (ix, name) in query.capture_names().iter().enumerate() {
1126            if !name.starts_with('_') {
1127                let value = self.config.overrides.remove(*name).unwrap_or_default();
1128                for server_name in &value.opt_into_language_servers {
1129                    if !self
1130                        .config
1131                        .scope_opt_in_language_servers
1132                        .contains(server_name)
1133                    {
1134                        util::debug_panic!("Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server");
1135                    }
1136                }
1137
1138                override_configs_by_id.insert(ix as u32, (name.to_string(), value));
1139            }
1140        }
1141
1142        if !self.config.overrides.is_empty() {
1143            let keys = self.config.overrides.keys().collect::<Vec<_>>();
1144            Err(anyhow!(
1145                "language {:?} has overrides in config not in query: {keys:?}",
1146                self.config.name
1147            ))?;
1148        }
1149
1150        for disabled_scope_name in self
1151            .config
1152            .brackets
1153            .disabled_scopes_by_bracket_ix
1154            .iter()
1155            .flatten()
1156        {
1157            if !override_configs_by_id
1158                .values()
1159                .any(|(scope_name, _)| scope_name == disabled_scope_name)
1160            {
1161                Err(anyhow!(
1162                    "language {:?} has overrides in config not in query: {disabled_scope_name:?}",
1163                    self.config.name
1164                ))?;
1165            }
1166        }
1167
1168        for (name, override_config) in override_configs_by_id.values_mut() {
1169            override_config.disabled_bracket_ixs = self
1170                .config
1171                .brackets
1172                .disabled_scopes_by_bracket_ix
1173                .iter()
1174                .enumerate()
1175                .filter_map(|(ix, disabled_scope_names)| {
1176                    if disabled_scope_names.contains(name) {
1177                        Some(ix as u16)
1178                    } else {
1179                        None
1180                    }
1181                })
1182                .collect();
1183        }
1184
1185        self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1186
1187        let grammar = self
1188            .grammar_mut()
1189            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1190        grammar.override_config = Some(OverrideConfig {
1191            query,
1192            values: override_configs_by_id,
1193        });
1194        Ok(self)
1195    }
1196
1197    pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1198        let grammar = self
1199            .grammar_mut()
1200            .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1201
1202        let query = Query::new(&grammar.ts_language, source)?;
1203        let mut redaction_capture_ix = None;
1204        get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1205
1206        if let Some(redaction_capture_ix) = redaction_capture_ix {
1207            grammar.redactions_config = Some(RedactionConfig {
1208                query,
1209                redaction_capture_ix,
1210            });
1211        }
1212
1213        Ok(self)
1214    }
1215
1216    fn grammar_mut(&mut self) -> Option<&mut Grammar> {
1217        Arc::get_mut(self.grammar.as_mut()?)
1218    }
1219
1220    pub fn name(&self) -> Arc<str> {
1221        self.config.name.clone()
1222    }
1223
1224    pub fn code_fence_block_name(&self) -> Arc<str> {
1225        self.config
1226            .code_fence_block_name
1227            .clone()
1228            .unwrap_or_else(|| self.config.name.to_lowercase().into())
1229    }
1230
1231    pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1232        self.context_provider.clone()
1233    }
1234
1235    pub fn highlight_text<'a>(
1236        self: &'a Arc<Self>,
1237        text: &'a Rope,
1238        range: Range<usize>,
1239    ) -> Vec<(Range<usize>, HighlightId)> {
1240        let mut result = Vec::new();
1241        if let Some(grammar) = &self.grammar {
1242            let tree = grammar.parse_text(text, None);
1243            let captures =
1244                SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1245                    grammar.highlights_query.as_ref()
1246                });
1247            let highlight_maps = vec![grammar.highlight_map()];
1248            let mut offset = 0;
1249            for chunk in BufferChunks::new(text, range, Some((captures, highlight_maps)), vec![]) {
1250                let end_offset = offset + chunk.text.len();
1251                if let Some(highlight_id) = chunk.syntax_highlight_id {
1252                    if !highlight_id.is_default() {
1253                        result.push((offset..end_offset, highlight_id));
1254                    }
1255                }
1256                offset = end_offset;
1257            }
1258        }
1259        result
1260    }
1261
1262    pub fn path_suffixes(&self) -> &[String] {
1263        &self.config.matcher.path_suffixes
1264    }
1265
1266    pub fn should_autoclose_before(&self, c: char) -> bool {
1267        c.is_whitespace() || self.config.autoclose_before.contains(c)
1268    }
1269
1270    pub fn set_theme(&self, theme: &SyntaxTheme) {
1271        if let Some(grammar) = self.grammar.as_ref() {
1272            if let Some(highlights_query) = &grammar.highlights_query {
1273                *grammar.highlight_map.lock() =
1274                    HighlightMap::new(highlights_query.capture_names(), theme);
1275            }
1276        }
1277    }
1278
1279    pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1280        self.grammar.as_ref()
1281    }
1282
1283    pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1284        LanguageScope {
1285            language: self.clone(),
1286            override_id: None,
1287        }
1288    }
1289
1290    pub fn prettier_parser_name(&self) -> Option<&str> {
1291        self.config.prettier_parser_name.as_deref()
1292    }
1293
1294    pub fn prettier_plugins(&self) -> &Vec<Arc<str>> {
1295        &self.config.prettier_plugins
1296    }
1297}
1298
1299impl LanguageScope {
1300    pub fn collapsed_placeholder(&self) -> &str {
1301        self.language.config.collapsed_placeholder.as_ref()
1302    }
1303
1304    /// Returns line prefix that is inserted in e.g. line continuations or
1305    /// in `toggle comments` action.
1306    pub fn line_comment_prefixes(&self) -> Option<&Vec<Arc<str>>> {
1307        Override::as_option(
1308            self.config_override().map(|o| &o.line_comments),
1309            Some(&self.language.config.line_comments),
1310        )
1311    }
1312
1313    pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1314        Override::as_option(
1315            self.config_override().map(|o| &o.block_comment),
1316            self.language.config.block_comment.as_ref(),
1317        )
1318        .map(|e| (&e.0, &e.1))
1319    }
1320
1321    /// Returns a list of language-specific word characters.
1322    ///
1323    /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1324    /// the purpose of actions like 'move to next word end` or whole-word search.
1325    /// It additionally accounts for language's additional word characters.
1326    pub fn word_characters(&self) -> Option<&HashSet<char>> {
1327        Override::as_option(
1328            self.config_override().map(|o| &o.word_characters),
1329            Some(&self.language.config.word_characters),
1330        )
1331    }
1332
1333    /// Returns a list of bracket pairs for a given language with an additional
1334    /// piece of information about whether the particular bracket pair is currently active for a given language.
1335    pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1336        let mut disabled_ids = self
1337            .config_override()
1338            .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1339        self.language
1340            .config
1341            .brackets
1342            .pairs
1343            .iter()
1344            .enumerate()
1345            .map(move |(ix, bracket)| {
1346                let mut is_enabled = true;
1347                if let Some(next_disabled_ix) = disabled_ids.first() {
1348                    if ix == *next_disabled_ix as usize {
1349                        disabled_ids = &disabled_ids[1..];
1350                        is_enabled = false;
1351                    }
1352                }
1353                (bracket, is_enabled)
1354            })
1355    }
1356
1357    pub fn should_autoclose_before(&self, c: char) -> bool {
1358        c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1359    }
1360
1361    pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1362        let config = &self.language.config;
1363        let opt_in_servers = &config.scope_opt_in_language_servers;
1364        if opt_in_servers.iter().any(|o| *o == *name.0) {
1365            if let Some(over) = self.config_override() {
1366                over.opt_into_language_servers.iter().any(|o| *o == *name.0)
1367            } else {
1368                false
1369            }
1370        } else {
1371            true
1372        }
1373    }
1374
1375    fn config_override(&self) -> Option<&LanguageConfigOverride> {
1376        let id = self.override_id?;
1377        let grammar = self.language.grammar.as_ref()?;
1378        let override_config = grammar.override_config.as_ref()?;
1379        override_config.values.get(&id).map(|e| &e.1)
1380    }
1381}
1382
1383impl Hash for Language {
1384    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1385        self.id.hash(state)
1386    }
1387}
1388
1389impl PartialEq for Language {
1390    fn eq(&self, other: &Self) -> bool {
1391        self.id.eq(&other.id)
1392    }
1393}
1394
1395impl Eq for Language {}
1396
1397impl Debug for Language {
1398    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1399        f.debug_struct("Language")
1400            .field("name", &self.config.name)
1401            .finish()
1402    }
1403}
1404
1405impl Grammar {
1406    pub fn id(&self) -> GrammarId {
1407        self.id
1408    }
1409
1410    fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1411        PARSER.with(|parser| {
1412            let mut parser = parser.borrow_mut();
1413            parser
1414                .set_language(&self.ts_language)
1415                .expect("incompatible grammar");
1416            let mut chunks = text.chunks_in_range(0..text.len());
1417            parser
1418                .parse_with(
1419                    &mut move |offset, _| {
1420                        chunks.seek(offset);
1421                        chunks.next().unwrap_or("").as_bytes()
1422                    },
1423                    old_tree.as_ref(),
1424                )
1425                .unwrap()
1426        })
1427    }
1428
1429    pub fn highlight_map(&self) -> HighlightMap {
1430        self.highlight_map.lock().clone()
1431    }
1432
1433    pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1434        let capture_id = self
1435            .highlights_query
1436            .as_ref()?
1437            .capture_index_for_name(name)?;
1438        Some(self.highlight_map.lock().get(capture_id))
1439    }
1440}
1441
1442impl CodeLabel {
1443    pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1444        let mut result = Self {
1445            runs: Vec::new(),
1446            filter_range: 0..text.len(),
1447            text,
1448        };
1449        if let Some(filter_text) = filter_text {
1450            if let Some(ix) = result.text.find(filter_text) {
1451                result.filter_range = ix..ix + filter_text.len();
1452            }
1453        }
1454        result
1455    }
1456}
1457
1458impl Ord for LanguageMatcher {
1459    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1460        self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
1461            self.first_line_pattern
1462                .as_ref()
1463                .map(Regex::as_str)
1464                .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
1465        })
1466    }
1467}
1468
1469impl PartialOrd for LanguageMatcher {
1470    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1471        Some(self.cmp(other))
1472    }
1473}
1474
1475impl Eq for LanguageMatcher {}
1476
1477impl PartialEq for LanguageMatcher {
1478    fn eq(&self, other: &Self) -> bool {
1479        self.path_suffixes == other.path_suffixes
1480            && self.first_line_pattern.as_ref().map(Regex::as_str)
1481                == other.first_line_pattern.as_ref().map(Regex::as_str)
1482    }
1483}
1484
1485#[cfg(any(test, feature = "test-support"))]
1486impl Default for FakeLspAdapter {
1487    fn default() -> Self {
1488        Self {
1489            name: "the-fake-language-server",
1490            capabilities: lsp::LanguageServer::full_capabilities(),
1491            initializer: None,
1492            disk_based_diagnostics_progress_token: None,
1493            initialization_options: None,
1494            disk_based_diagnostics_sources: Vec::new(),
1495            prettier_plugins: Vec::new(),
1496            language_server_binary: LanguageServerBinary {
1497                path: "/the/fake/lsp/path".into(),
1498                arguments: vec![],
1499                env: Default::default(),
1500            },
1501        }
1502    }
1503}
1504
1505#[cfg(any(test, feature = "test-support"))]
1506#[async_trait(?Send)]
1507impl LspAdapter for FakeLspAdapter {
1508    fn name(&self) -> LanguageServerName {
1509        LanguageServerName(self.name.into())
1510    }
1511
1512    fn get_language_server_command<'a>(
1513        self: Arc<Self>,
1514        _: Arc<Language>,
1515        _: Arc<Path>,
1516        _: Arc<dyn LspAdapterDelegate>,
1517        _: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
1518        _: &'a mut AsyncAppContext,
1519    ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
1520        async move { Ok(self.language_server_binary.clone()) }.boxed_local()
1521    }
1522
1523    async fn fetch_latest_server_version(
1524        &self,
1525        _: &dyn LspAdapterDelegate,
1526    ) -> Result<Box<dyn 'static + Send + Any>> {
1527        unreachable!();
1528    }
1529
1530    async fn fetch_server_binary(
1531        &self,
1532        _: Box<dyn 'static + Send + Any>,
1533        _: PathBuf,
1534        _: &dyn LspAdapterDelegate,
1535    ) -> Result<LanguageServerBinary> {
1536        unreachable!();
1537    }
1538
1539    async fn cached_server_binary(
1540        &self,
1541        _: PathBuf,
1542        _: &dyn LspAdapterDelegate,
1543    ) -> Option<LanguageServerBinary> {
1544        unreachable!();
1545    }
1546
1547    async fn installation_test_binary(&self, _: PathBuf) -> Option<LanguageServerBinary> {
1548        unreachable!();
1549    }
1550
1551    fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
1552
1553    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
1554        self.disk_based_diagnostics_sources.clone()
1555    }
1556
1557    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
1558        self.disk_based_diagnostics_progress_token.clone()
1559    }
1560
1561    async fn initialization_options(
1562        self: Arc<Self>,
1563        _: &Arc<dyn LspAdapterDelegate>,
1564    ) -> Result<Option<Value>> {
1565        Ok(self.initialization_options.clone())
1566    }
1567
1568    fn as_fake(&self) -> Option<&FakeLspAdapter> {
1569        Some(self)
1570    }
1571}
1572
1573fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
1574    for (ix, name) in query.capture_names().iter().enumerate() {
1575        for (capture_name, index) in captures.iter_mut() {
1576            if capture_name == name {
1577                **index = Some(ix as u32);
1578                break;
1579            }
1580        }
1581    }
1582}
1583
1584pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
1585    lsp::Position::new(point.row, point.column)
1586}
1587
1588pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
1589    Unclipped(PointUtf16::new(point.line, point.character))
1590}
1591
1592pub fn range_to_lsp(range: Range<PointUtf16>) -> lsp::Range {
1593    lsp::Range {
1594        start: point_to_lsp(range.start),
1595        end: point_to_lsp(range.end),
1596    }
1597}
1598
1599pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
1600    let mut start = point_from_lsp(range.start);
1601    let mut end = point_from_lsp(range.end);
1602    if start > end {
1603        mem::swap(&mut start, &mut end);
1604    }
1605    start..end
1606}
1607
1608#[cfg(test)]
1609mod tests {
1610    use super::*;
1611    use gpui::TestAppContext;
1612
1613    #[gpui::test(iterations = 10)]
1614    async fn test_language_loading(cx: &mut TestAppContext) {
1615        let languages = LanguageRegistry::test(cx.executor());
1616        let languages = Arc::new(languages);
1617        languages.register_native_grammars([
1618            ("json", tree_sitter_json::language()),
1619            ("rust", tree_sitter_rust::language()),
1620        ]);
1621        languages.register_test_language(LanguageConfig {
1622            name: "JSON".into(),
1623            grammar: Some("json".into()),
1624            matcher: LanguageMatcher {
1625                path_suffixes: vec!["json".into()],
1626                ..Default::default()
1627            },
1628            ..Default::default()
1629        });
1630        languages.register_test_language(LanguageConfig {
1631            name: "Rust".into(),
1632            grammar: Some("rust".into()),
1633            matcher: LanguageMatcher {
1634                path_suffixes: vec!["rs".into()],
1635                ..Default::default()
1636            },
1637            ..Default::default()
1638        });
1639        assert_eq!(
1640            languages.language_names(),
1641            &[
1642                "JSON".to_string(),
1643                "Plain Text".to_string(),
1644                "Rust".to_string(),
1645            ]
1646        );
1647
1648        let rust1 = languages.language_for_name("Rust");
1649        let rust2 = languages.language_for_name("Rust");
1650
1651        // Ensure language is still listed even if it's being loaded.
1652        assert_eq!(
1653            languages.language_names(),
1654            &[
1655                "JSON".to_string(),
1656                "Plain Text".to_string(),
1657                "Rust".to_string(),
1658            ]
1659        );
1660
1661        let (rust1, rust2) = futures::join!(rust1, rust2);
1662        assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
1663
1664        // Ensure language is still listed even after loading it.
1665        assert_eq!(
1666            languages.language_names(),
1667            &[
1668                "JSON".to_string(),
1669                "Plain Text".to_string(),
1670                "Rust".to_string(),
1671            ]
1672        );
1673
1674        // Loading an unknown language returns an error.
1675        assert!(languages.language_for_name("Unknown").await.is_err());
1676    }
1677}