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