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