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