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