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