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