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