language.rs

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