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