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