language.rs

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