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 it's API.
   9mod buffer;
  10mod diagnostic_set;
  11mod highlight_map;
  12pub mod language_settings;
  13mod outline;
  14pub mod proto;
  15mod syntax_map;
  16
  17#[cfg(test)]
  18mod buffer_tests;
  19pub mod markdown;
  20
  21use anyhow::{anyhow, Context, Result};
  22use async_trait::async_trait;
  23use collections::{HashMap, HashSet};
  24use futures::{
  25    channel::{mpsc, oneshot},
  26    future::Shared,
  27    FutureExt, TryFutureExt as _,
  28};
  29use gpui::{AppContext, AsyncAppContext, BackgroundExecutor, Task};
  30pub use highlight_map::HighlightMap;
  31use lazy_static::lazy_static;
  32use lsp::{CodeActionKind, LanguageServerBinary};
  33use parking_lot::{Mutex, RwLock};
  34use postage::watch;
  35use regex::Regex;
  36use serde::{de, Deserialize, Deserializer};
  37use serde_json::Value;
  38use std::{
  39    any::Any,
  40    borrow::Cow,
  41    cell::RefCell,
  42    fmt::Debug,
  43    hash::Hash,
  44    mem,
  45    ops::{Not, Range},
  46    path::{Path, PathBuf},
  47    str,
  48    sync::{
  49        atomic::{AtomicU64, AtomicUsize, Ordering::SeqCst},
  50        Arc,
  51    },
  52};
  53use syntax_map::SyntaxSnapshot;
  54use theme::{SyntaxTheme, Theme};
  55use tree_sitter::{self, wasmtime, Query, WasmStore};
  56use unicase::UniCase;
  57use util::{http::HttpClient, paths::PathExt};
  58use util::{post_inc, ResultExt, TryFutureExt as _, UnwrapFuture};
  59
  60pub use buffer::Operation;
  61pub use buffer::*;
  62pub use diagnostic_set::DiagnosticEntry;
  63pub use lsp::LanguageServerId;
  64pub use outline::{Outline, OutlineItem};
  65pub use syntax_map::{OwnedSyntaxLayer, SyntaxLayer};
  66pub use text::LineEnding;
  67pub use tree_sitter::{Parser, Tree};
  68
  69/// Initializes the `language` crate.
  70///
  71/// This should be called before making use of items from the create.
  72pub fn init(cx: &mut AppContext) {
  73    language_settings::init(cx);
  74}
  75
  76#[derive(Clone, Default)]
  77struct LspBinaryStatusSender {
  78    txs: Arc<Mutex<Vec<mpsc::UnboundedSender<(Arc<Language>, LanguageServerBinaryStatus)>>>>,
  79}
  80
  81impl LspBinaryStatusSender {
  82    fn subscribe(&self) -> mpsc::UnboundedReceiver<(Arc<Language>, LanguageServerBinaryStatus)> {
  83        let (tx, rx) = mpsc::unbounded();
  84        self.txs.lock().push(tx);
  85        rx
  86    }
  87
  88    fn send(&self, language: Arc<Language>, status: LanguageServerBinaryStatus) {
  89        let mut txs = self.txs.lock();
  90        txs.retain(|tx| {
  91            tx.unbounded_send((language.clone(), status.clone()))
  92                .is_ok()
  93        });
  94    }
  95}
  96
  97thread_local! {
  98    static PARSER: RefCell<Parser> = {
  99        let mut parser = Parser::new();
 100        parser.set_wasm_store(WasmStore::new(WASM_ENGINE.clone()).unwrap()).unwrap();
 101        RefCell::new(parser)
 102    };
 103}
 104
 105lazy_static! {
 106    pub(crate) static ref NEXT_GRAMMAR_ID: AtomicUsize = Default::default();
 107    /// A shared grammar for plain text, exposed for reuse by downstream crates.
 108    #[doc(hidden)]
 109    pub static ref WASM_ENGINE: wasmtime::Engine = wasmtime::Engine::default();
 110    pub static ref PLAIN_TEXT: Arc<Language> = Arc::new(Language::new(
 111        LanguageConfig {
 112            name: "Plain Text".into(),
 113            ..Default::default()
 114        },
 115        None,
 116    ));
 117}
 118
 119/// Types that represent a position in a buffer, and can be converted into
 120/// an LSP position, to send to a language server.
 121pub trait ToLspPosition {
 122    /// Converts the value into an LSP position.
 123    fn to_lsp_position(self) -> lsp::Position;
 124}
 125
 126/// A name of a language server.
 127#[derive(Clone, Debug, PartialEq, Eq, Hash)]
 128pub struct LanguageServerName(pub Arc<str>);
 129
 130/// Represents a Language Server, with certain cached sync properties.
 131/// Uses [`LspAdapter`] under the hood, but calls all 'static' methods
 132/// once at startup, and caches the results.
 133pub struct CachedLspAdapter {
 134    pub name: LanguageServerName,
 135    pub short_name: &'static str,
 136    pub disk_based_diagnostic_sources: Vec<String>,
 137    pub disk_based_diagnostics_progress_token: Option<String>,
 138    pub language_ids: HashMap<String, String>,
 139    pub adapter: Arc<dyn LspAdapter>,
 140    pub reinstall_attempt_count: AtomicU64,
 141}
 142
 143impl CachedLspAdapter {
 144    pub async fn new(adapter: Arc<dyn LspAdapter>) -> Arc<Self> {
 145        let name = adapter.name();
 146        let short_name = adapter.short_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            short_name,
 154            disk_based_diagnostic_sources,
 155            disk_based_diagnostics_progress_token,
 156            language_ids,
 157            adapter,
 158            reinstall_attempt_count: AtomicU64::new(0),
 159        })
 160    }
 161
 162    pub async fn fetch_latest_server_version(
 163        &self,
 164        delegate: &dyn LspAdapterDelegate,
 165    ) -> Result<Box<dyn 'static + Send + Any>> {
 166        self.adapter.fetch_latest_server_version(delegate).await
 167    }
 168
 169    pub fn will_fetch_server(
 170        &self,
 171        delegate: &Arc<dyn LspAdapterDelegate>,
 172        cx: &mut AsyncAppContext,
 173    ) -> Option<Task<Result<()>>> {
 174        self.adapter.will_fetch_server(delegate, cx)
 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 async fn fetch_server_binary(
 186        &self,
 187        version: Box<dyn 'static + Send + Any>,
 188        container_dir: PathBuf,
 189        delegate: &dyn LspAdapterDelegate,
 190    ) -> Result<LanguageServerBinary> {
 191        self.adapter
 192            .fetch_server_binary(version, container_dir, delegate)
 193            .await
 194    }
 195
 196    pub async fn cached_server_binary(
 197        &self,
 198        container_dir: PathBuf,
 199        delegate: &dyn LspAdapterDelegate,
 200    ) -> Option<LanguageServerBinary> {
 201        self.adapter
 202            .cached_server_binary(container_dir, delegate)
 203            .await
 204    }
 205
 206    pub fn can_be_reinstalled(&self) -> bool {
 207        self.adapter.can_be_reinstalled()
 208    }
 209
 210    pub async fn installation_test_binary(
 211        &self,
 212        container_dir: PathBuf,
 213    ) -> Option<LanguageServerBinary> {
 214        self.adapter.installation_test_binary(container_dir).await
 215    }
 216
 217    pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
 218        self.adapter.code_action_kinds()
 219    }
 220
 221    pub fn workspace_configuration(&self, workspace_root: &Path, cx: &mut AppContext) -> Value {
 222        self.adapter.workspace_configuration(workspace_root, cx)
 223    }
 224
 225    pub fn process_diagnostics(&self, params: &mut lsp::PublishDiagnosticsParams) {
 226        self.adapter.process_diagnostics(params)
 227    }
 228
 229    pub async fn process_completion(&self, completion_item: &mut lsp::CompletionItem) {
 230        self.adapter.process_completion(completion_item).await
 231    }
 232
 233    pub async fn label_for_completion(
 234        &self,
 235        completion_item: &lsp::CompletionItem,
 236        language: &Arc<Language>,
 237    ) -> Option<CodeLabel> {
 238        self.adapter
 239            .label_for_completion(completion_item, language)
 240            .await
 241    }
 242
 243    pub async fn label_for_symbol(
 244        &self,
 245        name: &str,
 246        kind: lsp::SymbolKind,
 247        language: &Arc<Language>,
 248    ) -> Option<CodeLabel> {
 249        self.adapter.label_for_symbol(name, kind, language).await
 250    }
 251
 252    pub fn prettier_plugins(&self) -> &[&'static str] {
 253        self.adapter.prettier_plugins()
 254    }
 255}
 256
 257/// [`LspAdapterDelegate`] allows [`LspAdapter]` implementations to interface with the application
 258// e.g. to display a notification or fetch data from the web.
 259pub trait LspAdapterDelegate: Send + Sync {
 260    fn show_notification(&self, message: &str, cx: &mut AppContext);
 261    fn http_client(&self) -> Arc<dyn HttpClient>;
 262}
 263
 264#[async_trait]
 265pub trait LspAdapter: 'static + Send + Sync {
 266    fn name(&self) -> LanguageServerName;
 267
 268    fn short_name(&self) -> &'static str;
 269
 270    async fn fetch_latest_server_version(
 271        &self,
 272        delegate: &dyn LspAdapterDelegate,
 273    ) -> Result<Box<dyn 'static + Send + Any>>;
 274
 275    fn will_fetch_server(
 276        &self,
 277        _: &Arc<dyn LspAdapterDelegate>,
 278        _: &mut AsyncAppContext,
 279    ) -> Option<Task<Result<()>>> {
 280        None
 281    }
 282
 283    fn will_start_server(
 284        &self,
 285        _: &Arc<dyn LspAdapterDelegate>,
 286        _: &mut AsyncAppContext,
 287    ) -> Option<Task<Result<()>>> {
 288        None
 289    }
 290
 291    async fn fetch_server_binary(
 292        &self,
 293        version: Box<dyn 'static + Send + Any>,
 294        container_dir: PathBuf,
 295        delegate: &dyn LspAdapterDelegate,
 296    ) -> Result<LanguageServerBinary>;
 297
 298    async fn cached_server_binary(
 299        &self,
 300        container_dir: PathBuf,
 301        delegate: &dyn LspAdapterDelegate,
 302    ) -> Option<LanguageServerBinary>;
 303
 304    /// Returns `true` if a language server can be reinstalled.
 305    ///
 306    /// If language server initialization fails, a reinstallation will be attempted unless the value returned from this method is `false`.
 307    ///
 308    /// Implementations that rely on software already installed on user's system
 309    /// should have [`can_be_reinstalled`](Self::can_be_reinstalled) return `false`.
 310    fn can_be_reinstalled(&self) -> bool {
 311        true
 312    }
 313
 314    async fn installation_test_binary(
 315        &self,
 316        container_dir: PathBuf,
 317    ) -> Option<LanguageServerBinary>;
 318
 319    fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
 320
 321    /// A callback called for each [`lsp::CompletionItem`] obtained from LSP server.
 322    /// Some LspAdapter implementations might want to modify the obtained item to
 323    /// change how it's displayed.
 324    async fn process_completion(&self, _: &mut lsp::CompletionItem) {}
 325
 326    async fn label_for_completion(
 327        &self,
 328        _: &lsp::CompletionItem,
 329        _: &Arc<Language>,
 330    ) -> Option<CodeLabel> {
 331        None
 332    }
 333
 334    async fn label_for_symbol(
 335        &self,
 336        _: &str,
 337        _: lsp::SymbolKind,
 338        _: &Arc<Language>,
 339    ) -> Option<CodeLabel> {
 340        None
 341    }
 342
 343    /// Returns initialization options that are going to be sent to a LSP server as a part of [`lsp::InitializeParams`]
 344    fn initialization_options(&self) -> Option<Value> {
 345        None
 346    }
 347
 348    fn workspace_configuration(&self, _workspace_root: &Path, _cx: &mut AppContext) -> Value {
 349        serde_json::json!({})
 350    }
 351
 352    /// Returns a list of code actions supported by a given LspAdapter
 353    fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
 354        Some(vec![
 355            CodeActionKind::EMPTY,
 356            CodeActionKind::QUICKFIX,
 357            CodeActionKind::REFACTOR,
 358            CodeActionKind::REFACTOR_EXTRACT,
 359            CodeActionKind::SOURCE,
 360        ])
 361    }
 362
 363    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
 364        Default::default()
 365    }
 366
 367    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
 368        None
 369    }
 370
 371    fn language_ids(&self) -> HashMap<String, String> {
 372        Default::default()
 373    }
 374
 375    fn prettier_plugins(&self) -> &[&'static str] {
 376        &[]
 377    }
 378}
 379
 380#[derive(Clone, Debug, PartialEq, Eq)]
 381pub struct CodeLabel {
 382    /// The text to display.
 383    pub text: String,
 384    /// Syntax highlighting runs.
 385    pub runs: Vec<(Range<usize>, HighlightId)>,
 386    /// The portion of the text that should be used in fuzzy filtering.
 387    pub filter_range: Range<usize>,
 388}
 389
 390#[derive(Clone, Deserialize)]
 391pub struct LanguageConfig {
 392    /// Human-readable name of the language.
 393    pub name: Arc<str>,
 394    // The name of the grammar in a WASM bundle (experimental).
 395    pub grammar_name: Option<Arc<str>>,
 396    /// 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`.
 397    pub path_suffixes: Vec<String>,
 398    /// List of bracket types in a language.
 399    pub brackets: BracketPairConfig,
 400    /// A regex pattern that determines whether the language should be assigned to a file or not.
 401    #[serde(default, deserialize_with = "deserialize_regex")]
 402    pub first_line_pattern: Option<Regex>,
 403    /// If set to true, auto indentation uses last non empty line to determine
 404    /// the indentation level for a new line.
 405    #[serde(default = "auto_indent_using_last_non_empty_line_default")]
 406    pub auto_indent_using_last_non_empty_line: bool,
 407    /// A regex that is used to determine whether the indentation level should be
 408    /// increased in the following line.
 409    #[serde(default, deserialize_with = "deserialize_regex")]
 410    pub increase_indent_pattern: Option<Regex>,
 411    /// A regex that is used to determine whether the indentation level should be
 412    /// decreased in the following line.
 413    #[serde(default, deserialize_with = "deserialize_regex")]
 414    pub decrease_indent_pattern: Option<Regex>,
 415    /// A list of characters that trigger the automatic insertion of a closing
 416    /// bracket when they immediately precede the point where an opening
 417    /// bracket is inserted.
 418    #[serde(default)]
 419    pub autoclose_before: String,
 420    /// A placeholder used internally by Semantic Index.
 421    #[serde(default)]
 422    pub collapsed_placeholder: String,
 423    /// A line comment string that is inserted in e.g. `toggle comments` action.
 424    /// A language can have multiple flavours of line comments. All of the provided line comments are
 425    /// used for comment continuations on the next line, but only the first one is used for Editor::ToggleComments.
 426    #[serde(default)]
 427    pub line_comments: Vec<Arc<str>>,
 428    /// Starting and closing characters of a block comment.
 429    #[serde(default)]
 430    pub block_comment: Option<(Arc<str>, Arc<str>)>,
 431    /// A list of language servers that are allowed to run on subranges of a given language.
 432    #[serde(default)]
 433    pub scope_opt_in_language_servers: Vec<String>,
 434    #[serde(default)]
 435    pub overrides: HashMap<String, LanguageConfigOverride>,
 436    /// A list of characters that Zed should treat as word characters for the
 437    /// purpose of features that operate on word boundaries, like 'move to next word end'
 438    /// or a whole-word search in buffer search.
 439    #[serde(default)]
 440    pub word_characters: HashSet<char>,
 441    /// The name of a Prettier parser that should be used for this language.
 442    #[serde(default)]
 443    pub prettier_parser_name: Option<String>,
 444}
 445
 446/// Tree-sitter language queries for a given language.
 447#[derive(Debug, Default)]
 448pub struct LanguageQueries {
 449    pub highlights: Option<Cow<'static, str>>,
 450    pub brackets: Option<Cow<'static, str>>,
 451    pub indents: Option<Cow<'static, str>>,
 452    pub outline: Option<Cow<'static, str>>,
 453    pub embedding: Option<Cow<'static, str>>,
 454    pub injections: Option<Cow<'static, str>>,
 455    pub overrides: Option<Cow<'static, str>>,
 456    pub redactions: Option<Cow<'static, str>>,
 457}
 458
 459/// Represents a language for the given range. Some languages (e.g. HTML)
 460/// interleave several languages together, thus a single buffer might actually contain
 461/// several nested scopes.
 462#[derive(Clone, Debug)]
 463pub struct LanguageScope {
 464    language: Arc<Language>,
 465    override_id: Option<u32>,
 466}
 467
 468#[derive(Clone, Deserialize, Default, Debug)]
 469pub struct LanguageConfigOverride {
 470    #[serde(default)]
 471    pub line_comments: Override<Vec<Arc<str>>>,
 472    #[serde(default)]
 473    pub block_comment: Override<(Arc<str>, Arc<str>)>,
 474    #[serde(skip_deserializing)]
 475    pub disabled_bracket_ixs: Vec<u16>,
 476    #[serde(default)]
 477    pub word_characters: Override<HashSet<char>>,
 478    #[serde(default)]
 479    pub opt_into_language_servers: Vec<String>,
 480}
 481
 482#[derive(Clone, Deserialize, Debug)]
 483#[serde(untagged)]
 484pub enum Override<T> {
 485    Remove { remove: bool },
 486    Set(T),
 487}
 488
 489impl<T> Default for Override<T> {
 490    fn default() -> Self {
 491        Override::Remove { remove: false }
 492    }
 493}
 494
 495impl<T> Override<T> {
 496    fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
 497        match this {
 498            Some(Self::Set(value)) => Some(value),
 499            Some(Self::Remove { remove: true }) => None,
 500            Some(Self::Remove { remove: false }) | None => original,
 501        }
 502    }
 503}
 504
 505impl Default for LanguageConfig {
 506    fn default() -> Self {
 507        Self {
 508            name: "".into(),
 509            grammar_name: None,
 510            path_suffixes: Default::default(),
 511            brackets: Default::default(),
 512            auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
 513            first_line_pattern: Default::default(),
 514            increase_indent_pattern: Default::default(),
 515            decrease_indent_pattern: Default::default(),
 516            autoclose_before: Default::default(),
 517            line_comments: Default::default(),
 518            block_comment: Default::default(),
 519            scope_opt_in_language_servers: Default::default(),
 520            overrides: Default::default(),
 521            word_characters: Default::default(),
 522            prettier_parser_name: None,
 523            collapsed_placeholder: Default::default(),
 524        }
 525    }
 526}
 527
 528fn auto_indent_using_last_non_empty_line_default() -> bool {
 529    true
 530}
 531
 532fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
 533    let source = Option::<String>::deserialize(d)?;
 534    if let Some(source) = source {
 535        Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
 536    } else {
 537        Ok(None)
 538    }
 539}
 540
 541#[doc(hidden)]
 542#[cfg(any(test, feature = "test-support"))]
 543pub struct FakeLspAdapter {
 544    pub name: &'static str,
 545    pub initialization_options: Option<Value>,
 546    pub capabilities: lsp::ServerCapabilities,
 547    pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
 548    pub disk_based_diagnostics_progress_token: Option<String>,
 549    pub disk_based_diagnostics_sources: Vec<String>,
 550    pub prettier_plugins: Vec<&'static str>,
 551}
 552
 553/// Configuration of handling bracket pairs for a given language.
 554///
 555/// This struct includes settings for defining which pairs of characters are considered brackets and
 556/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
 557#[derive(Clone, Debug, Default)]
 558pub struct BracketPairConfig {
 559    /// A list of character pairs that should be treated as brackets in the context of a given language.
 560    pub pairs: Vec<BracketPair>,
 561    /// A list of tree-sitter scopes for which a given bracket should not be active.
 562    /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
 563    pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
 564}
 565
 566impl<'de> Deserialize<'de> for BracketPairConfig {
 567    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
 568    where
 569        D: Deserializer<'de>,
 570    {
 571        #[derive(Deserialize)]
 572        pub struct Entry {
 573            #[serde(flatten)]
 574            pub bracket_pair: BracketPair,
 575            #[serde(default)]
 576            pub not_in: Vec<String>,
 577        }
 578
 579        let result = Vec::<Entry>::deserialize(deserializer)?;
 580        let mut brackets = Vec::with_capacity(result.len());
 581        let mut disabled_scopes_by_bracket_ix = Vec::with_capacity(result.len());
 582        for entry in result {
 583            brackets.push(entry.bracket_pair);
 584            disabled_scopes_by_bracket_ix.push(entry.not_in);
 585        }
 586
 587        Ok(BracketPairConfig {
 588            pairs: brackets,
 589            disabled_scopes_by_bracket_ix,
 590        })
 591    }
 592}
 593
 594/// Describes a single bracket pair and how an editor should react to e.g. inserting
 595/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
 596#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
 597pub struct BracketPair {
 598    /// Starting substring for a bracket.
 599    pub start: String,
 600    /// Ending substring for a bracket.
 601    pub end: String,
 602    /// True if `end` should be automatically inserted right after `start` characters.
 603    pub close: bool,
 604    /// True if an extra newline should be inserted while the cursor is in the middle
 605    /// of that bracket pair.
 606    pub newline: bool,
 607}
 608
 609pub struct Language {
 610    pub(crate) config: LanguageConfig,
 611    pub(crate) grammar: Option<Arc<Grammar>>,
 612    pub(crate) adapters: Vec<Arc<CachedLspAdapter>>,
 613
 614    #[cfg(any(test, feature = "test-support"))]
 615    fake_adapter: Option<(
 616        mpsc::UnboundedSender<lsp::FakeLanguageServer>,
 617        Arc<FakeLspAdapter>,
 618    )>,
 619}
 620
 621pub struct Grammar {
 622    id: usize,
 623    pub ts_language: tree_sitter::Language,
 624    pub(crate) error_query: Query,
 625    pub(crate) highlights_query: Option<Query>,
 626    pub(crate) brackets_config: Option<BracketConfig>,
 627    pub(crate) redactions_config: Option<RedactionConfig>,
 628    pub(crate) indents_config: Option<IndentConfig>,
 629    pub outline_config: Option<OutlineConfig>,
 630    pub embedding_config: Option<EmbeddingConfig>,
 631    pub(crate) injection_config: Option<InjectionConfig>,
 632    pub(crate) override_config: Option<OverrideConfig>,
 633    pub(crate) highlight_map: Mutex<HighlightMap>,
 634}
 635
 636struct IndentConfig {
 637    query: Query,
 638    indent_capture_ix: u32,
 639    start_capture_ix: Option<u32>,
 640    end_capture_ix: Option<u32>,
 641    outdent_capture_ix: Option<u32>,
 642}
 643
 644pub struct OutlineConfig {
 645    pub query: Query,
 646    pub item_capture_ix: u32,
 647    pub name_capture_ix: u32,
 648    pub context_capture_ix: Option<u32>,
 649    pub extra_context_capture_ix: Option<u32>,
 650}
 651
 652#[derive(Debug)]
 653pub struct EmbeddingConfig {
 654    pub query: Query,
 655    pub item_capture_ix: u32,
 656    pub name_capture_ix: Option<u32>,
 657    pub context_capture_ix: Option<u32>,
 658    pub collapse_capture_ix: Option<u32>,
 659    pub keep_capture_ix: Option<u32>,
 660}
 661
 662struct InjectionConfig {
 663    query: Query,
 664    content_capture_ix: u32,
 665    language_capture_ix: Option<u32>,
 666    patterns: Vec<InjectionPatternConfig>,
 667}
 668
 669struct RedactionConfig {
 670    pub query: Query,
 671    pub redaction_capture_ix: u32,
 672}
 673
 674struct OverrideConfig {
 675    query: Query,
 676    values: HashMap<u32, (String, LanguageConfigOverride)>,
 677}
 678
 679#[derive(Default, Clone)]
 680struct InjectionPatternConfig {
 681    language: Option<Box<str>>,
 682    combined: bool,
 683}
 684
 685struct BracketConfig {
 686    query: Query,
 687    open_capture_ix: u32,
 688    close_capture_ix: u32,
 689}
 690
 691#[derive(Clone)]
 692pub enum LanguageServerBinaryStatus {
 693    CheckingForUpdate,
 694    Downloading,
 695    Downloaded,
 696    Cached,
 697    Failed { error: String },
 698}
 699
 700type AvailableLanguageId = usize;
 701
 702#[derive(Clone)]
 703struct AvailableLanguage {
 704    id: AvailableLanguageId,
 705    config: LanguageConfig,
 706    grammar: AvailableGrammar,
 707    lsp_adapters: Vec<Arc<dyn LspAdapter>>,
 708    loaded: bool,
 709}
 710
 711#[derive(Clone)]
 712enum AvailableGrammar {
 713    Native {
 714        grammar: tree_sitter::Language,
 715        asset_dir: &'static str,
 716        get_queries: fn(&str) -> LanguageQueries,
 717    },
 718    Wasm {
 719        path: Arc<Path>,
 720        get_queries: fn(&Path) -> LanguageQueries,
 721    },
 722}
 723
 724pub struct LanguageRegistry {
 725    state: RwLock<LanguageRegistryState>,
 726    language_server_download_dir: Option<Arc<Path>>,
 727    login_shell_env_loaded: Shared<Task<()>>,
 728    #[allow(clippy::type_complexity)]
 729    lsp_binary_paths: Mutex<
 730        HashMap<LanguageServerName, Shared<Task<Result<LanguageServerBinary, Arc<anyhow::Error>>>>>,
 731    >,
 732    executor: Option<BackgroundExecutor>,
 733    lsp_binary_status_tx: LspBinaryStatusSender,
 734}
 735
 736struct LanguageRegistryState {
 737    next_language_server_id: usize,
 738    languages: Vec<Arc<Language>>,
 739    available_languages: Vec<AvailableLanguage>,
 740    next_available_language_id: AvailableLanguageId,
 741    loading_languages: HashMap<AvailableLanguageId, Vec<oneshot::Sender<Result<Arc<Language>>>>>,
 742    subscription: (watch::Sender<()>, watch::Receiver<()>),
 743    theme: Option<Arc<Theme>>,
 744    version: usize,
 745    reload_count: usize,
 746}
 747
 748pub struct PendingLanguageServer {
 749    pub server_id: LanguageServerId,
 750    pub task: Task<Result<lsp::LanguageServer>>,
 751    pub container_dir: Option<Arc<Path>>,
 752}
 753
 754impl LanguageRegistry {
 755    pub fn new(login_shell_env_loaded: Task<()>) -> Self {
 756        Self {
 757            state: RwLock::new(LanguageRegistryState {
 758                next_language_server_id: 0,
 759                languages: vec![PLAIN_TEXT.clone()],
 760                available_languages: Default::default(),
 761                next_available_language_id: 0,
 762                loading_languages: Default::default(),
 763                subscription: watch::channel(),
 764                theme: Default::default(),
 765                version: 0,
 766                reload_count: 0,
 767            }),
 768            language_server_download_dir: None,
 769            login_shell_env_loaded: login_shell_env_loaded.shared(),
 770            lsp_binary_paths: Default::default(),
 771            executor: None,
 772            lsp_binary_status_tx: Default::default(),
 773        }
 774    }
 775
 776    #[cfg(any(test, feature = "test-support"))]
 777    pub fn test() -> Self {
 778        Self::new(Task::ready(()))
 779    }
 780
 781    pub fn set_executor(&mut self, executor: BackgroundExecutor) {
 782        self.executor = Some(executor);
 783    }
 784
 785    /// Clear out all of the loaded languages and reload them from scratch.
 786    pub fn reload(&self) {
 787        self.state.write().reload();
 788    }
 789
 790    pub fn register(
 791        &self,
 792        asset_dir: &'static str,
 793        config: LanguageConfig,
 794        grammar: tree_sitter::Language,
 795        lsp_adapters: Vec<Arc<dyn LspAdapter>>,
 796        get_queries: fn(&str) -> LanguageQueries,
 797    ) {
 798        let state = &mut *self.state.write();
 799        state.available_languages.push(AvailableLanguage {
 800            id: post_inc(&mut state.next_available_language_id),
 801            config,
 802            grammar: AvailableGrammar::Native {
 803                grammar,
 804                get_queries,
 805                asset_dir,
 806            },
 807            lsp_adapters,
 808            loaded: false,
 809        });
 810    }
 811
 812    pub fn register_wasm(
 813        &self,
 814        path: Arc<Path>,
 815        config: LanguageConfig,
 816        get_queries: fn(&Path) -> LanguageQueries,
 817    ) {
 818        let state = &mut *self.state.write();
 819        state.available_languages.push(AvailableLanguage {
 820            id: post_inc(&mut state.next_available_language_id),
 821            config,
 822            grammar: AvailableGrammar::Wasm { path, get_queries },
 823            lsp_adapters: Vec::new(),
 824            loaded: false,
 825        });
 826    }
 827
 828    pub fn language_names(&self) -> Vec<String> {
 829        let state = self.state.read();
 830        let mut result = state
 831            .available_languages
 832            .iter()
 833            .filter_map(|l| l.loaded.not().then_some(l.config.name.to_string()))
 834            .chain(state.languages.iter().map(|l| l.config.name.to_string()))
 835            .collect::<Vec<_>>();
 836        result.sort_unstable_by_key(|language_name| language_name.to_lowercase());
 837        result
 838    }
 839
 840    pub fn add(&self, language: Arc<Language>) {
 841        self.state.write().add(language);
 842    }
 843
 844    pub fn subscribe(&self) -> watch::Receiver<()> {
 845        self.state.read().subscription.1.clone()
 846    }
 847
 848    /// The number of times that the registry has been changed,
 849    /// by adding languages or reloading.
 850    pub fn version(&self) -> usize {
 851        self.state.read().version
 852    }
 853
 854    /// The number of times that the registry has been reloaded.
 855    pub fn reload_count(&self) -> usize {
 856        self.state.read().reload_count
 857    }
 858
 859    pub fn set_theme(&self, theme: Arc<Theme>) {
 860        let mut state = self.state.write();
 861        state.theme = Some(theme.clone());
 862        for language in &state.languages {
 863            language.set_theme(theme.syntax());
 864        }
 865    }
 866
 867    pub fn set_language_server_download_dir(&mut self, path: impl Into<Arc<Path>>) {
 868        self.language_server_download_dir = Some(path.into());
 869    }
 870
 871    pub fn language_for_name(
 872        self: &Arc<Self>,
 873        name: &str,
 874    ) -> UnwrapFuture<oneshot::Receiver<Result<Arc<Language>>>> {
 875        let name = UniCase::new(name);
 876        self.get_or_load_language(|config| UniCase::new(config.name.as_ref()) == name)
 877    }
 878
 879    pub fn language_for_name_or_extension(
 880        self: &Arc<Self>,
 881        string: &str,
 882    ) -> UnwrapFuture<oneshot::Receiver<Result<Arc<Language>>>> {
 883        let string = UniCase::new(string);
 884        self.get_or_load_language(|config| {
 885            UniCase::new(config.name.as_ref()) == string
 886                || config
 887                    .path_suffixes
 888                    .iter()
 889                    .any(|suffix| UniCase::new(suffix) == string)
 890        })
 891    }
 892
 893    pub fn language_for_file(
 894        self: &Arc<Self>,
 895        path: impl AsRef<Path>,
 896        content: Option<&Rope>,
 897    ) -> UnwrapFuture<oneshot::Receiver<Result<Arc<Language>>>> {
 898        let path = path.as_ref();
 899        let filename = path.file_name().and_then(|name| name.to_str());
 900        let extension = path.extension_or_hidden_file_name();
 901        let path_suffixes = [extension, filename];
 902        self.get_or_load_language(|config| {
 903            let path_matches = config
 904                .path_suffixes
 905                .iter()
 906                .any(|suffix| path_suffixes.contains(&Some(suffix.as_str())));
 907            let content_matches = content.zip(config.first_line_pattern.as_ref()).map_or(
 908                false,
 909                |(content, pattern)| {
 910                    let end = content.clip_point(Point::new(0, 256), Bias::Left);
 911                    let end = content.point_to_offset(end);
 912                    let text = content.chunks_in_range(0..end).collect::<String>();
 913                    pattern.is_match(&text)
 914                },
 915            );
 916            path_matches || content_matches
 917        })
 918    }
 919
 920    fn get_or_load_language(
 921        self: &Arc<Self>,
 922        callback: impl Fn(&LanguageConfig) -> bool,
 923    ) -> UnwrapFuture<oneshot::Receiver<Result<Arc<Language>>>> {
 924        let (tx, rx) = oneshot::channel();
 925
 926        let mut state = self.state.write();
 927        if let Some(language) = state
 928            .languages
 929            .iter()
 930            .find(|language| callback(&language.config))
 931        {
 932            let _ = tx.send(Ok(language.clone()));
 933        } else if let Some(executor) = self.executor.clone() {
 934            if let Some(language) = state
 935                .available_languages
 936                .iter()
 937                .find(|l| !l.loaded && callback(&l.config))
 938                .cloned()
 939            {
 940                let txs = state
 941                    .loading_languages
 942                    .entry(language.id)
 943                    .or_insert_with(|| {
 944                        let this = self.clone();
 945                        executor
 946                            .spawn(async move {
 947                                let id = language.id;
 948                                let name = language.config.name.clone();
 949                                let language = async {
 950                                    let (grammar, queries) = match language.grammar {
 951                                        AvailableGrammar::Native {
 952                                            grammar,
 953                                            asset_dir,
 954                                            get_queries,
 955                                        } => (grammar, (get_queries)(asset_dir)),
 956                                        AvailableGrammar::Wasm { path, get_queries } => {
 957                                            let grammar_name =
 958                                                &language.config.grammar_name.as_ref().ok_or_else(
 959                                                    || anyhow!("missing grammar name"),
 960                                                )?;
 961                                            let mut wasm_path = path.join(grammar_name.as_ref());
 962                                            wasm_path.set_extension("wasm");
 963                                            let wasm_bytes = std::fs::read(&wasm_path)?;
 964                                            let grammar = PARSER.with(|parser| {
 965                                                let mut parser = parser.borrow_mut();
 966                                                let mut store = parser.take_wasm_store().unwrap();
 967                                                let grammar =
 968                                                    store.load_language(&grammar_name, &wasm_bytes);
 969                                                parser.set_wasm_store(store).unwrap();
 970                                                grammar
 971                                            })?;
 972                                            (grammar, get_queries(path.as_ref()))
 973                                        }
 974                                    };
 975                                    Language::new(language.config, Some(grammar))
 976                                        .with_lsp_adapters(language.lsp_adapters)
 977                                        .await
 978                                        .with_queries(queries)
 979                                }
 980                                .await;
 981
 982                                match language {
 983                                    Ok(language) => {
 984                                        let language = Arc::new(language);
 985                                        let mut state = this.state.write();
 986
 987                                        state.add(language.clone());
 988                                        state.mark_language_loaded(id);
 989                                        if let Some(mut txs) = state.loading_languages.remove(&id) {
 990                                            for tx in txs.drain(..) {
 991                                                let _ = tx.send(Ok(language.clone()));
 992                                            }
 993                                        }
 994                                    }
 995                                    Err(e) => {
 996                                        log::error!("failed to load language {name}:\n{:?}", e);
 997                                        let mut state = this.state.write();
 998                                        state.mark_language_loaded(id);
 999                                        if let Some(mut txs) = state.loading_languages.remove(&id) {
1000                                            for tx in txs.drain(..) {
1001                                                let _ = tx.send(Err(anyhow!(
1002                                                    "failed to load language {}: {}",
1003                                                    name,
1004                                                    e
1005                                                )));
1006                                            }
1007                                        }
1008                                    }
1009                                };
1010                            })
1011                            .detach();
1012
1013                        Vec::new()
1014                    });
1015                txs.push(tx);
1016            } else {
1017                let _ = tx.send(Err(anyhow!("language not found")));
1018            }
1019        } else {
1020            let _ = tx.send(Err(anyhow!("executor does not exist")));
1021        }
1022
1023        rx.unwrap()
1024    }
1025
1026    pub fn to_vec(&self) -> Vec<Arc<Language>> {
1027        self.state.read().languages.iter().cloned().collect()
1028    }
1029
1030    pub fn create_pending_language_server(
1031        self: &Arc<Self>,
1032        stderr_capture: Arc<Mutex<Option<String>>>,
1033        language: Arc<Language>,
1034        adapter: Arc<CachedLspAdapter>,
1035        root_path: Arc<Path>,
1036        delegate: Arc<dyn LspAdapterDelegate>,
1037        cx: &mut AppContext,
1038    ) -> Option<PendingLanguageServer> {
1039        let server_id = self.state.write().next_language_server_id();
1040        log::info!(
1041            "starting language server {:?}, path: {root_path:?}, id: {server_id}",
1042            adapter.name.0
1043        );
1044
1045        #[cfg(any(test, feature = "test-support"))]
1046        if language.fake_adapter.is_some() {
1047            let task = cx.spawn(|cx| async move {
1048                let (servers_tx, fake_adapter) = language.fake_adapter.as_ref().unwrap();
1049                let (server, mut fake_server) = lsp::FakeLanguageServer::new(
1050                    fake_adapter.name.to_string(),
1051                    fake_adapter.capabilities.clone(),
1052                    cx.clone(),
1053                );
1054
1055                if let Some(initializer) = &fake_adapter.initializer {
1056                    initializer(&mut fake_server);
1057                }
1058
1059                let servers_tx = servers_tx.clone();
1060                cx.background_executor()
1061                    .spawn(async move {
1062                        if fake_server
1063                            .try_receive_notification::<lsp::notification::Initialized>()
1064                            .await
1065                            .is_some()
1066                        {
1067                            servers_tx.unbounded_send(fake_server).ok();
1068                        }
1069                    })
1070                    .detach();
1071
1072                Ok(server)
1073            });
1074
1075            return Some(PendingLanguageServer {
1076                server_id,
1077                task,
1078                container_dir: None,
1079            });
1080        }
1081
1082        let download_dir = self
1083            .language_server_download_dir
1084            .clone()
1085            .ok_or_else(|| anyhow!("language server download directory has not been assigned before starting server"))
1086            .log_err()?;
1087        let this = self.clone();
1088        let language = language.clone();
1089        let container_dir: Arc<Path> = Arc::from(download_dir.join(adapter.name.0.as_ref()));
1090        let root_path = root_path.clone();
1091        let adapter = adapter.clone();
1092        let login_shell_env_loaded = self.login_shell_env_loaded.clone();
1093        let lsp_binary_statuses = self.lsp_binary_status_tx.clone();
1094
1095        let task = {
1096            let container_dir = container_dir.clone();
1097            cx.spawn(move |mut cx| async move {
1098                login_shell_env_loaded.await;
1099
1100                let entry = this
1101                    .lsp_binary_paths
1102                    .lock()
1103                    .entry(adapter.name.clone())
1104                    .or_insert_with(|| {
1105                        let adapter = adapter.clone();
1106                        let language = language.clone();
1107                        let delegate = delegate.clone();
1108                        cx.spawn(|cx| {
1109                            get_binary(
1110                                adapter,
1111                                language,
1112                                delegate,
1113                                container_dir,
1114                                lsp_binary_statuses,
1115                                cx,
1116                            )
1117                            .map_err(Arc::new)
1118                        })
1119                        .shared()
1120                    })
1121                    .clone();
1122
1123                let binary = match entry.await {
1124                    Ok(binary) => binary,
1125                    Err(err) => anyhow::bail!("{err}"),
1126                };
1127
1128                if let Some(task) = adapter.will_start_server(&delegate, &mut cx) {
1129                    task.await?;
1130                }
1131
1132                lsp::LanguageServer::new(
1133                    stderr_capture,
1134                    server_id,
1135                    binary,
1136                    &root_path,
1137                    adapter.code_action_kinds(),
1138                    cx,
1139                )
1140            })
1141        };
1142
1143        Some(PendingLanguageServer {
1144            server_id,
1145            task,
1146            container_dir: Some(container_dir),
1147        })
1148    }
1149
1150    pub fn language_server_binary_statuses(
1151        &self,
1152    ) -> mpsc::UnboundedReceiver<(Arc<Language>, LanguageServerBinaryStatus)> {
1153        self.lsp_binary_status_tx.subscribe()
1154    }
1155
1156    pub fn delete_server_container(
1157        &self,
1158        adapter: Arc<CachedLspAdapter>,
1159        cx: &mut AppContext,
1160    ) -> Task<()> {
1161        log::info!("deleting server container");
1162
1163        let mut lock = self.lsp_binary_paths.lock();
1164        lock.remove(&adapter.name);
1165
1166        let download_dir = self
1167            .language_server_download_dir
1168            .clone()
1169            .expect("language server download directory has not been assigned before deleting server container");
1170
1171        cx.spawn(|_| async move {
1172            let container_dir = download_dir.join(adapter.name.0.as_ref());
1173            smol::fs::remove_dir_all(container_dir)
1174                .await
1175                .context("server container removal")
1176                .log_err();
1177        })
1178    }
1179
1180    pub fn next_language_server_id(&self) -> LanguageServerId {
1181        self.state.write().next_language_server_id()
1182    }
1183}
1184
1185impl LanguageRegistryState {
1186    fn next_language_server_id(&mut self) -> LanguageServerId {
1187        LanguageServerId(post_inc(&mut self.next_language_server_id))
1188    }
1189
1190    fn add(&mut self, language: Arc<Language>) {
1191        if let Some(theme) = self.theme.as_ref() {
1192            language.set_theme(theme.syntax());
1193        }
1194        self.languages.push(language);
1195        self.version += 1;
1196        *self.subscription.0.borrow_mut() = ();
1197    }
1198
1199    fn reload(&mut self) {
1200        self.languages.clear();
1201        self.version += 1;
1202        self.reload_count += 1;
1203        for language in &mut self.available_languages {
1204            language.loaded = false;
1205        }
1206        *self.subscription.0.borrow_mut() = ();
1207    }
1208
1209    /// Mark the given language a having been loaded, so that the
1210    /// language registry won't try to load it again.
1211    fn mark_language_loaded(&mut self, id: AvailableLanguageId) {
1212        for language in &mut self.available_languages {
1213            if language.id == id {
1214                language.loaded = true;
1215                break;
1216            }
1217        }
1218    }
1219}
1220
1221#[cfg(any(test, feature = "test-support"))]
1222impl Default for LanguageRegistry {
1223    fn default() -> Self {
1224        Self::test()
1225    }
1226}
1227
1228async fn get_binary(
1229    adapter: Arc<CachedLspAdapter>,
1230    language: Arc<Language>,
1231    delegate: Arc<dyn LspAdapterDelegate>,
1232    container_dir: Arc<Path>,
1233    statuses: LspBinaryStatusSender,
1234    mut cx: AsyncAppContext,
1235) -> Result<LanguageServerBinary> {
1236    if !container_dir.exists() {
1237        smol::fs::create_dir_all(&container_dir)
1238            .await
1239            .context("failed to create container directory")?;
1240    }
1241
1242    if let Some(task) = adapter.will_fetch_server(&delegate, &mut cx) {
1243        task.await?;
1244    }
1245
1246    let binary = fetch_latest_binary(
1247        adapter.clone(),
1248        language.clone(),
1249        delegate.as_ref(),
1250        &container_dir,
1251        statuses.clone(),
1252    )
1253    .await;
1254
1255    if let Err(error) = binary.as_ref() {
1256        if let Some(binary) = adapter
1257            .cached_server_binary(container_dir.to_path_buf(), delegate.as_ref())
1258            .await
1259        {
1260            statuses.send(language.clone(), LanguageServerBinaryStatus::Cached);
1261            return Ok(binary);
1262        } else {
1263            statuses.send(
1264                language.clone(),
1265                LanguageServerBinaryStatus::Failed {
1266                    error: format!("{:?}", error),
1267                },
1268            );
1269        }
1270    }
1271
1272    binary
1273}
1274
1275async fn fetch_latest_binary(
1276    adapter: Arc<CachedLspAdapter>,
1277    language: Arc<Language>,
1278    delegate: &dyn LspAdapterDelegate,
1279    container_dir: &Path,
1280    lsp_binary_statuses_tx: LspBinaryStatusSender,
1281) -> Result<LanguageServerBinary> {
1282    let container_dir: Arc<Path> = container_dir.into();
1283    lsp_binary_statuses_tx.send(
1284        language.clone(),
1285        LanguageServerBinaryStatus::CheckingForUpdate,
1286    );
1287
1288    let version_info = adapter.fetch_latest_server_version(delegate).await?;
1289    lsp_binary_statuses_tx.send(language.clone(), LanguageServerBinaryStatus::Downloading);
1290
1291    let binary = adapter
1292        .fetch_server_binary(version_info, container_dir.to_path_buf(), delegate)
1293        .await?;
1294    lsp_binary_statuses_tx.send(language.clone(), LanguageServerBinaryStatus::Downloaded);
1295
1296    Ok(binary)
1297}
1298
1299impl Language {
1300    pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
1301        Self {
1302            config,
1303            grammar: ts_language.map(|ts_language| {
1304                Arc::new(Grammar {
1305                    id: NEXT_GRAMMAR_ID.fetch_add(1, SeqCst),
1306                    highlights_query: None,
1307                    brackets_config: None,
1308                    outline_config: None,
1309                    embedding_config: None,
1310                    indents_config: None,
1311                    injection_config: None,
1312                    override_config: None,
1313                    redactions_config: None,
1314                    error_query: Query::new(&ts_language, "(ERROR) @error").unwrap(),
1315                    ts_language,
1316                    highlight_map: Default::default(),
1317                })
1318            }),
1319            adapters: Vec::new(),
1320
1321            #[cfg(any(test, feature = "test-support"))]
1322            fake_adapter: None,
1323        }
1324    }
1325
1326    pub fn lsp_adapters(&self) -> &[Arc<CachedLspAdapter>] {
1327        &self.adapters
1328    }
1329
1330    pub fn id(&self) -> Option<usize> {
1331        self.grammar.as_ref().map(|g| g.id)
1332    }
1333
1334    pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
1335        if let Some(query) = queries.highlights {
1336            self = self
1337                .with_highlights_query(query.as_ref())
1338                .context("Error loading highlights query")?;
1339        }
1340        if let Some(query) = queries.brackets {
1341            self = self
1342                .with_brackets_query(query.as_ref())
1343                .context("Error loading brackets query")?;
1344        }
1345        if let Some(query) = queries.indents {
1346            self = self
1347                .with_indents_query(query.as_ref())
1348                .context("Error loading indents query")?;
1349        }
1350        if let Some(query) = queries.outline {
1351            self = self
1352                .with_outline_query(query.as_ref())
1353                .context("Error loading outline query")?;
1354        }
1355        if let Some(query) = queries.embedding {
1356            self = self
1357                .with_embedding_query(query.as_ref())
1358                .context("Error loading embedding query")?;
1359        }
1360        if let Some(query) = queries.injections {
1361            self = self
1362                .with_injection_query(query.as_ref())
1363                .context("Error loading injection query")?;
1364        }
1365        if let Some(query) = queries.overrides {
1366            self = self
1367                .with_override_query(query.as_ref())
1368                .context("Error loading override query")?;
1369        }
1370        if let Some(query) = queries.redactions {
1371            self = self
1372                .with_redaction_query(query.as_ref())
1373                .context("Error loading redaction query")?;
1374        }
1375        Ok(self)
1376    }
1377
1378    pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1379        let grammar = self.grammar_mut();
1380        grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
1381        Ok(self)
1382    }
1383
1384    pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1385        let grammar = self.grammar_mut();
1386        let query = Query::new(&grammar.ts_language, source)?;
1387        let mut item_capture_ix = None;
1388        let mut name_capture_ix = None;
1389        let mut context_capture_ix = None;
1390        let mut extra_context_capture_ix = None;
1391        get_capture_indices(
1392            &query,
1393            &mut [
1394                ("item", &mut item_capture_ix),
1395                ("name", &mut name_capture_ix),
1396                ("context", &mut context_capture_ix),
1397                ("context.extra", &mut extra_context_capture_ix),
1398            ],
1399        );
1400        if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
1401            grammar.outline_config = Some(OutlineConfig {
1402                query,
1403                item_capture_ix,
1404                name_capture_ix,
1405                context_capture_ix,
1406                extra_context_capture_ix,
1407            });
1408        }
1409        Ok(self)
1410    }
1411
1412    pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
1413        let grammar = self.grammar_mut();
1414        let query = Query::new(&grammar.ts_language, source)?;
1415        let mut item_capture_ix = None;
1416        let mut name_capture_ix = None;
1417        let mut context_capture_ix = None;
1418        let mut collapse_capture_ix = None;
1419        let mut keep_capture_ix = None;
1420        get_capture_indices(
1421            &query,
1422            &mut [
1423                ("item", &mut item_capture_ix),
1424                ("name", &mut name_capture_ix),
1425                ("context", &mut context_capture_ix),
1426                ("keep", &mut keep_capture_ix),
1427                ("collapse", &mut collapse_capture_ix),
1428            ],
1429        );
1430        if let Some(item_capture_ix) = item_capture_ix {
1431            grammar.embedding_config = Some(EmbeddingConfig {
1432                query,
1433                item_capture_ix,
1434                name_capture_ix,
1435                context_capture_ix,
1436                collapse_capture_ix,
1437                keep_capture_ix,
1438            });
1439        }
1440        Ok(self)
1441    }
1442
1443    pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1444        let grammar = self.grammar_mut();
1445        let query = Query::new(&grammar.ts_language, source)?;
1446        let mut open_capture_ix = None;
1447        let mut close_capture_ix = None;
1448        get_capture_indices(
1449            &query,
1450            &mut [
1451                ("open", &mut open_capture_ix),
1452                ("close", &mut close_capture_ix),
1453            ],
1454        );
1455        if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1456            grammar.brackets_config = Some(BracketConfig {
1457                query,
1458                open_capture_ix,
1459                close_capture_ix,
1460            });
1461        }
1462        Ok(self)
1463    }
1464
1465    pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1466        let grammar = self.grammar_mut();
1467        let query = Query::new(&grammar.ts_language, source)?;
1468        let mut indent_capture_ix = None;
1469        let mut start_capture_ix = None;
1470        let mut end_capture_ix = None;
1471        let mut outdent_capture_ix = None;
1472        get_capture_indices(
1473            &query,
1474            &mut [
1475                ("indent", &mut indent_capture_ix),
1476                ("start", &mut start_capture_ix),
1477                ("end", &mut end_capture_ix),
1478                ("outdent", &mut outdent_capture_ix),
1479            ],
1480        );
1481        if let Some(indent_capture_ix) = indent_capture_ix {
1482            grammar.indents_config = Some(IndentConfig {
1483                query,
1484                indent_capture_ix,
1485                start_capture_ix,
1486                end_capture_ix,
1487                outdent_capture_ix,
1488            });
1489        }
1490        Ok(self)
1491    }
1492
1493    pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1494        let grammar = self.grammar_mut();
1495        let query = Query::new(&grammar.ts_language, source)?;
1496        let mut language_capture_ix = None;
1497        let mut content_capture_ix = None;
1498        get_capture_indices(
1499            &query,
1500            &mut [
1501                ("language", &mut language_capture_ix),
1502                ("content", &mut content_capture_ix),
1503            ],
1504        );
1505        let patterns = (0..query.pattern_count())
1506            .map(|ix| {
1507                let mut config = InjectionPatternConfig::default();
1508                for setting in query.property_settings(ix) {
1509                    match setting.key.as_ref() {
1510                        "language" => {
1511                            config.language = setting.value.clone();
1512                        }
1513                        "combined" => {
1514                            config.combined = true;
1515                        }
1516                        _ => {}
1517                    }
1518                }
1519                config
1520            })
1521            .collect();
1522        if let Some(content_capture_ix) = content_capture_ix {
1523            grammar.injection_config = Some(InjectionConfig {
1524                query,
1525                language_capture_ix,
1526                content_capture_ix,
1527                patterns,
1528            });
1529        }
1530        Ok(self)
1531    }
1532
1533    pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1534        let query = Query::new(&self.grammar_mut().ts_language, source)?;
1535
1536        let mut override_configs_by_id = HashMap::default();
1537        for (ix, name) in query.capture_names().iter().enumerate() {
1538            if !name.starts_with('_') {
1539                let value = self.config.overrides.remove(*name).unwrap_or_default();
1540                for server_name in &value.opt_into_language_servers {
1541                    if !self
1542                        .config
1543                        .scope_opt_in_language_servers
1544                        .contains(server_name)
1545                    {
1546                        util::debug_panic!("Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server");
1547                    }
1548                }
1549
1550                override_configs_by_id.insert(ix as u32, (name.to_string(), value));
1551            }
1552        }
1553
1554        if !self.config.overrides.is_empty() {
1555            let keys = self.config.overrides.keys().collect::<Vec<_>>();
1556            Err(anyhow!(
1557                "language {:?} has overrides in config not in query: {keys:?}",
1558                self.config.name
1559            ))?;
1560        }
1561
1562        for disabled_scope_name in self
1563            .config
1564            .brackets
1565            .disabled_scopes_by_bracket_ix
1566            .iter()
1567            .flatten()
1568        {
1569            if !override_configs_by_id
1570                .values()
1571                .any(|(scope_name, _)| scope_name == disabled_scope_name)
1572            {
1573                Err(anyhow!(
1574                    "language {:?} has overrides in config not in query: {disabled_scope_name:?}",
1575                    self.config.name
1576                ))?;
1577            }
1578        }
1579
1580        for (name, override_config) in override_configs_by_id.values_mut() {
1581            override_config.disabled_bracket_ixs = self
1582                .config
1583                .brackets
1584                .disabled_scopes_by_bracket_ix
1585                .iter()
1586                .enumerate()
1587                .filter_map(|(ix, disabled_scope_names)| {
1588                    if disabled_scope_names.contains(name) {
1589                        Some(ix as u16)
1590                    } else {
1591                        None
1592                    }
1593                })
1594                .collect();
1595        }
1596
1597        self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1598        self.grammar_mut().override_config = Some(OverrideConfig {
1599            query,
1600            values: override_configs_by_id,
1601        });
1602        Ok(self)
1603    }
1604
1605    pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1606        let grammar = self.grammar_mut();
1607        let query = Query::new(&grammar.ts_language, source)?;
1608        let mut redaction_capture_ix = None;
1609        get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1610
1611        if let Some(redaction_capture_ix) = redaction_capture_ix {
1612            grammar.redactions_config = Some(RedactionConfig {
1613                query,
1614                redaction_capture_ix,
1615            });
1616        }
1617
1618        Ok(self)
1619    }
1620
1621    fn grammar_mut(&mut self) -> &mut Grammar {
1622        Arc::get_mut(self.grammar.as_mut().unwrap()).unwrap()
1623    }
1624
1625    pub async fn with_lsp_adapters(mut self, lsp_adapters: Vec<Arc<dyn LspAdapter>>) -> Self {
1626        for adapter in lsp_adapters {
1627            self.adapters.push(CachedLspAdapter::new(adapter).await);
1628        }
1629        self
1630    }
1631
1632    #[cfg(any(test, feature = "test-support"))]
1633    pub async fn set_fake_lsp_adapter(
1634        &mut self,
1635        fake_lsp_adapter: Arc<FakeLspAdapter>,
1636    ) -> mpsc::UnboundedReceiver<lsp::FakeLanguageServer> {
1637        let (servers_tx, servers_rx) = mpsc::unbounded();
1638        self.fake_adapter = Some((servers_tx, fake_lsp_adapter.clone()));
1639        let adapter = CachedLspAdapter::new(Arc::new(fake_lsp_adapter)).await;
1640        self.adapters = vec![adapter];
1641        servers_rx
1642    }
1643
1644    pub fn name(&self) -> Arc<str> {
1645        self.config.name.clone()
1646    }
1647
1648    pub async fn disk_based_diagnostic_sources(&self) -> &[String] {
1649        match self.adapters.first().as_ref() {
1650            Some(adapter) => &adapter.disk_based_diagnostic_sources,
1651            None => &[],
1652        }
1653    }
1654
1655    pub async fn disk_based_diagnostics_progress_token(&self) -> Option<&str> {
1656        for adapter in &self.adapters {
1657            let token = adapter.disk_based_diagnostics_progress_token.as_deref();
1658            if token.is_some() {
1659                return token;
1660            }
1661        }
1662
1663        None
1664    }
1665
1666    pub async fn process_completion(self: &Arc<Self>, completion: &mut lsp::CompletionItem) {
1667        for adapter in &self.adapters {
1668            adapter.process_completion(completion).await;
1669        }
1670    }
1671
1672    pub async fn label_for_completion(
1673        self: &Arc<Self>,
1674        completion: &lsp::CompletionItem,
1675    ) -> Option<CodeLabel> {
1676        self.adapters
1677            .first()
1678            .as_ref()?
1679            .label_for_completion(completion, self)
1680            .await
1681    }
1682
1683    pub async fn label_for_symbol(
1684        self: &Arc<Self>,
1685        name: &str,
1686        kind: lsp::SymbolKind,
1687    ) -> Option<CodeLabel> {
1688        self.adapters
1689            .first()
1690            .as_ref()?
1691            .label_for_symbol(name, kind, self)
1692            .await
1693    }
1694
1695    pub fn highlight_text<'a>(
1696        self: &'a Arc<Self>,
1697        text: &'a Rope,
1698        range: Range<usize>,
1699    ) -> Vec<(Range<usize>, HighlightId)> {
1700        let mut result = Vec::new();
1701        if let Some(grammar) = &self.grammar {
1702            let tree = grammar.parse_text(text, None);
1703            let captures =
1704                SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1705                    grammar.highlights_query.as_ref()
1706                });
1707            let highlight_maps = vec![grammar.highlight_map()];
1708            let mut offset = 0;
1709            for chunk in BufferChunks::new(text, range, Some((captures, highlight_maps)), vec![]) {
1710                let end_offset = offset + chunk.text.len();
1711                if let Some(highlight_id) = chunk.syntax_highlight_id {
1712                    if !highlight_id.is_default() {
1713                        result.push((offset..end_offset, highlight_id));
1714                    }
1715                }
1716                offset = end_offset;
1717            }
1718        }
1719        result
1720    }
1721
1722    pub fn path_suffixes(&self) -> &[String] {
1723        &self.config.path_suffixes
1724    }
1725
1726    pub fn should_autoclose_before(&self, c: char) -> bool {
1727        c.is_whitespace() || self.config.autoclose_before.contains(c)
1728    }
1729
1730    pub fn set_theme(&self, theme: &SyntaxTheme) {
1731        if let Some(grammar) = self.grammar.as_ref() {
1732            if let Some(highlights_query) = &grammar.highlights_query {
1733                *grammar.highlight_map.lock() =
1734                    HighlightMap::new(highlights_query.capture_names(), theme);
1735            }
1736        }
1737    }
1738
1739    pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1740        self.grammar.as_ref()
1741    }
1742
1743    pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1744        LanguageScope {
1745            language: self.clone(),
1746            override_id: None,
1747        }
1748    }
1749
1750    pub fn prettier_parser_name(&self) -> Option<&str> {
1751        self.config.prettier_parser_name.as_deref()
1752    }
1753}
1754
1755impl LanguageScope {
1756    pub fn collapsed_placeholder(&self) -> &str {
1757        self.language.config.collapsed_placeholder.as_ref()
1758    }
1759
1760    /// Returns line prefix that is inserted in e.g. line continuations or
1761    /// in `toggle comments` action.
1762    pub fn line_comment_prefixes(&self) -> Option<&Vec<Arc<str>>> {
1763        Override::as_option(
1764            self.config_override().map(|o| &o.line_comments),
1765            Some(&self.language.config.line_comments),
1766        )
1767    }
1768
1769    pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1770        Override::as_option(
1771            self.config_override().map(|o| &o.block_comment),
1772            self.language.config.block_comment.as_ref(),
1773        )
1774        .map(|e| (&e.0, &e.1))
1775    }
1776
1777    /// Returns a list of language-specific word characters.
1778    ///
1779    /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1780    /// the purpose of actions like 'move to next word end` or whole-word search.
1781    /// It additionally accounts for language's additional word characters.
1782    pub fn word_characters(&self) -> Option<&HashSet<char>> {
1783        Override::as_option(
1784            self.config_override().map(|o| &o.word_characters),
1785            Some(&self.language.config.word_characters),
1786        )
1787    }
1788
1789    /// Returns a list of bracket pairs for a given language with an additional
1790    /// piece of information about whether the particular bracket pair is currently active for a given language.
1791    pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1792        let mut disabled_ids = self
1793            .config_override()
1794            .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1795        self.language
1796            .config
1797            .brackets
1798            .pairs
1799            .iter()
1800            .enumerate()
1801            .map(move |(ix, bracket)| {
1802                let mut is_enabled = true;
1803                if let Some(next_disabled_ix) = disabled_ids.first() {
1804                    if ix == *next_disabled_ix as usize {
1805                        disabled_ids = &disabled_ids[1..];
1806                        is_enabled = false;
1807                    }
1808                }
1809                (bracket, is_enabled)
1810            })
1811    }
1812
1813    pub fn should_autoclose_before(&self, c: char) -> bool {
1814        c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1815    }
1816
1817    pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1818        let config = &self.language.config;
1819        let opt_in_servers = &config.scope_opt_in_language_servers;
1820        if opt_in_servers.iter().any(|o| *o == *name.0) {
1821            if let Some(over) = self.config_override() {
1822                over.opt_into_language_servers.iter().any(|o| *o == *name.0)
1823            } else {
1824                false
1825            }
1826        } else {
1827            true
1828        }
1829    }
1830
1831    fn config_override(&self) -> Option<&LanguageConfigOverride> {
1832        let id = self.override_id?;
1833        let grammar = self.language.grammar.as_ref()?;
1834        let override_config = grammar.override_config.as_ref()?;
1835        override_config.values.get(&id).map(|e| &e.1)
1836    }
1837}
1838
1839impl Hash for Language {
1840    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1841        self.id().hash(state)
1842    }
1843}
1844
1845impl PartialEq for Language {
1846    fn eq(&self, other: &Self) -> bool {
1847        self.id().eq(&other.id())
1848    }
1849}
1850
1851impl Eq for Language {}
1852
1853impl Debug for Language {
1854    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1855        f.debug_struct("Language")
1856            .field("name", &self.config.name)
1857            .finish()
1858    }
1859}
1860
1861impl Grammar {
1862    pub fn id(&self) -> usize {
1863        self.id
1864    }
1865
1866    fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1867        PARSER.with(|parser| {
1868            let mut parser = parser.borrow_mut();
1869            parser
1870                .set_language(&self.ts_language)
1871                .expect("incompatible grammar");
1872            let mut chunks = text.chunks_in_range(0..text.len());
1873            parser
1874                .parse_with(
1875                    &mut move |offset, _| {
1876                        chunks.seek(offset);
1877                        chunks.next().unwrap_or("").as_bytes()
1878                    },
1879                    old_tree.as_ref(),
1880                )
1881                .unwrap()
1882        })
1883    }
1884
1885    pub fn highlight_map(&self) -> HighlightMap {
1886        self.highlight_map.lock().clone()
1887    }
1888
1889    pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1890        let capture_id = self
1891            .highlights_query
1892            .as_ref()?
1893            .capture_index_for_name(name)?;
1894        Some(self.highlight_map.lock().get(capture_id))
1895    }
1896}
1897
1898impl CodeLabel {
1899    pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1900        let mut result = Self {
1901            runs: Vec::new(),
1902            filter_range: 0..text.len(),
1903            text,
1904        };
1905        if let Some(filter_text) = filter_text {
1906            if let Some(ix) = result.text.find(filter_text) {
1907                result.filter_range = ix..ix + filter_text.len();
1908            }
1909        }
1910        result
1911    }
1912}
1913
1914#[cfg(any(test, feature = "test-support"))]
1915impl Default for FakeLspAdapter {
1916    fn default() -> Self {
1917        Self {
1918            name: "the-fake-language-server",
1919            capabilities: lsp::LanguageServer::full_capabilities(),
1920            initializer: None,
1921            disk_based_diagnostics_progress_token: None,
1922            initialization_options: None,
1923            disk_based_diagnostics_sources: Vec::new(),
1924            prettier_plugins: Vec::new(),
1925        }
1926    }
1927}
1928
1929#[cfg(any(test, feature = "test-support"))]
1930#[async_trait]
1931impl LspAdapter for Arc<FakeLspAdapter> {
1932    fn name(&self) -> LanguageServerName {
1933        LanguageServerName(self.name.into())
1934    }
1935
1936    fn short_name(&self) -> &'static str {
1937        "FakeLspAdapter"
1938    }
1939
1940    async fn fetch_latest_server_version(
1941        &self,
1942        _: &dyn LspAdapterDelegate,
1943    ) -> Result<Box<dyn 'static + Send + Any>> {
1944        unreachable!();
1945    }
1946
1947    async fn fetch_server_binary(
1948        &self,
1949        _: Box<dyn 'static + Send + Any>,
1950        _: PathBuf,
1951        _: &dyn LspAdapterDelegate,
1952    ) -> Result<LanguageServerBinary> {
1953        unreachable!();
1954    }
1955
1956    async fn cached_server_binary(
1957        &self,
1958        _: PathBuf,
1959        _: &dyn LspAdapterDelegate,
1960    ) -> Option<LanguageServerBinary> {
1961        unreachable!();
1962    }
1963
1964    async fn installation_test_binary(&self, _: PathBuf) -> Option<LanguageServerBinary> {
1965        unreachable!();
1966    }
1967
1968    fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
1969
1970    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
1971        self.disk_based_diagnostics_sources.clone()
1972    }
1973
1974    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
1975        self.disk_based_diagnostics_progress_token.clone()
1976    }
1977
1978    fn initialization_options(&self) -> Option<Value> {
1979        self.initialization_options.clone()
1980    }
1981
1982    fn prettier_plugins(&self) -> &[&'static str] {
1983        &self.prettier_plugins
1984    }
1985}
1986
1987fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
1988    for (ix, name) in query.capture_names().iter().enumerate() {
1989        for (capture_name, index) in captures.iter_mut() {
1990            if capture_name == name {
1991                **index = Some(ix as u32);
1992                break;
1993            }
1994        }
1995    }
1996}
1997
1998pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
1999    lsp::Position::new(point.row, point.column)
2000}
2001
2002pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
2003    Unclipped(PointUtf16::new(point.line, point.character))
2004}
2005
2006pub fn range_to_lsp(range: Range<PointUtf16>) -> lsp::Range {
2007    lsp::Range {
2008        start: point_to_lsp(range.start),
2009        end: point_to_lsp(range.end),
2010    }
2011}
2012
2013pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
2014    let mut start = point_from_lsp(range.start);
2015    let mut end = point_from_lsp(range.end);
2016    if start > end {
2017        mem::swap(&mut start, &mut end);
2018    }
2019    start..end
2020}
2021
2022#[cfg(test)]
2023mod tests {
2024    use super::*;
2025    use gpui::TestAppContext;
2026
2027    #[gpui::test(iterations = 10)]
2028    async fn test_first_line_pattern(cx: &mut TestAppContext) {
2029        let mut languages = LanguageRegistry::test();
2030
2031        languages.set_executor(cx.executor());
2032        let languages = Arc::new(languages);
2033        languages.register(
2034            "/javascript",
2035            LanguageConfig {
2036                name: "JavaScript".into(),
2037                path_suffixes: vec!["js".into()],
2038                first_line_pattern: Some(Regex::new(r"\bnode\b").unwrap()),
2039                ..Default::default()
2040            },
2041            tree_sitter_typescript::language_tsx(),
2042            vec![],
2043            |_| Default::default(),
2044        );
2045
2046        languages
2047            .language_for_file("the/script", None)
2048            .await
2049            .unwrap_err();
2050        languages
2051            .language_for_file("the/script", Some(&"nothing".into()))
2052            .await
2053            .unwrap_err();
2054        assert_eq!(
2055            languages
2056                .language_for_file("the/script", Some(&"#!/bin/env node".into()))
2057                .await
2058                .unwrap()
2059                .name()
2060                .as_ref(),
2061            "JavaScript"
2062        );
2063    }
2064
2065    #[gpui::test(iterations = 10)]
2066    async fn test_language_loading(cx: &mut TestAppContext) {
2067        let mut languages = LanguageRegistry::test();
2068        languages.set_executor(cx.executor());
2069        let languages = Arc::new(languages);
2070        languages.register(
2071            "/JSON",
2072            LanguageConfig {
2073                name: "JSON".into(),
2074                path_suffixes: vec!["json".into()],
2075                ..Default::default()
2076            },
2077            tree_sitter_json::language(),
2078            vec![],
2079            |_| Default::default(),
2080        );
2081        languages.register(
2082            "/rust",
2083            LanguageConfig {
2084                name: "Rust".into(),
2085                path_suffixes: vec!["rs".into()],
2086                ..Default::default()
2087            },
2088            tree_sitter_rust::language(),
2089            vec![],
2090            |_| Default::default(),
2091        );
2092        assert_eq!(
2093            languages.language_names(),
2094            &[
2095                "JSON".to_string(),
2096                "Plain Text".to_string(),
2097                "Rust".to_string(),
2098            ]
2099        );
2100
2101        let rust1 = languages.language_for_name("Rust");
2102        let rust2 = languages.language_for_name("Rust");
2103
2104        // Ensure language is still listed even if it's being loaded.
2105        assert_eq!(
2106            languages.language_names(),
2107            &[
2108                "JSON".to_string(),
2109                "Plain Text".to_string(),
2110                "Rust".to_string(),
2111            ]
2112        );
2113
2114        let (rust1, rust2) = futures::join!(rust1, rust2);
2115        assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
2116
2117        // Ensure language is still listed even after loading it.
2118        assert_eq!(
2119            languages.language_names(),
2120            &[
2121                "JSON".to_string(),
2122                "Plain Text".to_string(),
2123                "Rust".to_string(),
2124            ]
2125        );
2126
2127        // Loading an unknown language returns an error.
2128        assert!(languages.language_for_name("Unknown").await.is_err());
2129    }
2130}