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