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