language.rs

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