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 manifest;
  15mod outline;
  16pub mod proto;
  17mod syntax_map;
  18mod task_context;
  19mod text_diff;
  20mod toolchain;
  21
  22#[cfg(test)]
  23pub mod buffer_tests;
  24
  25pub use crate::language_settings::EditPredictionsMode;
  26use crate::language_settings::SoftWrap;
  27use anyhow::{Context as _, Result};
  28use async_trait::async_trait;
  29use collections::{HashMap, HashSet, IndexSet};
  30use futures::Future;
  31use gpui::{App, AsyncApp, Entity, SharedString};
  32pub use highlight_map::HighlightMap;
  33use http_client::HttpClient;
  34pub use language_registry::{
  35    LanguageName, LanguageServerStatusUpdate, LoadedLanguage, ServerHealth,
  36};
  37use lsp::{CodeActionKind, InitializeParams, LanguageServerBinary, LanguageServerBinaryOptions};
  38pub use manifest::{ManifestDelegate, ManifestName, ManifestProvider, ManifestQuery};
  39use parking_lot::Mutex;
  40use regex::Regex;
  41use schemars::{JsonSchema, SchemaGenerator, json_schema};
  42use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
  43use serde_json::Value;
  44use settings::WorktreeId;
  45use smol::future::FutureExt as _;
  46use std::num::NonZeroU32;
  47use std::{
  48    ffi::OsStr,
  49    fmt::Debug,
  50    hash::Hash,
  51    mem,
  52    ops::{DerefMut, Range},
  53    path::{Path, PathBuf},
  54    pin::Pin,
  55    str,
  56    sync::{
  57        Arc, LazyLock,
  58        atomic::{AtomicU64, AtomicUsize, Ordering::SeqCst},
  59    },
  60};
  61use syntax_map::{QueryCursorHandle, SyntaxSnapshot};
  62use task::RunnableTag;
  63pub use task_context::{ContextLocation, ContextProvider, RunnableRange};
  64pub use text_diff::{
  65    DiffOptions, apply_diff_patch, line_diff, text_diff, text_diff_with_options, unified_diff,
  66};
  67use theme::SyntaxTheme;
  68pub use toolchain::{
  69    LanguageToolchainStore, LocalLanguageToolchainStore, Toolchain, ToolchainList, ToolchainLister,
  70    ToolchainMetadata, ToolchainScope,
  71};
  72use tree_sitter::{self, Query, QueryCursor, WasmStore, wasmtime};
  73use util::serde::default_true;
  74
  75pub use buffer::Operation;
  76pub use buffer::*;
  77pub use diagnostic_set::{DiagnosticEntry, DiagnosticGroup};
  78pub use language_registry::{
  79    AvailableLanguage, BinaryStatus, LanguageNotFound, LanguageQueries, LanguageRegistry,
  80    QUERY_FILENAME_PREFIXES,
  81};
  82pub use lsp::{LanguageServerId, LanguageServerName};
  83pub use outline::*;
  84pub use syntax_map::{
  85    OwnedSyntaxLayer, SyntaxLayer, SyntaxMapMatches, ToTreeSitterPoint, TreeSitterOptions,
  86};
  87pub use text::{AnchorRangeExt, LineEnding};
  88pub use tree_sitter::{Node, Parser, Tree, TreeCursor};
  89
  90/// Initializes the `language` crate.
  91///
  92/// This should be called before making use of items from the create.
  93pub fn init(cx: &mut App) {
  94    language_settings::init(cx);
  95}
  96
  97static QUERY_CURSORS: Mutex<Vec<QueryCursor>> = Mutex::new(vec![]);
  98static PARSERS: Mutex<Vec<Parser>> = Mutex::new(vec![]);
  99
 100pub fn with_parser<F, R>(func: F) -> R
 101where
 102    F: FnOnce(&mut Parser) -> R,
 103{
 104    let mut parser = PARSERS.lock().pop().unwrap_or_else(|| {
 105        let mut parser = Parser::new();
 106        parser
 107            .set_wasm_store(WasmStore::new(&WASM_ENGINE).unwrap())
 108            .unwrap();
 109        parser
 110    });
 111    parser.set_included_ranges(&[]).unwrap();
 112    let result = func(&mut parser);
 113    PARSERS.lock().push(parser);
 114    result
 115}
 116
 117pub fn with_query_cursor<F, R>(func: F) -> R
 118where
 119    F: FnOnce(&mut QueryCursor) -> R,
 120{
 121    let mut cursor = QueryCursorHandle::new();
 122    func(cursor.deref_mut())
 123}
 124
 125static NEXT_LANGUAGE_ID: AtomicUsize = AtomicUsize::new(0);
 126static NEXT_GRAMMAR_ID: AtomicUsize = AtomicUsize::new(0);
 127static WASM_ENGINE: LazyLock<wasmtime::Engine> = LazyLock::new(|| {
 128    wasmtime::Engine::new(&wasmtime::Config::new()).expect("Failed to create Wasmtime engine")
 129});
 130
 131/// A shared grammar for plain text, exposed for reuse by downstream crates.
 132pub static PLAIN_TEXT: LazyLock<Arc<Language>> = LazyLock::new(|| {
 133    Arc::new(Language::new(
 134        LanguageConfig {
 135            name: "Plain Text".into(),
 136            soft_wrap: Some(SoftWrap::EditorWidth),
 137            matcher: LanguageMatcher {
 138                path_suffixes: vec!["txt".to_owned()],
 139                first_line_pattern: None,
 140            },
 141            ..Default::default()
 142        },
 143        None,
 144    ))
 145});
 146
 147/// Types that represent a position in a buffer, and can be converted into
 148/// an LSP position, to send to a language server.
 149pub trait ToLspPosition {
 150    /// Converts the value into an LSP position.
 151    fn to_lsp_position(self) -> lsp::Position;
 152}
 153
 154#[derive(Debug, Clone, PartialEq, Eq, Hash)]
 155pub struct Location {
 156    pub buffer: Entity<Buffer>,
 157    pub range: Range<Anchor>,
 158}
 159
 160type ServerBinaryCache = futures::lock::Mutex<Option<(bool, LanguageServerBinary)>>;
 161
 162/// Represents a Language Server, with certain cached sync properties.
 163/// Uses [`LspAdapter`] under the hood, but calls all 'static' methods
 164/// once at startup, and caches the results.
 165pub struct CachedLspAdapter {
 166    pub name: LanguageServerName,
 167    pub disk_based_diagnostic_sources: Vec<String>,
 168    pub disk_based_diagnostics_progress_token: Option<String>,
 169    language_ids: HashMap<LanguageName, String>,
 170    pub adapter: Arc<dyn LspAdapter>,
 171    pub reinstall_attempt_count: AtomicU64,
 172    cached_binary: ServerBinaryCache,
 173}
 174
 175impl Debug for CachedLspAdapter {
 176    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 177        f.debug_struct("CachedLspAdapter")
 178            .field("name", &self.name)
 179            .field(
 180                "disk_based_diagnostic_sources",
 181                &self.disk_based_diagnostic_sources,
 182            )
 183            .field(
 184                "disk_based_diagnostics_progress_token",
 185                &self.disk_based_diagnostics_progress_token,
 186            )
 187            .field("language_ids", &self.language_ids)
 188            .field("reinstall_attempt_count", &self.reinstall_attempt_count)
 189            .finish_non_exhaustive()
 190    }
 191}
 192
 193impl CachedLspAdapter {
 194    pub fn new(adapter: Arc<dyn LspAdapter>) -> Arc<Self> {
 195        let name = adapter.name();
 196        let disk_based_diagnostic_sources = adapter.disk_based_diagnostic_sources();
 197        let disk_based_diagnostics_progress_token = adapter.disk_based_diagnostics_progress_token();
 198        let language_ids = adapter.language_ids();
 199
 200        Arc::new(CachedLspAdapter {
 201            name,
 202            disk_based_diagnostic_sources,
 203            disk_based_diagnostics_progress_token,
 204            language_ids,
 205            adapter,
 206            cached_binary: Default::default(),
 207            reinstall_attempt_count: AtomicU64::new(0),
 208        })
 209    }
 210
 211    pub fn name(&self) -> LanguageServerName {
 212        self.adapter.name()
 213    }
 214
 215    pub async fn get_language_server_command(
 216        self: Arc<Self>,
 217        delegate: Arc<dyn LspAdapterDelegate>,
 218        toolchains: Option<Toolchain>,
 219        binary_options: LanguageServerBinaryOptions,
 220        cx: &mut AsyncApp,
 221    ) -> Result<LanguageServerBinary> {
 222        let mut cached_binary = self.cached_binary.lock().await;
 223        self.adapter
 224            .clone()
 225            .get_language_server_command(
 226                delegate,
 227                toolchains,
 228                binary_options,
 229                &mut cached_binary,
 230                cx,
 231            )
 232            .await
 233    }
 234
 235    pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
 236        self.adapter.code_action_kinds()
 237    }
 238
 239    pub fn process_diagnostics(
 240        &self,
 241        params: &mut lsp::PublishDiagnosticsParams,
 242        server_id: LanguageServerId,
 243        existing_diagnostics: Option<&'_ Buffer>,
 244    ) {
 245        self.adapter
 246            .process_diagnostics(params, server_id, existing_diagnostics)
 247    }
 248
 249    pub fn retain_old_diagnostic(&self, previous_diagnostic: &Diagnostic, cx: &App) -> bool {
 250        self.adapter.retain_old_diagnostic(previous_diagnostic, cx)
 251    }
 252
 253    pub fn underline_diagnostic(&self, diagnostic: &lsp::Diagnostic) -> bool {
 254        self.adapter.underline_diagnostic(diagnostic)
 255    }
 256
 257    pub fn diagnostic_message_to_markdown(&self, message: &str) -> Option<String> {
 258        self.adapter.diagnostic_message_to_markdown(message)
 259    }
 260
 261    pub async fn process_completions(&self, completion_items: &mut [lsp::CompletionItem]) {
 262        self.adapter.process_completions(completion_items).await
 263    }
 264
 265    pub async fn labels_for_completions(
 266        &self,
 267        completion_items: &[lsp::CompletionItem],
 268        language: &Arc<Language>,
 269    ) -> Result<Vec<Option<CodeLabel>>> {
 270        self.adapter
 271            .clone()
 272            .labels_for_completions(completion_items, language)
 273            .await
 274    }
 275
 276    pub async fn labels_for_symbols(
 277        &self,
 278        symbols: &[(String, lsp::SymbolKind)],
 279        language: &Arc<Language>,
 280    ) -> Result<Vec<Option<CodeLabel>>> {
 281        self.adapter
 282            .clone()
 283            .labels_for_symbols(symbols, language)
 284            .await
 285    }
 286
 287    pub fn language_id(&self, language_name: &LanguageName) -> String {
 288        self.language_ids
 289            .get(language_name)
 290            .cloned()
 291            .unwrap_or_else(|| language_name.lsp_id())
 292    }
 293}
 294
 295/// [`LspAdapterDelegate`] allows [`LspAdapter]` implementations to interface with the application
 296// e.g. to display a notification or fetch data from the web.
 297#[async_trait]
 298pub trait LspAdapterDelegate: Send + Sync {
 299    fn show_notification(&self, message: &str, cx: &mut App);
 300    fn http_client(&self) -> Arc<dyn HttpClient>;
 301    fn worktree_id(&self) -> WorktreeId;
 302    fn worktree_root_path(&self) -> &Path;
 303    fn update_status(&self, language: LanguageServerName, status: BinaryStatus);
 304    fn registered_lsp_adapters(&self) -> Vec<Arc<dyn LspAdapter>>;
 305    async fn language_server_download_dir(&self, name: &LanguageServerName) -> Option<Arc<Path>>;
 306
 307    async fn npm_package_installed_version(
 308        &self,
 309        package_name: &str,
 310    ) -> Result<Option<(PathBuf, String)>>;
 311    async fn which(&self, command: &OsStr) -> Option<PathBuf>;
 312    async fn shell_env(&self) -> HashMap<String, String>;
 313    async fn read_text_file(&self, path: PathBuf) -> Result<String>;
 314    async fn try_exec(&self, binary: LanguageServerBinary) -> Result<()>;
 315}
 316
 317#[async_trait(?Send)]
 318pub trait LspAdapter: 'static + Send + Sync + DynLspInstaller {
 319    fn name(&self) -> LanguageServerName;
 320
 321    fn process_diagnostics(
 322        &self,
 323        _: &mut lsp::PublishDiagnosticsParams,
 324        _: LanguageServerId,
 325        _: Option<&'_ Buffer>,
 326    ) {
 327    }
 328
 329    /// When processing new `lsp::PublishDiagnosticsParams` diagnostics, whether to retain previous one(s) or not.
 330    fn retain_old_diagnostic(&self, _previous_diagnostic: &Diagnostic, _cx: &App) -> bool {
 331        false
 332    }
 333
 334    /// Whether to underline a given diagnostic or not, when rendering in the editor.
 335    ///
 336    /// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#diagnosticTag
 337    /// states that
 338    /// > Clients are allowed to render diagnostics with this tag faded out instead of having an error squiggle.
 339    /// for the unnecessary diagnostics, so do not underline them.
 340    fn underline_diagnostic(&self, _diagnostic: &lsp::Diagnostic) -> bool {
 341        true
 342    }
 343
 344    /// Post-processes completions provided by the language server.
 345    async fn process_completions(&self, _: &mut [lsp::CompletionItem]) {}
 346
 347    fn diagnostic_message_to_markdown(&self, _message: &str) -> Option<String> {
 348        None
 349    }
 350
 351    async fn labels_for_completions(
 352        self: Arc<Self>,
 353        completions: &[lsp::CompletionItem],
 354        language: &Arc<Language>,
 355    ) -> Result<Vec<Option<CodeLabel>>> {
 356        let mut labels = Vec::new();
 357        for (ix, completion) in completions.iter().enumerate() {
 358            let label = self.label_for_completion(completion, language).await;
 359            if let Some(label) = label {
 360                labels.resize(ix + 1, None);
 361                *labels.last_mut().unwrap() = Some(label);
 362            }
 363        }
 364        Ok(labels)
 365    }
 366
 367    async fn label_for_completion(
 368        &self,
 369        _: &lsp::CompletionItem,
 370        _: &Arc<Language>,
 371    ) -> Option<CodeLabel> {
 372        None
 373    }
 374
 375    async fn labels_for_symbols(
 376        self: Arc<Self>,
 377        symbols: &[(String, lsp::SymbolKind)],
 378        language: &Arc<Language>,
 379    ) -> Result<Vec<Option<CodeLabel>>> {
 380        let mut labels = Vec::new();
 381        for (ix, (name, kind)) in symbols.iter().enumerate() {
 382            let label = self.label_for_symbol(name, *kind, language).await;
 383            if let Some(label) = label {
 384                labels.resize(ix + 1, None);
 385                *labels.last_mut().unwrap() = Some(label);
 386            }
 387        }
 388        Ok(labels)
 389    }
 390
 391    async fn label_for_symbol(
 392        &self,
 393        _: &str,
 394        _: lsp::SymbolKind,
 395        _: &Arc<Language>,
 396    ) -> Option<CodeLabel> {
 397        None
 398    }
 399
 400    /// Returns initialization options that are going to be sent to a LSP server as a part of [`lsp::InitializeParams`]
 401    async fn initialization_options(
 402        self: Arc<Self>,
 403        _: &Arc<dyn LspAdapterDelegate>,
 404    ) -> Result<Option<Value>> {
 405        Ok(None)
 406    }
 407
 408    async fn workspace_configuration(
 409        self: Arc<Self>,
 410        _: &Arc<dyn LspAdapterDelegate>,
 411        _: Option<Toolchain>,
 412        _cx: &mut AsyncApp,
 413    ) -> Result<Value> {
 414        Ok(serde_json::json!({}))
 415    }
 416
 417    async fn additional_initialization_options(
 418        self: Arc<Self>,
 419        _target_language_server_id: LanguageServerName,
 420        _: &Arc<dyn LspAdapterDelegate>,
 421    ) -> Result<Option<Value>> {
 422        Ok(None)
 423    }
 424
 425    async fn additional_workspace_configuration(
 426        self: Arc<Self>,
 427        _target_language_server_id: LanguageServerName,
 428        _: &Arc<dyn LspAdapterDelegate>,
 429        _cx: &mut AsyncApp,
 430    ) -> Result<Option<Value>> {
 431        Ok(None)
 432    }
 433
 434    /// Returns a list of code actions supported by a given LspAdapter
 435    fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
 436        None
 437    }
 438
 439    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
 440        Default::default()
 441    }
 442
 443    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
 444        None
 445    }
 446
 447    fn language_ids(&self) -> HashMap<LanguageName, String> {
 448        HashMap::default()
 449    }
 450
 451    /// Support custom initialize params.
 452    fn prepare_initialize_params(
 453        &self,
 454        original: InitializeParams,
 455        _: &App,
 456    ) -> Result<InitializeParams> {
 457        Ok(original)
 458    }
 459
 460    /// Method only implemented by the default JSON language server adapter.
 461    /// Used to provide dynamic reloading of the JSON schemas used to
 462    /// provide autocompletion and diagnostics in Zed setting and keybind
 463    /// files
 464    fn is_primary_zed_json_schema_adapter(&self) -> bool {
 465        false
 466    }
 467
 468    /// Method only implemented by the default JSON language server adapter.
 469    /// Used to clear the cache of JSON schemas that are used to provide
 470    /// autocompletion and diagnostics in Zed settings and keybinds files.
 471    /// Should not be called unless the callee is sure that
 472    /// `Self::is_primary_zed_json_schema_adapter` returns `true`
 473    async fn clear_zed_json_schema_cache(&self) {
 474        unreachable!(
 475            "Not implemented for this adapter. This method should only be called on the default JSON language server adapter"
 476        );
 477    }
 478
 479    /// True for the extension adapter and false otherwise.
 480    fn is_extension(&self) -> bool {
 481        false
 482    }
 483}
 484
 485pub trait LspInstaller {
 486    type BinaryVersion;
 487    fn check_if_user_installed(
 488        &self,
 489        _: &dyn LspAdapterDelegate,
 490        _: Option<Toolchain>,
 491        _: &AsyncApp,
 492    ) -> impl Future<Output = Option<LanguageServerBinary>> {
 493        async { None }
 494    }
 495
 496    fn fetch_latest_server_version(
 497        &self,
 498        delegate: &dyn LspAdapterDelegate,
 499        pre_release: bool,
 500        cx: &mut AsyncApp,
 501    ) -> impl Future<Output = Result<Self::BinaryVersion>>;
 502
 503    fn check_if_version_installed(
 504        &self,
 505        _version: &Self::BinaryVersion,
 506        _container_dir: &PathBuf,
 507        _delegate: &dyn LspAdapterDelegate,
 508    ) -> impl Future<Output = Option<LanguageServerBinary>> {
 509        async { None }
 510    }
 511
 512    fn fetch_server_binary(
 513        &self,
 514        latest_version: Self::BinaryVersion,
 515        container_dir: PathBuf,
 516        delegate: &dyn LspAdapterDelegate,
 517    ) -> impl Future<Output = Result<LanguageServerBinary>>;
 518
 519    fn cached_server_binary(
 520        &self,
 521        container_dir: PathBuf,
 522        delegate: &dyn LspAdapterDelegate,
 523    ) -> impl Future<Output = Option<LanguageServerBinary>>;
 524}
 525
 526#[async_trait(?Send)]
 527pub trait DynLspInstaller {
 528    async fn try_fetch_server_binary(
 529        &self,
 530        delegate: &Arc<dyn LspAdapterDelegate>,
 531        container_dir: PathBuf,
 532        pre_release: bool,
 533        cx: &mut AsyncApp,
 534    ) -> Result<LanguageServerBinary>;
 535    fn get_language_server_command<'a>(
 536        self: Arc<Self>,
 537        delegate: Arc<dyn LspAdapterDelegate>,
 538        toolchains: Option<Toolchain>,
 539        binary_options: LanguageServerBinaryOptions,
 540        cached_binary: &'a mut Option<(bool, LanguageServerBinary)>,
 541        cx: &'a mut AsyncApp,
 542    ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>>;
 543}
 544
 545#[async_trait(?Send)]
 546impl<LI, BinaryVersion> DynLspInstaller for LI
 547where
 548    LI: LspInstaller<BinaryVersion = BinaryVersion> + LspAdapter,
 549{
 550    async fn try_fetch_server_binary(
 551        &self,
 552        delegate: &Arc<dyn LspAdapterDelegate>,
 553        container_dir: PathBuf,
 554        pre_release: bool,
 555        cx: &mut AsyncApp,
 556    ) -> Result<LanguageServerBinary> {
 557        let name = self.name();
 558
 559        log::debug!("fetching latest version of language server {:?}", name.0);
 560        delegate.update_status(name.clone(), BinaryStatus::CheckingForUpdate);
 561
 562        let latest_version = self
 563            .fetch_latest_server_version(delegate.as_ref(), pre_release, cx)
 564            .await?;
 565
 566        if let Some(binary) = self
 567            .check_if_version_installed(&latest_version, &container_dir, delegate.as_ref())
 568            .await
 569        {
 570            log::debug!("language server {:?} is already installed", name.0);
 571            delegate.update_status(name.clone(), BinaryStatus::None);
 572            Ok(binary)
 573        } else {
 574            log::debug!("downloading language server {:?}", name.0);
 575            delegate.update_status(name.clone(), BinaryStatus::Downloading);
 576            let binary = self
 577                .fetch_server_binary(latest_version, container_dir, delegate.as_ref())
 578                .await;
 579
 580            delegate.update_status(name.clone(), BinaryStatus::None);
 581            binary
 582        }
 583    }
 584    fn get_language_server_command<'a>(
 585        self: Arc<Self>,
 586        delegate: Arc<dyn LspAdapterDelegate>,
 587        toolchain: Option<Toolchain>,
 588        binary_options: LanguageServerBinaryOptions,
 589        cached_binary: &'a mut Option<(bool, LanguageServerBinary)>,
 590        cx: &'a mut AsyncApp,
 591    ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
 592        async move {
 593            // First we check whether the adapter can give us a user-installed binary.
 594            // If so, we do *not* want to cache that, because each worktree might give us a different
 595            // binary:
 596            //
 597            //      worktree 1: user-installed at `.bin/gopls`
 598            //      worktree 2: user-installed at `~/bin/gopls`
 599            //      worktree 3: no gopls found in PATH -> fallback to Zed installation
 600            //
 601            // We only want to cache when we fall back to the global one,
 602            // because we don't want to download and overwrite our global one
 603            // for each worktree we might have open.
 604            if binary_options.allow_path_lookup
 605                && let Some(binary) = self
 606                    .check_if_user_installed(delegate.as_ref(), toolchain, cx)
 607                    .await
 608            {
 609                log::info!(
 610                    "found user-installed language server for {}. path: {:?}, arguments: {:?}",
 611                    self.name().0,
 612                    binary.path,
 613                    binary.arguments
 614                );
 615                return Ok(binary);
 616            }
 617
 618            anyhow::ensure!(
 619                binary_options.allow_binary_download,
 620                "downloading language servers disabled"
 621            );
 622
 623            if let Some((pre_release, cached_binary)) = cached_binary
 624                && *pre_release == binary_options.pre_release
 625            {
 626                return Ok(cached_binary.clone());
 627            }
 628
 629            let Some(container_dir) = delegate.language_server_download_dir(&self.name()).await
 630            else {
 631                anyhow::bail!("no language server download dir defined")
 632            };
 633
 634            let mut binary = self
 635                .try_fetch_server_binary(
 636                    &delegate,
 637                    container_dir.to_path_buf(),
 638                    binary_options.pre_release,
 639                    cx,
 640                )
 641                .await;
 642
 643            if let Err(error) = binary.as_ref() {
 644                if let Some(prev_downloaded_binary) = self
 645                    .cached_server_binary(container_dir.to_path_buf(), delegate.as_ref())
 646                    .await
 647                {
 648                    log::info!(
 649                        "failed to fetch newest version of language server {:?}. \
 650                        error: {:?}, falling back to using {:?}",
 651                        self.name(),
 652                        error,
 653                        prev_downloaded_binary.path
 654                    );
 655                    binary = Ok(prev_downloaded_binary);
 656                } else {
 657                    delegate.update_status(
 658                        self.name(),
 659                        BinaryStatus::Failed {
 660                            error: format!("{error:?}"),
 661                        },
 662                    );
 663                }
 664            }
 665
 666            if let Ok(binary) = &binary {
 667                *cached_binary = Some((binary_options.pre_release, binary.clone()));
 668            }
 669
 670            binary
 671        }
 672        .boxed_local()
 673    }
 674}
 675
 676#[derive(Clone, Debug, Default, PartialEq, Eq)]
 677pub struct CodeLabel {
 678    /// The text to display.
 679    pub text: String,
 680    /// Syntax highlighting runs.
 681    pub runs: Vec<(Range<usize>, HighlightId)>,
 682    /// The portion of the text that should be used in fuzzy filtering.
 683    pub filter_range: Range<usize>,
 684}
 685
 686#[derive(Clone, Deserialize, JsonSchema)]
 687pub struct LanguageConfig {
 688    /// Human-readable name of the language.
 689    pub name: LanguageName,
 690    /// The name of this language for a Markdown code fence block
 691    pub code_fence_block_name: Option<Arc<str>>,
 692    // The name of the grammar in a WASM bundle (experimental).
 693    pub grammar: Option<Arc<str>>,
 694    /// The criteria for matching this language to a given file.
 695    #[serde(flatten)]
 696    pub matcher: LanguageMatcher,
 697    /// List of bracket types in a language.
 698    #[serde(default)]
 699    pub brackets: BracketPairConfig,
 700    /// If set to true, auto indentation uses last non empty line to determine
 701    /// the indentation level for a new line.
 702    #[serde(default = "auto_indent_using_last_non_empty_line_default")]
 703    pub auto_indent_using_last_non_empty_line: bool,
 704    // Whether indentation of pasted content should be adjusted based on the context.
 705    #[serde(default)]
 706    pub auto_indent_on_paste: Option<bool>,
 707    /// A regex that is used to determine whether the indentation level should be
 708    /// increased in the following line.
 709    #[serde(default, deserialize_with = "deserialize_regex")]
 710    #[schemars(schema_with = "regex_json_schema")]
 711    pub increase_indent_pattern: Option<Regex>,
 712    /// A regex that is used to determine whether the indentation level should be
 713    /// decreased in the following line.
 714    #[serde(default, deserialize_with = "deserialize_regex")]
 715    #[schemars(schema_with = "regex_json_schema")]
 716    pub decrease_indent_pattern: Option<Regex>,
 717    /// A list of rules for decreasing indentation. Each rule pairs a regex with a set of valid
 718    /// "block-starting" tokens. When a line matches a pattern, its indentation is aligned with
 719    /// the most recent line that began with a corresponding token. This enables context-aware
 720    /// outdenting, like aligning an `else` with its `if`.
 721    #[serde(default)]
 722    pub decrease_indent_patterns: Vec<DecreaseIndentConfig>,
 723    /// A list of characters that trigger the automatic insertion of a closing
 724    /// bracket when they immediately precede the point where an opening
 725    /// bracket is inserted.
 726    #[serde(default)]
 727    pub autoclose_before: String,
 728    /// A placeholder used internally by Semantic Index.
 729    #[serde(default)]
 730    pub collapsed_placeholder: String,
 731    /// A line comment string that is inserted in e.g. `toggle comments` action.
 732    /// A language can have multiple flavours of line comments. All of the provided line comments are
 733    /// used for comment continuations on the next line, but only the first one is used for Editor::ToggleComments.
 734    #[serde(default)]
 735    pub line_comments: Vec<Arc<str>>,
 736    /// Delimiters and configuration for recognizing and formatting block comments.
 737    #[serde(default)]
 738    pub block_comment: Option<BlockCommentConfig>,
 739    /// Delimiters and configuration for recognizing and formatting documentation comments.
 740    #[serde(default, alias = "documentation")]
 741    pub documentation_comment: Option<BlockCommentConfig>,
 742    /// A list of additional regex patterns that should be treated as prefixes
 743    /// for creating boundaries during rewrapping, ensuring content from one
 744    /// prefixed section doesn't merge with another (e.g., markdown list items).
 745    /// By default, Zed treats as paragraph and comment prefixes as boundaries.
 746    #[serde(default, deserialize_with = "deserialize_regex_vec")]
 747    #[schemars(schema_with = "regex_vec_json_schema")]
 748    pub rewrap_prefixes: Vec<Regex>,
 749    /// A list of language servers that are allowed to run on subranges of a given language.
 750    #[serde(default)]
 751    pub scope_opt_in_language_servers: Vec<LanguageServerName>,
 752    #[serde(default)]
 753    pub overrides: HashMap<String, LanguageConfigOverride>,
 754    /// A list of characters that Zed should treat as word characters for the
 755    /// purpose of features that operate on word boundaries, like 'move to next word end'
 756    /// or a whole-word search in buffer search.
 757    #[serde(default)]
 758    pub word_characters: HashSet<char>,
 759    /// Whether to indent lines using tab characters, as opposed to multiple
 760    /// spaces.
 761    #[serde(default)]
 762    pub hard_tabs: Option<bool>,
 763    /// How many columns a tab should occupy.
 764    #[serde(default)]
 765    pub tab_size: Option<NonZeroU32>,
 766    /// How to soft-wrap long lines of text.
 767    #[serde(default)]
 768    pub soft_wrap: Option<SoftWrap>,
 769    /// When set, selections can be wrapped using prefix/suffix pairs on both sides.
 770    #[serde(default)]
 771    pub wrap_characters: Option<WrapCharactersConfig>,
 772    /// The name of a Prettier parser that will be used for this language when no file path is available.
 773    /// If there's a parser name in the language settings, that will be used instead.
 774    #[serde(default)]
 775    pub prettier_parser_name: Option<String>,
 776    /// If true, this language is only for syntax highlighting via an injection into other
 777    /// languages, but should not appear to the user as a distinct language.
 778    #[serde(default)]
 779    pub hidden: bool,
 780    /// If configured, this language contains JSX style tags, and should support auto-closing of those tags.
 781    #[serde(default)]
 782    pub jsx_tag_auto_close: Option<JsxTagAutoCloseConfig>,
 783    /// A list of characters that Zed should treat as word characters for completion queries.
 784    #[serde(default)]
 785    pub completion_query_characters: HashSet<char>,
 786    /// A list of preferred debuggers for this language.
 787    #[serde(default)]
 788    pub debuggers: IndexSet<SharedString>,
 789}
 790
 791#[derive(Clone, Debug, Deserialize, Default, JsonSchema)]
 792pub struct DecreaseIndentConfig {
 793    #[serde(default, deserialize_with = "deserialize_regex")]
 794    #[schemars(schema_with = "regex_json_schema")]
 795    pub pattern: Option<Regex>,
 796    #[serde(default)]
 797    pub valid_after: Vec<String>,
 798}
 799
 800#[derive(Clone, Debug, Serialize, Deserialize, Default, JsonSchema)]
 801pub struct LanguageMatcher {
 802    /// 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`.
 803    #[serde(default)]
 804    pub path_suffixes: Vec<String>,
 805    /// A regex pattern that determines whether the language should be assigned to a file or not.
 806    #[serde(
 807        default,
 808        serialize_with = "serialize_regex",
 809        deserialize_with = "deserialize_regex"
 810    )]
 811    #[schemars(schema_with = "regex_json_schema")]
 812    pub first_line_pattern: Option<Regex>,
 813}
 814
 815/// The configuration for JSX tag auto-closing.
 816#[derive(Clone, Deserialize, JsonSchema)]
 817pub struct JsxTagAutoCloseConfig {
 818    /// The name of the node for a opening tag
 819    pub open_tag_node_name: String,
 820    /// The name of the node for an closing tag
 821    pub close_tag_node_name: String,
 822    /// The name of the node for a complete element with children for open and close tags
 823    pub jsx_element_node_name: String,
 824    /// The name of the node found within both opening and closing
 825    /// tags that describes the tag name
 826    pub tag_name_node_name: String,
 827    /// Alternate Node names for tag names.
 828    /// Specifically needed as TSX represents the name in `<Foo.Bar>`
 829    /// as `member_expression` rather than `identifier` as usual
 830    #[serde(default)]
 831    pub tag_name_node_name_alternates: Vec<String>,
 832    /// Some grammars are smart enough to detect a closing tag
 833    /// that is not valid i.e. doesn't match it's corresponding
 834    /// opening tag or does not have a corresponding opening tag
 835    /// This should be set to the name of the node for invalid
 836    /// closing tags if the grammar contains such a node, otherwise
 837    /// detecting already closed tags will not work properly
 838    #[serde(default)]
 839    pub erroneous_close_tag_node_name: Option<String>,
 840    /// See above for erroneous_close_tag_node_name for details
 841    /// This should be set if the node used for the tag name
 842    /// within erroneous closing tags is different from the
 843    /// normal tag name node name
 844    #[serde(default)]
 845    pub erroneous_close_tag_name_node_name: Option<String>,
 846}
 847
 848/// The configuration for block comments for this language.
 849#[derive(Clone, Debug, JsonSchema, PartialEq)]
 850pub struct BlockCommentConfig {
 851    /// A start tag of block comment.
 852    pub start: Arc<str>,
 853    /// A end tag of block comment.
 854    pub end: Arc<str>,
 855    /// A character to add as a prefix when a new line is added to a block comment.
 856    pub prefix: Arc<str>,
 857    /// A indent to add for prefix and end line upon new line.
 858    pub tab_size: u32,
 859}
 860
 861impl<'de> Deserialize<'de> for BlockCommentConfig {
 862    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
 863    where
 864        D: Deserializer<'de>,
 865    {
 866        #[derive(Deserialize)]
 867        #[serde(untagged)]
 868        enum BlockCommentConfigHelper {
 869            New {
 870                start: Arc<str>,
 871                end: Arc<str>,
 872                prefix: Arc<str>,
 873                tab_size: u32,
 874            },
 875            Old([Arc<str>; 2]),
 876        }
 877
 878        match BlockCommentConfigHelper::deserialize(deserializer)? {
 879            BlockCommentConfigHelper::New {
 880                start,
 881                end,
 882                prefix,
 883                tab_size,
 884            } => Ok(BlockCommentConfig {
 885                start,
 886                end,
 887                prefix,
 888                tab_size,
 889            }),
 890            BlockCommentConfigHelper::Old([start, end]) => Ok(BlockCommentConfig {
 891                start,
 892                end,
 893                prefix: "".into(),
 894                tab_size: 0,
 895            }),
 896        }
 897    }
 898}
 899
 900/// Represents a language for the given range. Some languages (e.g. HTML)
 901/// interleave several languages together, thus a single buffer might actually contain
 902/// several nested scopes.
 903#[derive(Clone, Debug)]
 904pub struct LanguageScope {
 905    language: Arc<Language>,
 906    override_id: Option<u32>,
 907}
 908
 909#[derive(Clone, Deserialize, Default, Debug, JsonSchema)]
 910pub struct LanguageConfigOverride {
 911    #[serde(default)]
 912    pub line_comments: Override<Vec<Arc<str>>>,
 913    #[serde(default)]
 914    pub block_comment: Override<BlockCommentConfig>,
 915    #[serde(skip)]
 916    pub disabled_bracket_ixs: Vec<u16>,
 917    #[serde(default)]
 918    pub word_characters: Override<HashSet<char>>,
 919    #[serde(default)]
 920    pub completion_query_characters: Override<HashSet<char>>,
 921    #[serde(default)]
 922    pub opt_into_language_servers: Vec<LanguageServerName>,
 923    #[serde(default)]
 924    pub prefer_label_for_snippet: Option<bool>,
 925}
 926
 927#[derive(Clone, Deserialize, Debug, Serialize, JsonSchema)]
 928#[serde(untagged)]
 929pub enum Override<T> {
 930    Remove { remove: bool },
 931    Set(T),
 932}
 933
 934impl<T> Default for Override<T> {
 935    fn default() -> Self {
 936        Override::Remove { remove: false }
 937    }
 938}
 939
 940impl<T> Override<T> {
 941    fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
 942        match this {
 943            Some(Self::Set(value)) => Some(value),
 944            Some(Self::Remove { remove: true }) => None,
 945            Some(Self::Remove { remove: false }) | None => original,
 946        }
 947    }
 948}
 949
 950impl Default for LanguageConfig {
 951    fn default() -> Self {
 952        Self {
 953            name: LanguageName::new(""),
 954            code_fence_block_name: None,
 955            grammar: None,
 956            matcher: LanguageMatcher::default(),
 957            brackets: Default::default(),
 958            auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
 959            auto_indent_on_paste: None,
 960            increase_indent_pattern: Default::default(),
 961            decrease_indent_pattern: Default::default(),
 962            decrease_indent_patterns: Default::default(),
 963            autoclose_before: Default::default(),
 964            line_comments: Default::default(),
 965            block_comment: Default::default(),
 966            documentation_comment: Default::default(),
 967            rewrap_prefixes: Default::default(),
 968            scope_opt_in_language_servers: Default::default(),
 969            overrides: Default::default(),
 970            word_characters: Default::default(),
 971            collapsed_placeholder: Default::default(),
 972            hard_tabs: None,
 973            tab_size: None,
 974            soft_wrap: None,
 975            wrap_characters: None,
 976            prettier_parser_name: None,
 977            hidden: false,
 978            jsx_tag_auto_close: None,
 979            completion_query_characters: Default::default(),
 980            debuggers: Default::default(),
 981        }
 982    }
 983}
 984
 985#[derive(Clone, Debug, Deserialize, JsonSchema)]
 986pub struct WrapCharactersConfig {
 987    /// Opening token split into a prefix and suffix. The first caret goes
 988    /// after the prefix (i.e., between prefix and suffix).
 989    pub start_prefix: String,
 990    pub start_suffix: String,
 991    /// Closing token split into a prefix and suffix. The second caret goes
 992    /// after the prefix (i.e., between prefix and suffix).
 993    pub end_prefix: String,
 994    pub end_suffix: String,
 995}
 996
 997fn auto_indent_using_last_non_empty_line_default() -> bool {
 998    true
 999}
1000
1001fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
1002    let source = Option::<String>::deserialize(d)?;
1003    if let Some(source) = source {
1004        Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
1005    } else {
1006        Ok(None)
1007    }
1008}
1009
1010fn regex_json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1011    json_schema!({
1012        "type": "string"
1013    })
1014}
1015
1016fn serialize_regex<S>(regex: &Option<Regex>, serializer: S) -> Result<S::Ok, S::Error>
1017where
1018    S: Serializer,
1019{
1020    match regex {
1021        Some(regex) => serializer.serialize_str(regex.as_str()),
1022        None => serializer.serialize_none(),
1023    }
1024}
1025
1026fn deserialize_regex_vec<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<Regex>, D::Error> {
1027    let sources = Vec::<String>::deserialize(d)?;
1028    sources
1029        .into_iter()
1030        .map(|source| regex::Regex::new(&source))
1031        .collect::<Result<_, _>>()
1032        .map_err(de::Error::custom)
1033}
1034
1035fn regex_vec_json_schema(_: &mut SchemaGenerator) -> schemars::Schema {
1036    json_schema!({
1037        "type": "array",
1038        "items": { "type": "string" }
1039    })
1040}
1041
1042#[doc(hidden)]
1043#[cfg(any(test, feature = "test-support"))]
1044pub struct FakeLspAdapter {
1045    pub name: &'static str,
1046    pub initialization_options: Option<Value>,
1047    pub prettier_plugins: Vec<&'static str>,
1048    pub disk_based_diagnostics_progress_token: Option<String>,
1049    pub disk_based_diagnostics_sources: Vec<String>,
1050    pub language_server_binary: LanguageServerBinary,
1051
1052    pub capabilities: lsp::ServerCapabilities,
1053    pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
1054    pub label_for_completion: Option<
1055        Box<
1056            dyn 'static
1057                + Send
1058                + Sync
1059                + Fn(&lsp::CompletionItem, &Arc<Language>) -> Option<CodeLabel>,
1060        >,
1061    >,
1062}
1063
1064/// Configuration of handling bracket pairs for a given language.
1065///
1066/// This struct includes settings for defining which pairs of characters are considered brackets and
1067/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
1068#[derive(Clone, Debug, Default, JsonSchema)]
1069#[schemars(with = "Vec::<BracketPairContent>")]
1070pub struct BracketPairConfig {
1071    /// A list of character pairs that should be treated as brackets in the context of a given language.
1072    pub pairs: Vec<BracketPair>,
1073    /// A list of tree-sitter scopes for which a given bracket should not be active.
1074    /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
1075    pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
1076}
1077
1078impl BracketPairConfig {
1079    pub fn is_closing_brace(&self, c: char) -> bool {
1080        self.pairs.iter().any(|pair| pair.end.starts_with(c))
1081    }
1082}
1083
1084#[derive(Deserialize, JsonSchema)]
1085pub struct BracketPairContent {
1086    #[serde(flatten)]
1087    pub bracket_pair: BracketPair,
1088    #[serde(default)]
1089    pub not_in: Vec<String>,
1090}
1091
1092impl<'de> Deserialize<'de> for BracketPairConfig {
1093    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1094    where
1095        D: Deserializer<'de>,
1096    {
1097        let result = Vec::<BracketPairContent>::deserialize(deserializer)?;
1098        let (brackets, disabled_scopes_by_bracket_ix) = result
1099            .into_iter()
1100            .map(|entry| (entry.bracket_pair, entry.not_in))
1101            .unzip();
1102
1103        Ok(BracketPairConfig {
1104            pairs: brackets,
1105            disabled_scopes_by_bracket_ix,
1106        })
1107    }
1108}
1109
1110/// Describes a single bracket pair and how an editor should react to e.g. inserting
1111/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
1112#[derive(Clone, Debug, Default, Deserialize, PartialEq, JsonSchema)]
1113pub struct BracketPair {
1114    /// Starting substring for a bracket.
1115    pub start: String,
1116    /// Ending substring for a bracket.
1117    pub end: String,
1118    /// True if `end` should be automatically inserted right after `start` characters.
1119    pub close: bool,
1120    /// True if selected text should be surrounded by `start` and `end` characters.
1121    #[serde(default = "default_true")]
1122    pub surround: bool,
1123    /// True if an extra newline should be inserted while the cursor is in the middle
1124    /// of that bracket pair.
1125    pub newline: bool,
1126}
1127
1128#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
1129pub struct LanguageId(usize);
1130
1131impl LanguageId {
1132    pub(crate) fn new() -> Self {
1133        Self(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst))
1134    }
1135}
1136
1137pub struct Language {
1138    pub(crate) id: LanguageId,
1139    pub(crate) config: LanguageConfig,
1140    pub(crate) grammar: Option<Arc<Grammar>>,
1141    pub(crate) context_provider: Option<Arc<dyn ContextProvider>>,
1142    pub(crate) toolchain: Option<Arc<dyn ToolchainLister>>,
1143    pub(crate) manifest_name: Option<ManifestName>,
1144}
1145
1146#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
1147pub struct GrammarId(pub usize);
1148
1149impl GrammarId {
1150    pub(crate) fn new() -> Self {
1151        Self(NEXT_GRAMMAR_ID.fetch_add(1, SeqCst))
1152    }
1153}
1154
1155pub struct Grammar {
1156    id: GrammarId,
1157    pub ts_language: tree_sitter::Language,
1158    pub(crate) error_query: Option<Query>,
1159    pub highlights_config: Option<HighlightsConfig>,
1160    pub(crate) brackets_config: Option<BracketsConfig>,
1161    pub(crate) redactions_config: Option<RedactionConfig>,
1162    pub(crate) runnable_config: Option<RunnableConfig>,
1163    pub(crate) indents_config: Option<IndentConfig>,
1164    pub outline_config: Option<OutlineConfig>,
1165    pub text_object_config: Option<TextObjectConfig>,
1166    pub embedding_config: Option<EmbeddingConfig>,
1167    pub(crate) injection_config: Option<InjectionConfig>,
1168    pub(crate) override_config: Option<OverrideConfig>,
1169    pub(crate) debug_variables_config: Option<DebugVariablesConfig>,
1170    pub(crate) highlight_map: Mutex<HighlightMap>,
1171}
1172
1173pub struct HighlightsConfig {
1174    pub query: Query,
1175    pub identifier_capture_indices: Vec<u32>,
1176}
1177
1178struct IndentConfig {
1179    query: Query,
1180    indent_capture_ix: u32,
1181    start_capture_ix: Option<u32>,
1182    end_capture_ix: Option<u32>,
1183    outdent_capture_ix: Option<u32>,
1184    suffixed_start_captures: HashMap<u32, SharedString>,
1185}
1186
1187pub struct OutlineConfig {
1188    pub query: Query,
1189    pub item_capture_ix: u32,
1190    pub name_capture_ix: u32,
1191    pub context_capture_ix: Option<u32>,
1192    pub extra_context_capture_ix: Option<u32>,
1193    pub open_capture_ix: Option<u32>,
1194    pub close_capture_ix: Option<u32>,
1195    pub annotation_capture_ix: Option<u32>,
1196}
1197
1198#[derive(Debug, Clone, Copy, PartialEq)]
1199pub enum DebuggerTextObject {
1200    Variable,
1201    Scope,
1202}
1203
1204impl DebuggerTextObject {
1205    pub fn from_capture_name(name: &str) -> Option<DebuggerTextObject> {
1206        match name {
1207            "debug-variable" => Some(DebuggerTextObject::Variable),
1208            "debug-scope" => Some(DebuggerTextObject::Scope),
1209            _ => None,
1210        }
1211    }
1212}
1213
1214#[derive(Debug, Clone, Copy, PartialEq)]
1215pub enum TextObject {
1216    InsideFunction,
1217    AroundFunction,
1218    InsideClass,
1219    AroundClass,
1220    InsideComment,
1221    AroundComment,
1222}
1223
1224impl TextObject {
1225    pub fn from_capture_name(name: &str) -> Option<TextObject> {
1226        match name {
1227            "function.inside" => Some(TextObject::InsideFunction),
1228            "function.around" => Some(TextObject::AroundFunction),
1229            "class.inside" => Some(TextObject::InsideClass),
1230            "class.around" => Some(TextObject::AroundClass),
1231            "comment.inside" => Some(TextObject::InsideComment),
1232            "comment.around" => Some(TextObject::AroundComment),
1233            _ => None,
1234        }
1235    }
1236
1237    pub fn around(&self) -> Option<Self> {
1238        match self {
1239            TextObject::InsideFunction => Some(TextObject::AroundFunction),
1240            TextObject::InsideClass => Some(TextObject::AroundClass),
1241            TextObject::InsideComment => Some(TextObject::AroundComment),
1242            _ => None,
1243        }
1244    }
1245}
1246
1247pub struct TextObjectConfig {
1248    pub query: Query,
1249    pub text_objects_by_capture_ix: Vec<(u32, TextObject)>,
1250}
1251
1252#[derive(Debug)]
1253pub struct EmbeddingConfig {
1254    pub query: Query,
1255    pub item_capture_ix: u32,
1256    pub name_capture_ix: Option<u32>,
1257    pub context_capture_ix: Option<u32>,
1258    pub collapse_capture_ix: Option<u32>,
1259    pub keep_capture_ix: Option<u32>,
1260}
1261
1262struct InjectionConfig {
1263    query: Query,
1264    content_capture_ix: u32,
1265    language_capture_ix: Option<u32>,
1266    patterns: Vec<InjectionPatternConfig>,
1267}
1268
1269struct RedactionConfig {
1270    pub query: Query,
1271    pub redaction_capture_ix: u32,
1272}
1273
1274#[derive(Clone, Debug, PartialEq)]
1275enum RunnableCapture {
1276    Named(SharedString),
1277    Run,
1278}
1279
1280struct RunnableConfig {
1281    pub query: Query,
1282    /// A mapping from capture indice to capture kind
1283    pub extra_captures: Vec<RunnableCapture>,
1284}
1285
1286struct OverrideConfig {
1287    query: Query,
1288    values: HashMap<u32, OverrideEntry>,
1289}
1290
1291#[derive(Debug)]
1292struct OverrideEntry {
1293    name: String,
1294    range_is_inclusive: bool,
1295    value: LanguageConfigOverride,
1296}
1297
1298#[derive(Default, Clone)]
1299struct InjectionPatternConfig {
1300    language: Option<Box<str>>,
1301    combined: bool,
1302}
1303
1304#[derive(Debug)]
1305struct BracketsConfig {
1306    query: Query,
1307    open_capture_ix: u32,
1308    close_capture_ix: u32,
1309    patterns: Vec<BracketsPatternConfig>,
1310}
1311
1312#[derive(Clone, Debug, Default)]
1313struct BracketsPatternConfig {
1314    newline_only: bool,
1315}
1316
1317pub struct DebugVariablesConfig {
1318    pub query: Query,
1319    pub objects_by_capture_ix: Vec<(u32, DebuggerTextObject)>,
1320}
1321
1322impl Language {
1323    pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
1324        Self::new_with_id(LanguageId::new(), config, ts_language)
1325    }
1326
1327    pub fn id(&self) -> LanguageId {
1328        self.id
1329    }
1330
1331    fn new_with_id(
1332        id: LanguageId,
1333        config: LanguageConfig,
1334        ts_language: Option<tree_sitter::Language>,
1335    ) -> Self {
1336        Self {
1337            id,
1338            config,
1339            grammar: ts_language.map(|ts_language| {
1340                Arc::new(Grammar {
1341                    id: GrammarId::new(),
1342                    highlights_config: None,
1343                    brackets_config: None,
1344                    outline_config: None,
1345                    text_object_config: None,
1346                    embedding_config: None,
1347                    indents_config: None,
1348                    injection_config: None,
1349                    override_config: None,
1350                    redactions_config: None,
1351                    runnable_config: None,
1352                    error_query: Query::new(&ts_language, "(ERROR) @error").ok(),
1353                    debug_variables_config: None,
1354                    ts_language,
1355                    highlight_map: Default::default(),
1356                })
1357            }),
1358            context_provider: None,
1359            toolchain: None,
1360            manifest_name: None,
1361        }
1362    }
1363
1364    pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
1365        self.context_provider = provider;
1366        self
1367    }
1368
1369    pub fn with_toolchain_lister(mut self, provider: Option<Arc<dyn ToolchainLister>>) -> Self {
1370        self.toolchain = provider;
1371        self
1372    }
1373
1374    pub fn with_manifest(mut self, name: Option<ManifestName>) -> Self {
1375        self.manifest_name = name;
1376        self
1377    }
1378
1379    pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
1380        if let Some(query) = queries.highlights {
1381            self = self
1382                .with_highlights_query(query.as_ref())
1383                .context("Error loading highlights query")?;
1384        }
1385        if let Some(query) = queries.brackets {
1386            self = self
1387                .with_brackets_query(query.as_ref())
1388                .context("Error loading brackets query")?;
1389        }
1390        if let Some(query) = queries.indents {
1391            self = self
1392                .with_indents_query(query.as_ref())
1393                .context("Error loading indents query")?;
1394        }
1395        if let Some(query) = queries.outline {
1396            self = self
1397                .with_outline_query(query.as_ref())
1398                .context("Error loading outline query")?;
1399        }
1400        if let Some(query) = queries.embedding {
1401            self = self
1402                .with_embedding_query(query.as_ref())
1403                .context("Error loading embedding query")?;
1404        }
1405        if let Some(query) = queries.injections {
1406            self = self
1407                .with_injection_query(query.as_ref())
1408                .context("Error loading injection query")?;
1409        }
1410        if let Some(query) = queries.overrides {
1411            self = self
1412                .with_override_query(query.as_ref())
1413                .context("Error loading override query")?;
1414        }
1415        if let Some(query) = queries.redactions {
1416            self = self
1417                .with_redaction_query(query.as_ref())
1418                .context("Error loading redaction query")?;
1419        }
1420        if let Some(query) = queries.runnables {
1421            self = self
1422                .with_runnable_query(query.as_ref())
1423                .context("Error loading runnables query")?;
1424        }
1425        if let Some(query) = queries.text_objects {
1426            self = self
1427                .with_text_object_query(query.as_ref())
1428                .context("Error loading textobject query")?;
1429        }
1430        if let Some(query) = queries.debugger {
1431            self = self
1432                .with_debug_variables_query(query.as_ref())
1433                .context("Error loading debug variables query")?;
1434        }
1435        Ok(self)
1436    }
1437
1438    pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1439        let grammar = self.grammar_mut()?;
1440        let query = Query::new(&grammar.ts_language, source)?;
1441
1442        let mut identifier_capture_indices = Vec::new();
1443        for name in [
1444            "variable",
1445            "constant",
1446            "constructor",
1447            "function",
1448            "function.method",
1449            "function.method.call",
1450            "function.special",
1451            "property",
1452            "type",
1453            "type.interface",
1454        ] {
1455            identifier_capture_indices.extend(query.capture_index_for_name(name));
1456        }
1457
1458        grammar.highlights_config = Some(HighlightsConfig {
1459            query,
1460            identifier_capture_indices,
1461        });
1462
1463        Ok(self)
1464    }
1465
1466    pub fn with_runnable_query(mut self, source: &str) -> Result<Self> {
1467        let grammar = self.grammar_mut()?;
1468
1469        let query = Query::new(&grammar.ts_language, source)?;
1470        let extra_captures: Vec<_> = query
1471            .capture_names()
1472            .iter()
1473            .map(|&name| match name {
1474                "run" => RunnableCapture::Run,
1475                name => RunnableCapture::Named(name.to_string().into()),
1476            })
1477            .collect();
1478
1479        grammar.runnable_config = Some(RunnableConfig {
1480            extra_captures,
1481            query,
1482        });
1483
1484        Ok(self)
1485    }
1486
1487    pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1488        let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1489        let mut item_capture_ix = 0;
1490        let mut name_capture_ix = 0;
1491        let mut context_capture_ix = None;
1492        let mut extra_context_capture_ix = None;
1493        let mut open_capture_ix = None;
1494        let mut close_capture_ix = None;
1495        let mut annotation_capture_ix = None;
1496        if populate_capture_indices(
1497            &query,
1498            &self.config.name,
1499            "outline",
1500            &[],
1501            &mut [
1502                Capture::Required("item", &mut item_capture_ix),
1503                Capture::Required("name", &mut name_capture_ix),
1504                Capture::Optional("context", &mut context_capture_ix),
1505                Capture::Optional("context.extra", &mut extra_context_capture_ix),
1506                Capture::Optional("open", &mut open_capture_ix),
1507                Capture::Optional("close", &mut close_capture_ix),
1508                Capture::Optional("annotation", &mut annotation_capture_ix),
1509            ],
1510        ) {
1511            self.grammar_mut()?.outline_config = Some(OutlineConfig {
1512                query,
1513                item_capture_ix,
1514                name_capture_ix,
1515                context_capture_ix,
1516                extra_context_capture_ix,
1517                open_capture_ix,
1518                close_capture_ix,
1519                annotation_capture_ix,
1520            });
1521        }
1522        Ok(self)
1523    }
1524
1525    pub fn with_text_object_query(mut self, source: &str) -> Result<Self> {
1526        let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1527
1528        let mut text_objects_by_capture_ix = Vec::new();
1529        for (ix, name) in query.capture_names().iter().enumerate() {
1530            if let Some(text_object) = TextObject::from_capture_name(name) {
1531                text_objects_by_capture_ix.push((ix as u32, text_object));
1532            } else {
1533                log::warn!(
1534                    "unrecognized capture name '{}' in {} textobjects TreeSitter query",
1535                    name,
1536                    self.config.name,
1537                );
1538            }
1539        }
1540
1541        self.grammar_mut()?.text_object_config = Some(TextObjectConfig {
1542            query,
1543            text_objects_by_capture_ix,
1544        });
1545        Ok(self)
1546    }
1547
1548    pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
1549        let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1550        let mut item_capture_ix = 0;
1551        let mut name_capture_ix = None;
1552        let mut context_capture_ix = None;
1553        let mut collapse_capture_ix = None;
1554        let mut keep_capture_ix = None;
1555        if populate_capture_indices(
1556            &query,
1557            &self.config.name,
1558            "embedding",
1559            &[],
1560            &mut [
1561                Capture::Required("item", &mut item_capture_ix),
1562                Capture::Optional("name", &mut name_capture_ix),
1563                Capture::Optional("context", &mut context_capture_ix),
1564                Capture::Optional("keep", &mut keep_capture_ix),
1565                Capture::Optional("collapse", &mut collapse_capture_ix),
1566            ],
1567        ) {
1568            self.grammar_mut()?.embedding_config = Some(EmbeddingConfig {
1569                query,
1570                item_capture_ix,
1571                name_capture_ix,
1572                context_capture_ix,
1573                collapse_capture_ix,
1574                keep_capture_ix,
1575            });
1576        }
1577        Ok(self)
1578    }
1579
1580    pub fn with_debug_variables_query(mut self, source: &str) -> Result<Self> {
1581        let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1582
1583        let mut objects_by_capture_ix = Vec::new();
1584        for (ix, name) in query.capture_names().iter().enumerate() {
1585            if let Some(text_object) = DebuggerTextObject::from_capture_name(name) {
1586                objects_by_capture_ix.push((ix as u32, text_object));
1587            } else {
1588                log::warn!(
1589                    "unrecognized capture name '{}' in {} debugger TreeSitter query",
1590                    name,
1591                    self.config.name,
1592                );
1593            }
1594        }
1595
1596        self.grammar_mut()?.debug_variables_config = Some(DebugVariablesConfig {
1597            query,
1598            objects_by_capture_ix,
1599        });
1600        Ok(self)
1601    }
1602
1603    pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1604        let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1605        let mut open_capture_ix = 0;
1606        let mut close_capture_ix = 0;
1607        if populate_capture_indices(
1608            &query,
1609            &self.config.name,
1610            "brackets",
1611            &[],
1612            &mut [
1613                Capture::Required("open", &mut open_capture_ix),
1614                Capture::Required("close", &mut close_capture_ix),
1615            ],
1616        ) {
1617            let patterns = (0..query.pattern_count())
1618                .map(|ix| {
1619                    let mut config = BracketsPatternConfig::default();
1620                    for setting in query.property_settings(ix) {
1621                        if setting.key.as_ref() == "newline.only" {
1622                            config.newline_only = true
1623                        }
1624                    }
1625                    config
1626                })
1627                .collect();
1628            self.grammar_mut()?.brackets_config = Some(BracketsConfig {
1629                query,
1630                open_capture_ix,
1631                close_capture_ix,
1632                patterns,
1633            });
1634        }
1635        Ok(self)
1636    }
1637
1638    pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1639        let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1640        let mut indent_capture_ix = 0;
1641        let mut start_capture_ix = None;
1642        let mut end_capture_ix = None;
1643        let mut outdent_capture_ix = None;
1644        if populate_capture_indices(
1645            &query,
1646            &self.config.name,
1647            "indents",
1648            &["start."],
1649            &mut [
1650                Capture::Required("indent", &mut indent_capture_ix),
1651                Capture::Optional("start", &mut start_capture_ix),
1652                Capture::Optional("end", &mut end_capture_ix),
1653                Capture::Optional("outdent", &mut outdent_capture_ix),
1654            ],
1655        ) {
1656            let mut suffixed_start_captures = HashMap::default();
1657            for (ix, name) in query.capture_names().iter().enumerate() {
1658                if let Some(suffix) = name.strip_prefix("start.") {
1659                    suffixed_start_captures.insert(ix as u32, suffix.to_owned().into());
1660                }
1661            }
1662
1663            self.grammar_mut()?.indents_config = Some(IndentConfig {
1664                query,
1665                indent_capture_ix,
1666                start_capture_ix,
1667                end_capture_ix,
1668                outdent_capture_ix,
1669                suffixed_start_captures,
1670            });
1671        }
1672        Ok(self)
1673    }
1674
1675    pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1676        let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1677        let mut language_capture_ix = None;
1678        let mut injection_language_capture_ix = None;
1679        let mut content_capture_ix = None;
1680        let mut injection_content_capture_ix = None;
1681        if populate_capture_indices(
1682            &query,
1683            &self.config.name,
1684            "injections",
1685            &[],
1686            &mut [
1687                Capture::Optional("language", &mut language_capture_ix),
1688                Capture::Optional("injection.language", &mut injection_language_capture_ix),
1689                Capture::Optional("content", &mut content_capture_ix),
1690                Capture::Optional("injection.content", &mut injection_content_capture_ix),
1691            ],
1692        ) {
1693            language_capture_ix = match (language_capture_ix, injection_language_capture_ix) {
1694                (None, Some(ix)) => Some(ix),
1695                (Some(_), Some(_)) => {
1696                    anyhow::bail!("both language and injection.language captures are present");
1697                }
1698                _ => language_capture_ix,
1699            };
1700            content_capture_ix = match (content_capture_ix, injection_content_capture_ix) {
1701                (None, Some(ix)) => Some(ix),
1702                (Some(_), Some(_)) => {
1703                    anyhow::bail!("both content and injection.content captures are present")
1704                }
1705                _ => content_capture_ix,
1706            };
1707            let patterns = (0..query.pattern_count())
1708                .map(|ix| {
1709                    let mut config = InjectionPatternConfig::default();
1710                    for setting in query.property_settings(ix) {
1711                        match setting.key.as_ref() {
1712                            "language" | "injection.language" => {
1713                                config.language.clone_from(&setting.value);
1714                            }
1715                            "combined" | "injection.combined" => {
1716                                config.combined = true;
1717                            }
1718                            _ => {}
1719                        }
1720                    }
1721                    config
1722                })
1723                .collect();
1724            if let Some(content_capture_ix) = content_capture_ix {
1725                self.grammar_mut()?.injection_config = Some(InjectionConfig {
1726                    query,
1727                    language_capture_ix,
1728                    content_capture_ix,
1729                    patterns,
1730                });
1731            } else {
1732                log::error!(
1733                    "missing required capture in injections {} TreeSitter query: \
1734                    content or injection.content",
1735                    &self.config.name,
1736                );
1737            }
1738        }
1739        Ok(self)
1740    }
1741
1742    pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1743        let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1744
1745        let mut override_configs_by_id = HashMap::default();
1746        for (ix, mut name) in query.capture_names().iter().copied().enumerate() {
1747            let mut range_is_inclusive = false;
1748            if name.starts_with('_') {
1749                continue;
1750            }
1751            if let Some(prefix) = name.strip_suffix(".inclusive") {
1752                name = prefix;
1753                range_is_inclusive = true;
1754            }
1755
1756            let value = self.config.overrides.get(name).cloned().unwrap_or_default();
1757            for server_name in &value.opt_into_language_servers {
1758                if !self
1759                    .config
1760                    .scope_opt_in_language_servers
1761                    .contains(server_name)
1762                {
1763                    util::debug_panic!(
1764                        "Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server"
1765                    );
1766                }
1767            }
1768
1769            override_configs_by_id.insert(
1770                ix as u32,
1771                OverrideEntry {
1772                    name: name.to_string(),
1773                    range_is_inclusive,
1774                    value,
1775                },
1776            );
1777        }
1778
1779        let referenced_override_names = self.config.overrides.keys().chain(
1780            self.config
1781                .brackets
1782                .disabled_scopes_by_bracket_ix
1783                .iter()
1784                .flatten(),
1785        );
1786
1787        for referenced_name in referenced_override_names {
1788            if !override_configs_by_id
1789                .values()
1790                .any(|entry| entry.name == *referenced_name)
1791            {
1792                anyhow::bail!(
1793                    "language {:?} has overrides in config not in query: {referenced_name:?}",
1794                    self.config.name
1795                );
1796            }
1797        }
1798
1799        for entry in override_configs_by_id.values_mut() {
1800            entry.value.disabled_bracket_ixs = self
1801                .config
1802                .brackets
1803                .disabled_scopes_by_bracket_ix
1804                .iter()
1805                .enumerate()
1806                .filter_map(|(ix, disabled_scope_names)| {
1807                    if disabled_scope_names.contains(&entry.name) {
1808                        Some(ix as u16)
1809                    } else {
1810                        None
1811                    }
1812                })
1813                .collect();
1814        }
1815
1816        self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1817
1818        let grammar = self.grammar_mut()?;
1819        grammar.override_config = Some(OverrideConfig {
1820            query,
1821            values: override_configs_by_id,
1822        });
1823        Ok(self)
1824    }
1825
1826    pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1827        let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1828        let mut redaction_capture_ix = 0;
1829        if populate_capture_indices(
1830            &query,
1831            &self.config.name,
1832            "redactions",
1833            &[],
1834            &mut [Capture::Required("redact", &mut redaction_capture_ix)],
1835        ) {
1836            self.grammar_mut()?.redactions_config = Some(RedactionConfig {
1837                query,
1838                redaction_capture_ix,
1839            });
1840        }
1841        Ok(self)
1842    }
1843
1844    fn expect_grammar(&self) -> Result<&Grammar> {
1845        self.grammar
1846            .as_ref()
1847            .map(|grammar| grammar.as_ref())
1848            .context("no grammar for language")
1849    }
1850
1851    fn grammar_mut(&mut self) -> Result<&mut Grammar> {
1852        Arc::get_mut(self.grammar.as_mut().context("no grammar for language")?)
1853            .context("cannot mutate grammar")
1854    }
1855
1856    pub fn name(&self) -> LanguageName {
1857        self.config.name.clone()
1858    }
1859    pub fn manifest(&self) -> Option<&ManifestName> {
1860        self.manifest_name.as_ref()
1861    }
1862
1863    pub fn code_fence_block_name(&self) -> Arc<str> {
1864        self.config
1865            .code_fence_block_name
1866            .clone()
1867            .unwrap_or_else(|| self.config.name.as_ref().to_lowercase().into())
1868    }
1869
1870    pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1871        self.context_provider.clone()
1872    }
1873
1874    pub fn toolchain_lister(&self) -> Option<Arc<dyn ToolchainLister>> {
1875        self.toolchain.clone()
1876    }
1877
1878    pub fn highlight_text<'a>(
1879        self: &'a Arc<Self>,
1880        text: &'a Rope,
1881        range: Range<usize>,
1882    ) -> Vec<(Range<usize>, HighlightId)> {
1883        let mut result = Vec::new();
1884        if let Some(grammar) = &self.grammar {
1885            let tree = grammar.parse_text(text, None);
1886            let captures =
1887                SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1888                    grammar
1889                        .highlights_config
1890                        .as_ref()
1891                        .map(|config| &config.query)
1892                });
1893            let highlight_maps = vec![grammar.highlight_map()];
1894            let mut offset = 0;
1895            for chunk in
1896                BufferChunks::new(text, range, Some((captures, highlight_maps)), false, None)
1897            {
1898                let end_offset = offset + chunk.text.len();
1899                if let Some(highlight_id) = chunk.syntax_highlight_id
1900                    && !highlight_id.is_default()
1901                {
1902                    result.push((offset..end_offset, highlight_id));
1903                }
1904                offset = end_offset;
1905            }
1906        }
1907        result
1908    }
1909
1910    pub fn path_suffixes(&self) -> &[String] {
1911        &self.config.matcher.path_suffixes
1912    }
1913
1914    pub fn should_autoclose_before(&self, c: char) -> bool {
1915        c.is_whitespace() || self.config.autoclose_before.contains(c)
1916    }
1917
1918    pub fn set_theme(&self, theme: &SyntaxTheme) {
1919        if let Some(grammar) = self.grammar.as_ref()
1920            && let Some(highlights_config) = &grammar.highlights_config
1921        {
1922            *grammar.highlight_map.lock() =
1923                HighlightMap::new(highlights_config.query.capture_names(), theme);
1924        }
1925    }
1926
1927    pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1928        self.grammar.as_ref()
1929    }
1930
1931    pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1932        LanguageScope {
1933            language: self.clone(),
1934            override_id: None,
1935        }
1936    }
1937
1938    pub fn lsp_id(&self) -> String {
1939        self.config.name.lsp_id()
1940    }
1941
1942    pub fn prettier_parser_name(&self) -> Option<&str> {
1943        self.config.prettier_parser_name.as_deref()
1944    }
1945
1946    pub fn config(&self) -> &LanguageConfig {
1947        &self.config
1948    }
1949}
1950
1951impl LanguageScope {
1952    pub fn path_suffixes(&self) -> &[String] {
1953        self.language.path_suffixes()
1954    }
1955
1956    pub fn language_name(&self) -> LanguageName {
1957        self.language.config.name.clone()
1958    }
1959
1960    pub fn collapsed_placeholder(&self) -> &str {
1961        self.language.config.collapsed_placeholder.as_ref()
1962    }
1963
1964    /// Returns line prefix that is inserted in e.g. line continuations or
1965    /// in `toggle comments` action.
1966    pub fn line_comment_prefixes(&self) -> &[Arc<str>] {
1967        Override::as_option(
1968            self.config_override().map(|o| &o.line_comments),
1969            Some(&self.language.config.line_comments),
1970        )
1971        .map_or([].as_slice(), |e| e.as_slice())
1972    }
1973
1974    /// Config for block comments for this language.
1975    pub fn block_comment(&self) -> Option<&BlockCommentConfig> {
1976        Override::as_option(
1977            self.config_override().map(|o| &o.block_comment),
1978            self.language.config.block_comment.as_ref(),
1979        )
1980    }
1981
1982    /// Config for documentation-style block comments for this language.
1983    pub fn documentation_comment(&self) -> Option<&BlockCommentConfig> {
1984        self.language.config.documentation_comment.as_ref()
1985    }
1986
1987    /// Returns additional regex patterns that act as prefix markers for creating
1988    /// boundaries during rewrapping.
1989    ///
1990    /// By default, Zed treats as paragraph and comment prefixes as boundaries.
1991    pub fn rewrap_prefixes(&self) -> &[Regex] {
1992        &self.language.config.rewrap_prefixes
1993    }
1994
1995    /// Returns a list of language-specific word characters.
1996    ///
1997    /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1998    /// the purpose of actions like 'move to next word end` or whole-word search.
1999    /// It additionally accounts for language's additional word characters.
2000    pub fn word_characters(&self) -> Option<&HashSet<char>> {
2001        Override::as_option(
2002            self.config_override().map(|o| &o.word_characters),
2003            Some(&self.language.config.word_characters),
2004        )
2005    }
2006
2007    /// Returns a list of language-specific characters that are considered part of
2008    /// a completion query.
2009    pub fn completion_query_characters(&self) -> Option<&HashSet<char>> {
2010        Override::as_option(
2011            self.config_override()
2012                .map(|o| &o.completion_query_characters),
2013            Some(&self.language.config.completion_query_characters),
2014        )
2015    }
2016
2017    /// Returns whether to prefer snippet `label` over `new_text` to replace text when
2018    /// completion is accepted.
2019    ///
2020    /// In cases like when cursor is in string or renaming existing function,
2021    /// you don't want to expand function signature instead just want function name
2022    /// to replace existing one.
2023    pub fn prefers_label_for_snippet_in_completion(&self) -> bool {
2024        self.config_override()
2025            .and_then(|o| o.prefer_label_for_snippet)
2026            .unwrap_or(false)
2027    }
2028
2029    /// Returns a list of bracket pairs for a given language with an additional
2030    /// piece of information about whether the particular bracket pair is currently active for a given language.
2031    pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
2032        let mut disabled_ids = self
2033            .config_override()
2034            .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
2035        self.language
2036            .config
2037            .brackets
2038            .pairs
2039            .iter()
2040            .enumerate()
2041            .map(move |(ix, bracket)| {
2042                let mut is_enabled = true;
2043                if let Some(next_disabled_ix) = disabled_ids.first()
2044                    && ix == *next_disabled_ix as usize
2045                {
2046                    disabled_ids = &disabled_ids[1..];
2047                    is_enabled = false;
2048                }
2049                (bracket, is_enabled)
2050            })
2051    }
2052
2053    pub fn should_autoclose_before(&self, c: char) -> bool {
2054        c.is_whitespace() || self.language.config.autoclose_before.contains(c)
2055    }
2056
2057    pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
2058        let config = &self.language.config;
2059        let opt_in_servers = &config.scope_opt_in_language_servers;
2060        if opt_in_servers.contains(name) {
2061            if let Some(over) = self.config_override() {
2062                over.opt_into_language_servers.contains(name)
2063            } else {
2064                false
2065            }
2066        } else {
2067            true
2068        }
2069    }
2070
2071    pub fn override_name(&self) -> Option<&str> {
2072        let id = self.override_id?;
2073        let grammar = self.language.grammar.as_ref()?;
2074        let override_config = grammar.override_config.as_ref()?;
2075        override_config.values.get(&id).map(|e| e.name.as_str())
2076    }
2077
2078    fn config_override(&self) -> Option<&LanguageConfigOverride> {
2079        let id = self.override_id?;
2080        let grammar = self.language.grammar.as_ref()?;
2081        let override_config = grammar.override_config.as_ref()?;
2082        override_config.values.get(&id).map(|e| &e.value)
2083    }
2084}
2085
2086impl Hash for Language {
2087    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
2088        self.id.hash(state)
2089    }
2090}
2091
2092impl PartialEq for Language {
2093    fn eq(&self, other: &Self) -> bool {
2094        self.id.eq(&other.id)
2095    }
2096}
2097
2098impl Eq for Language {}
2099
2100impl Debug for Language {
2101    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2102        f.debug_struct("Language")
2103            .field("name", &self.config.name)
2104            .finish()
2105    }
2106}
2107
2108impl Grammar {
2109    pub fn id(&self) -> GrammarId {
2110        self.id
2111    }
2112
2113    fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
2114        with_parser(|parser| {
2115            parser
2116                .set_language(&self.ts_language)
2117                .expect("incompatible grammar");
2118            let mut chunks = text.chunks_in_range(0..text.len());
2119            parser
2120                .parse_with_options(
2121                    &mut move |offset, _| {
2122                        chunks.seek(offset);
2123                        chunks.next().unwrap_or("").as_bytes()
2124                    },
2125                    old_tree.as_ref(),
2126                    None,
2127                )
2128                .unwrap()
2129        })
2130    }
2131
2132    pub fn highlight_map(&self) -> HighlightMap {
2133        self.highlight_map.lock().clone()
2134    }
2135
2136    pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
2137        let capture_id = self
2138            .highlights_config
2139            .as_ref()?
2140            .query
2141            .capture_index_for_name(name)?;
2142        Some(self.highlight_map.lock().get(capture_id))
2143    }
2144
2145    pub fn debug_variables_config(&self) -> Option<&DebugVariablesConfig> {
2146        self.debug_variables_config.as_ref()
2147    }
2148}
2149
2150impl CodeLabel {
2151    pub fn fallback_for_completion(
2152        item: &lsp::CompletionItem,
2153        language: Option<&Language>,
2154    ) -> Self {
2155        let highlight_id = item.kind.and_then(|kind| {
2156            let grammar = language?.grammar()?;
2157            use lsp::CompletionItemKind as Kind;
2158            match kind {
2159                Kind::CLASS => grammar.highlight_id_for_name("type"),
2160                Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
2161                Kind::CONSTRUCTOR => grammar.highlight_id_for_name("constructor"),
2162                Kind::ENUM => grammar
2163                    .highlight_id_for_name("enum")
2164                    .or_else(|| grammar.highlight_id_for_name("type")),
2165                Kind::ENUM_MEMBER => grammar
2166                    .highlight_id_for_name("variant")
2167                    .or_else(|| grammar.highlight_id_for_name("property")),
2168                Kind::FIELD => grammar.highlight_id_for_name("property"),
2169                Kind::FUNCTION => grammar.highlight_id_for_name("function"),
2170                Kind::INTERFACE => grammar.highlight_id_for_name("type"),
2171                Kind::METHOD => grammar
2172                    .highlight_id_for_name("function.method")
2173                    .or_else(|| grammar.highlight_id_for_name("function")),
2174                Kind::OPERATOR => grammar.highlight_id_for_name("operator"),
2175                Kind::PROPERTY => grammar.highlight_id_for_name("property"),
2176                Kind::STRUCT => grammar.highlight_id_for_name("type"),
2177                Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
2178                Kind::KEYWORD => grammar.highlight_id_for_name("keyword"),
2179                _ => None,
2180            }
2181        });
2182
2183        let label = &item.label;
2184        let label_length = label.len();
2185        let runs = highlight_id
2186            .map(|highlight_id| vec![(0..label_length, highlight_id)])
2187            .unwrap_or_default();
2188        let text = if let Some(detail) = item.detail.as_deref().filter(|detail| detail != label) {
2189            format!("{label} {detail}")
2190        } else if let Some(description) = item
2191            .label_details
2192            .as_ref()
2193            .and_then(|label_details| label_details.description.as_deref())
2194            .filter(|description| description != label)
2195        {
2196            format!("{label} {description}")
2197        } else {
2198            label.clone()
2199        };
2200        let filter_range = item
2201            .filter_text
2202            .as_deref()
2203            .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
2204            .unwrap_or(0..label_length);
2205        Self {
2206            text,
2207            runs,
2208            filter_range,
2209        }
2210    }
2211
2212    pub fn plain(text: String, filter_text: Option<&str>) -> Self {
2213        let filter_range = filter_text
2214            .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
2215            .unwrap_or(0..text.len());
2216        Self {
2217            runs: Vec::new(),
2218            filter_range,
2219            text,
2220        }
2221    }
2222
2223    pub fn push_str(&mut self, text: &str, highlight: Option<HighlightId>) {
2224        let start_ix = self.text.len();
2225        self.text.push_str(text);
2226        let end_ix = self.text.len();
2227        if let Some(highlight) = highlight {
2228            self.runs.push((start_ix..end_ix, highlight));
2229        }
2230    }
2231
2232    pub fn text(&self) -> &str {
2233        self.text.as_str()
2234    }
2235
2236    pub fn filter_text(&self) -> &str {
2237        &self.text[self.filter_range.clone()]
2238    }
2239}
2240
2241impl From<String> for CodeLabel {
2242    fn from(value: String) -> Self {
2243        Self::plain(value, None)
2244    }
2245}
2246
2247impl From<&str> for CodeLabel {
2248    fn from(value: &str) -> Self {
2249        Self::plain(value.to_string(), None)
2250    }
2251}
2252
2253impl Ord for LanguageMatcher {
2254    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
2255        self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
2256            self.first_line_pattern
2257                .as_ref()
2258                .map(Regex::as_str)
2259                .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
2260        })
2261    }
2262}
2263
2264impl PartialOrd for LanguageMatcher {
2265    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2266        Some(self.cmp(other))
2267    }
2268}
2269
2270impl Eq for LanguageMatcher {}
2271
2272impl PartialEq for LanguageMatcher {
2273    fn eq(&self, other: &Self) -> bool {
2274        self.path_suffixes == other.path_suffixes
2275            && self.first_line_pattern.as_ref().map(Regex::as_str)
2276                == other.first_line_pattern.as_ref().map(Regex::as_str)
2277    }
2278}
2279
2280#[cfg(any(test, feature = "test-support"))]
2281impl Default for FakeLspAdapter {
2282    fn default() -> Self {
2283        Self {
2284            name: "the-fake-language-server",
2285            capabilities: lsp::LanguageServer::full_capabilities(),
2286            initializer: None,
2287            disk_based_diagnostics_progress_token: None,
2288            initialization_options: None,
2289            disk_based_diagnostics_sources: Vec::new(),
2290            prettier_plugins: Vec::new(),
2291            language_server_binary: LanguageServerBinary {
2292                path: "/the/fake/lsp/path".into(),
2293                arguments: vec![],
2294                env: Default::default(),
2295            },
2296            label_for_completion: None,
2297        }
2298    }
2299}
2300
2301#[cfg(any(test, feature = "test-support"))]
2302impl LspInstaller for FakeLspAdapter {
2303    type BinaryVersion = ();
2304
2305    async fn fetch_latest_server_version(
2306        &self,
2307        _: &dyn LspAdapterDelegate,
2308        _: bool,
2309        _: &mut AsyncApp,
2310    ) -> Result<Self::BinaryVersion> {
2311        unreachable!()
2312    }
2313
2314    async fn check_if_user_installed(
2315        &self,
2316        _: &dyn LspAdapterDelegate,
2317        _: Option<Toolchain>,
2318        _: &AsyncApp,
2319    ) -> Option<LanguageServerBinary> {
2320        Some(self.language_server_binary.clone())
2321    }
2322
2323    async fn fetch_server_binary(
2324        &self,
2325        _: (),
2326        _: PathBuf,
2327        _: &dyn LspAdapterDelegate,
2328    ) -> Result<LanguageServerBinary> {
2329        unreachable!();
2330    }
2331
2332    async fn cached_server_binary(
2333        &self,
2334        _: PathBuf,
2335        _: &dyn LspAdapterDelegate,
2336    ) -> Option<LanguageServerBinary> {
2337        unreachable!();
2338    }
2339}
2340
2341#[cfg(any(test, feature = "test-support"))]
2342#[async_trait(?Send)]
2343impl LspAdapter for FakeLspAdapter {
2344    fn name(&self) -> LanguageServerName {
2345        LanguageServerName(self.name.into())
2346    }
2347
2348    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
2349        self.disk_based_diagnostics_sources.clone()
2350    }
2351
2352    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
2353        self.disk_based_diagnostics_progress_token.clone()
2354    }
2355
2356    async fn initialization_options(
2357        self: Arc<Self>,
2358        _: &Arc<dyn LspAdapterDelegate>,
2359    ) -> Result<Option<Value>> {
2360        Ok(self.initialization_options.clone())
2361    }
2362
2363    async fn label_for_completion(
2364        &self,
2365        item: &lsp::CompletionItem,
2366        language: &Arc<Language>,
2367    ) -> Option<CodeLabel> {
2368        let label_for_completion = self.label_for_completion.as_ref()?;
2369        label_for_completion(item, language)
2370    }
2371
2372    fn is_extension(&self) -> bool {
2373        false
2374    }
2375}
2376
2377enum Capture<'a> {
2378    Required(&'static str, &'a mut u32),
2379    Optional(&'static str, &'a mut Option<u32>),
2380}
2381
2382fn populate_capture_indices(
2383    query: &Query,
2384    language_name: &LanguageName,
2385    query_type: &str,
2386    expected_prefixes: &[&str],
2387    captures: &mut [Capture<'_>],
2388) -> bool {
2389    let mut found_required_indices = Vec::new();
2390    'outer: for (ix, name) in query.capture_names().iter().enumerate() {
2391        for (required_ix, capture) in captures.iter_mut().enumerate() {
2392            match capture {
2393                Capture::Required(capture_name, index) if capture_name == name => {
2394                    **index = ix as u32;
2395                    found_required_indices.push(required_ix);
2396                    continue 'outer;
2397                }
2398                Capture::Optional(capture_name, index) if capture_name == name => {
2399                    **index = Some(ix as u32);
2400                    continue 'outer;
2401                }
2402                _ => {}
2403            }
2404        }
2405        if !name.starts_with("_")
2406            && !expected_prefixes
2407                .iter()
2408                .any(|&prefix| name.starts_with(prefix))
2409        {
2410            log::warn!(
2411                "unrecognized capture name '{}' in {} {} TreeSitter query \
2412                (suppress this warning by prefixing with '_')",
2413                name,
2414                language_name,
2415                query_type
2416            );
2417        }
2418    }
2419    let mut missing_required_captures = Vec::new();
2420    for (capture_ix, capture) in captures.iter().enumerate() {
2421        if let Capture::Required(capture_name, _) = capture
2422            && !found_required_indices.contains(&capture_ix)
2423        {
2424            missing_required_captures.push(*capture_name);
2425        }
2426    }
2427    let success = missing_required_captures.is_empty();
2428    if !success {
2429        log::error!(
2430            "missing required capture(s) in {} {} TreeSitter query: {}",
2431            language_name,
2432            query_type,
2433            missing_required_captures.join(", ")
2434        );
2435    }
2436    success
2437}
2438
2439pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
2440    lsp::Position::new(point.row, point.column)
2441}
2442
2443pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
2444    Unclipped(PointUtf16::new(point.line, point.character))
2445}
2446
2447pub fn range_to_lsp(range: Range<PointUtf16>) -> Result<lsp::Range> {
2448    anyhow::ensure!(
2449        range.start <= range.end,
2450        "Inverted range provided to an LSP request: {:?}-{:?}",
2451        range.start,
2452        range.end
2453    );
2454    Ok(lsp::Range {
2455        start: point_to_lsp(range.start),
2456        end: point_to_lsp(range.end),
2457    })
2458}
2459
2460pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
2461    let mut start = point_from_lsp(range.start);
2462    let mut end = point_from_lsp(range.end);
2463    if start > end {
2464        log::warn!("range_from_lsp called with inverted range {start:?}-{end:?}");
2465        mem::swap(&mut start, &mut end);
2466    }
2467    start..end
2468}
2469
2470#[cfg(test)]
2471mod tests {
2472    use super::*;
2473    use gpui::TestAppContext;
2474    use pretty_assertions::assert_matches;
2475
2476    #[gpui::test(iterations = 10)]
2477    async fn test_language_loading(cx: &mut TestAppContext) {
2478        let languages = LanguageRegistry::test(cx.executor());
2479        let languages = Arc::new(languages);
2480        languages.register_native_grammars([
2481            ("json", tree_sitter_json::LANGUAGE),
2482            ("rust", tree_sitter_rust::LANGUAGE),
2483        ]);
2484        languages.register_test_language(LanguageConfig {
2485            name: "JSON".into(),
2486            grammar: Some("json".into()),
2487            matcher: LanguageMatcher {
2488                path_suffixes: vec!["json".into()],
2489                ..Default::default()
2490            },
2491            ..Default::default()
2492        });
2493        languages.register_test_language(LanguageConfig {
2494            name: "Rust".into(),
2495            grammar: Some("rust".into()),
2496            matcher: LanguageMatcher {
2497                path_suffixes: vec!["rs".into()],
2498                ..Default::default()
2499            },
2500            ..Default::default()
2501        });
2502        assert_eq!(
2503            languages.language_names(),
2504            &[
2505                LanguageName::new("JSON"),
2506                LanguageName::new("Plain Text"),
2507                LanguageName::new("Rust"),
2508            ]
2509        );
2510
2511        let rust1 = languages.language_for_name("Rust");
2512        let rust2 = languages.language_for_name("Rust");
2513
2514        // Ensure language is still listed even if it's being loaded.
2515        assert_eq!(
2516            languages.language_names(),
2517            &[
2518                LanguageName::new("JSON"),
2519                LanguageName::new("Plain Text"),
2520                LanguageName::new("Rust"),
2521            ]
2522        );
2523
2524        let (rust1, rust2) = futures::join!(rust1, rust2);
2525        assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
2526
2527        // Ensure language is still listed even after loading it.
2528        assert_eq!(
2529            languages.language_names(),
2530            &[
2531                LanguageName::new("JSON"),
2532                LanguageName::new("Plain Text"),
2533                LanguageName::new("Rust"),
2534            ]
2535        );
2536
2537        // Loading an unknown language returns an error.
2538        assert!(languages.language_for_name("Unknown").await.is_err());
2539    }
2540
2541    #[gpui::test]
2542    async fn test_completion_label_omits_duplicate_data() {
2543        let regular_completion_item_1 = lsp::CompletionItem {
2544            label: "regular1".to_string(),
2545            detail: Some("detail1".to_string()),
2546            label_details: Some(lsp::CompletionItemLabelDetails {
2547                detail: None,
2548                description: Some("description 1".to_string()),
2549            }),
2550            ..lsp::CompletionItem::default()
2551        };
2552
2553        let regular_completion_item_2 = lsp::CompletionItem {
2554            label: "regular2".to_string(),
2555            label_details: Some(lsp::CompletionItemLabelDetails {
2556                detail: None,
2557                description: Some("description 2".to_string()),
2558            }),
2559            ..lsp::CompletionItem::default()
2560        };
2561
2562        let completion_item_with_duplicate_detail_and_proper_description = lsp::CompletionItem {
2563            detail: Some(regular_completion_item_1.label.clone()),
2564            ..regular_completion_item_1.clone()
2565        };
2566
2567        let completion_item_with_duplicate_detail = lsp::CompletionItem {
2568            detail: Some(regular_completion_item_1.label.clone()),
2569            label_details: None,
2570            ..regular_completion_item_1.clone()
2571        };
2572
2573        let completion_item_with_duplicate_description = lsp::CompletionItem {
2574            label_details: Some(lsp::CompletionItemLabelDetails {
2575                detail: None,
2576                description: Some(regular_completion_item_2.label.clone()),
2577            }),
2578            ..regular_completion_item_2.clone()
2579        };
2580
2581        assert_eq!(
2582            CodeLabel::fallback_for_completion(&regular_completion_item_1, None).text,
2583            format!(
2584                "{} {}",
2585                regular_completion_item_1.label,
2586                regular_completion_item_1.detail.unwrap()
2587            ),
2588            "LSP completion items with both detail and label_details.description should prefer detail"
2589        );
2590        assert_eq!(
2591            CodeLabel::fallback_for_completion(&regular_completion_item_2, None).text,
2592            format!(
2593                "{} {}",
2594                regular_completion_item_2.label,
2595                regular_completion_item_2
2596                    .label_details
2597                    .as_ref()
2598                    .unwrap()
2599                    .description
2600                    .as_ref()
2601                    .unwrap()
2602            ),
2603            "LSP completion items without detail but with label_details.description should use that"
2604        );
2605        assert_eq!(
2606            CodeLabel::fallback_for_completion(
2607                &completion_item_with_duplicate_detail_and_proper_description,
2608                None
2609            )
2610            .text,
2611            format!(
2612                "{} {}",
2613                regular_completion_item_1.label,
2614                regular_completion_item_1
2615                    .label_details
2616                    .as_ref()
2617                    .unwrap()
2618                    .description
2619                    .as_ref()
2620                    .unwrap()
2621            ),
2622            "LSP completion items with both detail and label_details.description should prefer description only if the detail duplicates the completion label"
2623        );
2624        assert_eq!(
2625            CodeLabel::fallback_for_completion(&completion_item_with_duplicate_detail, None).text,
2626            regular_completion_item_1.label,
2627            "LSP completion items with duplicate label and detail, should omit the detail"
2628        );
2629        assert_eq!(
2630            CodeLabel::fallback_for_completion(&completion_item_with_duplicate_description, None)
2631                .text,
2632            regular_completion_item_2.label,
2633            "LSP completion items with duplicate label and detail, should omit the detail"
2634        );
2635    }
2636
2637    #[test]
2638    fn test_deserializing_comments_backwards_compat() {
2639        // current version of `block_comment` and `documentation_comment` work
2640        {
2641            let config: LanguageConfig = ::toml::from_str(
2642                r#"
2643                name = "Foo"
2644                block_comment = { start = "a", end = "b", prefix = "c", tab_size = 1 }
2645                documentation_comment = { start = "d", end = "e", prefix = "f", tab_size = 2 }
2646                "#,
2647            )
2648            .unwrap();
2649            assert_matches!(config.block_comment, Some(BlockCommentConfig { .. }));
2650            assert_matches!(
2651                config.documentation_comment,
2652                Some(BlockCommentConfig { .. })
2653            );
2654
2655            let block_config = config.block_comment.unwrap();
2656            assert_eq!(block_config.start.as_ref(), "a");
2657            assert_eq!(block_config.end.as_ref(), "b");
2658            assert_eq!(block_config.prefix.as_ref(), "c");
2659            assert_eq!(block_config.tab_size, 1);
2660
2661            let doc_config = config.documentation_comment.unwrap();
2662            assert_eq!(doc_config.start.as_ref(), "d");
2663            assert_eq!(doc_config.end.as_ref(), "e");
2664            assert_eq!(doc_config.prefix.as_ref(), "f");
2665            assert_eq!(doc_config.tab_size, 2);
2666        }
2667
2668        // former `documentation` setting is read into `documentation_comment`
2669        {
2670            let config: LanguageConfig = ::toml::from_str(
2671                r#"
2672                name = "Foo"
2673                documentation = { start = "a", end = "b", prefix = "c", tab_size = 1}
2674                "#,
2675            )
2676            .unwrap();
2677            assert_matches!(
2678                config.documentation_comment,
2679                Some(BlockCommentConfig { .. })
2680            );
2681
2682            let config = config.documentation_comment.unwrap();
2683            assert_eq!(config.start.as_ref(), "a");
2684            assert_eq!(config.end.as_ref(), "b");
2685            assert_eq!(config.prefix.as_ref(), "c");
2686            assert_eq!(config.tab_size, 1);
2687        }
2688
2689        // old block_comment format is read into BlockCommentConfig
2690        {
2691            let config: LanguageConfig = ::toml::from_str(
2692                r#"
2693                name = "Foo"
2694                block_comment = ["a", "b"]
2695                "#,
2696            )
2697            .unwrap();
2698            assert_matches!(config.block_comment, Some(BlockCommentConfig { .. }));
2699
2700            let config = config.block_comment.unwrap();
2701            assert_eq!(config.start.as_ref(), "a");
2702            assert_eq!(config.end.as_ref(), "b");
2703            assert_eq!(config.prefix.as_ref(), "");
2704            assert_eq!(config.tab_size, 0);
2705        }
2706    }
2707}