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(
 856            LanguageId(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst)),
 857            config,
 858            ts_language,
 859        )
 860    }
 861
 862    fn new_with_id(
 863        id: LanguageId,
 864        config: LanguageConfig,
 865        ts_language: Option<tree_sitter::Language>,
 866    ) -> Self {
 867        Self {
 868            id,
 869            config,
 870            grammar: ts_language.map(|ts_language| {
 871                Arc::new(Grammar {
 872                    id: GrammarId::new(),
 873                    highlights_query: None,
 874                    brackets_config: None,
 875                    outline_config: None,
 876                    embedding_config: None,
 877                    indents_config: None,
 878                    injection_config: None,
 879                    override_config: None,
 880                    redactions_config: None,
 881                    error_query: Query::new(&ts_language, "(ERROR) @error").unwrap(),
 882                    ts_language,
 883                    highlight_map: Default::default(),
 884                })
 885            }),
 886            context_provider: None,
 887        }
 888    }
 889
 890    pub fn with_context_provider(
 891        mut self,
 892        provider: Option<Arc<dyn LanguageContextProvider>>,
 893    ) -> Self {
 894        self.context_provider = provider;
 895        self
 896    }
 897
 898    pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
 899        if let Some(query) = queries.highlights {
 900            self = self
 901                .with_highlights_query(query.as_ref())
 902                .context("Error loading highlights query")?;
 903        }
 904        if let Some(query) = queries.brackets {
 905            self = self
 906                .with_brackets_query(query.as_ref())
 907                .context("Error loading brackets query")?;
 908        }
 909        if let Some(query) = queries.indents {
 910            self = self
 911                .with_indents_query(query.as_ref())
 912                .context("Error loading indents query")?;
 913        }
 914        if let Some(query) = queries.outline {
 915            self = self
 916                .with_outline_query(query.as_ref())
 917                .context("Error loading outline query")?;
 918        }
 919        if let Some(query) = queries.embedding {
 920            self = self
 921                .with_embedding_query(query.as_ref())
 922                .context("Error loading embedding query")?;
 923        }
 924        if let Some(query) = queries.injections {
 925            self = self
 926                .with_injection_query(query.as_ref())
 927                .context("Error loading injection query")?;
 928        }
 929        if let Some(query) = queries.overrides {
 930            self = self
 931                .with_override_query(query.as_ref())
 932                .context("Error loading override query")?;
 933        }
 934        if let Some(query) = queries.redactions {
 935            self = self
 936                .with_redaction_query(query.as_ref())
 937                .context("Error loading redaction query")?;
 938        }
 939        Ok(self)
 940    }
 941
 942    pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
 943        let grammar = self.grammar_mut();
 944        grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
 945        Ok(self)
 946    }
 947
 948    pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
 949        let grammar = self.grammar_mut();
 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 extra_context_capture_ix = None;
 955        get_capture_indices(
 956            &query,
 957            &mut [
 958                ("item", &mut item_capture_ix),
 959                ("name", &mut name_capture_ix),
 960                ("context", &mut context_capture_ix),
 961                ("context.extra", &mut extra_context_capture_ix),
 962            ],
 963        );
 964        if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
 965            grammar.outline_config = Some(OutlineConfig {
 966                query,
 967                item_capture_ix,
 968                name_capture_ix,
 969                context_capture_ix,
 970                extra_context_capture_ix,
 971            });
 972        }
 973        Ok(self)
 974    }
 975
 976    pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
 977        let grammar = self.grammar_mut();
 978        let query = Query::new(&grammar.ts_language, source)?;
 979        let mut item_capture_ix = None;
 980        let mut name_capture_ix = None;
 981        let mut context_capture_ix = None;
 982        let mut collapse_capture_ix = None;
 983        let mut keep_capture_ix = None;
 984        get_capture_indices(
 985            &query,
 986            &mut [
 987                ("item", &mut item_capture_ix),
 988                ("name", &mut name_capture_ix),
 989                ("context", &mut context_capture_ix),
 990                ("keep", &mut keep_capture_ix),
 991                ("collapse", &mut collapse_capture_ix),
 992            ],
 993        );
 994        if let Some(item_capture_ix) = item_capture_ix {
 995            grammar.embedding_config = Some(EmbeddingConfig {
 996                query,
 997                item_capture_ix,
 998                name_capture_ix,
 999                context_capture_ix,
1000                collapse_capture_ix,
1001                keep_capture_ix,
1002            });
1003        }
1004        Ok(self)
1005    }
1006
1007    pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1008        let grammar = self.grammar_mut();
1009        let query = Query::new(&grammar.ts_language, source)?;
1010        let mut open_capture_ix = None;
1011        let mut close_capture_ix = None;
1012        get_capture_indices(
1013            &query,
1014            &mut [
1015                ("open", &mut open_capture_ix),
1016                ("close", &mut close_capture_ix),
1017            ],
1018        );
1019        if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1020            grammar.brackets_config = Some(BracketConfig {
1021                query,
1022                open_capture_ix,
1023                close_capture_ix,
1024            });
1025        }
1026        Ok(self)
1027    }
1028
1029    pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1030        let grammar = self.grammar_mut();
1031        let query = Query::new(&grammar.ts_language, source)?;
1032        let mut indent_capture_ix = None;
1033        let mut start_capture_ix = None;
1034        let mut end_capture_ix = None;
1035        let mut outdent_capture_ix = None;
1036        get_capture_indices(
1037            &query,
1038            &mut [
1039                ("indent", &mut indent_capture_ix),
1040                ("start", &mut start_capture_ix),
1041                ("end", &mut end_capture_ix),
1042                ("outdent", &mut outdent_capture_ix),
1043            ],
1044        );
1045        if let Some(indent_capture_ix) = indent_capture_ix {
1046            grammar.indents_config = Some(IndentConfig {
1047                query,
1048                indent_capture_ix,
1049                start_capture_ix,
1050                end_capture_ix,
1051                outdent_capture_ix,
1052            });
1053        }
1054        Ok(self)
1055    }
1056
1057    pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1058        let grammar = self.grammar_mut();
1059        let query = Query::new(&grammar.ts_language, source)?;
1060        let mut language_capture_ix = None;
1061        let mut content_capture_ix = None;
1062        get_capture_indices(
1063            &query,
1064            &mut [
1065                ("language", &mut language_capture_ix),
1066                ("content", &mut content_capture_ix),
1067            ],
1068        );
1069        let patterns = (0..query.pattern_count())
1070            .map(|ix| {
1071                let mut config = InjectionPatternConfig::default();
1072                for setting in query.property_settings(ix) {
1073                    match setting.key.as_ref() {
1074                        "language" => {
1075                            config.language = setting.value.clone();
1076                        }
1077                        "combined" => {
1078                            config.combined = true;
1079                        }
1080                        _ => {}
1081                    }
1082                }
1083                config
1084            })
1085            .collect();
1086        if let Some(content_capture_ix) = content_capture_ix {
1087            grammar.injection_config = Some(InjectionConfig {
1088                query,
1089                language_capture_ix,
1090                content_capture_ix,
1091                patterns,
1092            });
1093        }
1094        Ok(self)
1095    }
1096
1097    pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1098        let query = Query::new(&self.grammar_mut().ts_language, source)?;
1099
1100        let mut override_configs_by_id = HashMap::default();
1101        for (ix, name) in query.capture_names().iter().enumerate() {
1102            if !name.starts_with('_') {
1103                let value = self.config.overrides.remove(*name).unwrap_or_default();
1104                for server_name in &value.opt_into_language_servers {
1105                    if !self
1106                        .config
1107                        .scope_opt_in_language_servers
1108                        .contains(server_name)
1109                    {
1110                        util::debug_panic!("Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server");
1111                    }
1112                }
1113
1114                override_configs_by_id.insert(ix as u32, (name.to_string(), value));
1115            }
1116        }
1117
1118        if !self.config.overrides.is_empty() {
1119            let keys = self.config.overrides.keys().collect::<Vec<_>>();
1120            Err(anyhow!(
1121                "language {:?} has overrides in config not in query: {keys:?}",
1122                self.config.name
1123            ))?;
1124        }
1125
1126        for disabled_scope_name in self
1127            .config
1128            .brackets
1129            .disabled_scopes_by_bracket_ix
1130            .iter()
1131            .flatten()
1132        {
1133            if !override_configs_by_id
1134                .values()
1135                .any(|(scope_name, _)| scope_name == disabled_scope_name)
1136            {
1137                Err(anyhow!(
1138                    "language {:?} has overrides in config not in query: {disabled_scope_name:?}",
1139                    self.config.name
1140                ))?;
1141            }
1142        }
1143
1144        for (name, override_config) in override_configs_by_id.values_mut() {
1145            override_config.disabled_bracket_ixs = self
1146                .config
1147                .brackets
1148                .disabled_scopes_by_bracket_ix
1149                .iter()
1150                .enumerate()
1151                .filter_map(|(ix, disabled_scope_names)| {
1152                    if disabled_scope_names.contains(name) {
1153                        Some(ix as u16)
1154                    } else {
1155                        None
1156                    }
1157                })
1158                .collect();
1159        }
1160
1161        self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1162        self.grammar_mut().override_config = Some(OverrideConfig {
1163            query,
1164            values: override_configs_by_id,
1165        });
1166        Ok(self)
1167    }
1168
1169    pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1170        let grammar = self.grammar_mut();
1171        let query = Query::new(&grammar.ts_language, source)?;
1172        let mut redaction_capture_ix = None;
1173        get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1174
1175        if let Some(redaction_capture_ix) = redaction_capture_ix {
1176            grammar.redactions_config = Some(RedactionConfig {
1177                query,
1178                redaction_capture_ix,
1179            });
1180        }
1181
1182        Ok(self)
1183    }
1184
1185    fn grammar_mut(&mut self) -> &mut Grammar {
1186        Arc::get_mut(self.grammar.as_mut().unwrap()).unwrap()
1187    }
1188
1189    pub fn name(&self) -> Arc<str> {
1190        self.config.name.clone()
1191    }
1192
1193    pub fn context_provider(&self) -> Option<Arc<dyn LanguageContextProvider>> {
1194        self.context_provider.clone()
1195    }
1196
1197    pub fn highlight_text<'a>(
1198        self: &'a Arc<Self>,
1199        text: &'a Rope,
1200        range: Range<usize>,
1201    ) -> Vec<(Range<usize>, HighlightId)> {
1202        let mut result = Vec::new();
1203        if let Some(grammar) = &self.grammar {
1204            let tree = grammar.parse_text(text, None);
1205            let captures =
1206                SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1207                    grammar.highlights_query.as_ref()
1208                });
1209            let highlight_maps = vec![grammar.highlight_map()];
1210            let mut offset = 0;
1211            for chunk in BufferChunks::new(text, range, Some((captures, highlight_maps)), vec![]) {
1212                let end_offset = offset + chunk.text.len();
1213                if let Some(highlight_id) = chunk.syntax_highlight_id {
1214                    if !highlight_id.is_default() {
1215                        result.push((offset..end_offset, highlight_id));
1216                    }
1217                }
1218                offset = end_offset;
1219            }
1220        }
1221        result
1222    }
1223
1224    pub fn path_suffixes(&self) -> &[String] {
1225        &self.config.matcher.path_suffixes
1226    }
1227
1228    pub fn should_autoclose_before(&self, c: char) -> bool {
1229        c.is_whitespace() || self.config.autoclose_before.contains(c)
1230    }
1231
1232    pub fn set_theme(&self, theme: &SyntaxTheme) {
1233        if let Some(grammar) = self.grammar.as_ref() {
1234            if let Some(highlights_query) = &grammar.highlights_query {
1235                *grammar.highlight_map.lock() =
1236                    HighlightMap::new(highlights_query.capture_names(), theme);
1237            }
1238        }
1239    }
1240
1241    pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1242        self.grammar.as_ref()
1243    }
1244
1245    pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1246        LanguageScope {
1247            language: self.clone(),
1248            override_id: None,
1249        }
1250    }
1251
1252    pub fn prettier_parser_name(&self) -> Option<&str> {
1253        self.config.prettier_parser_name.as_deref()
1254    }
1255}
1256
1257impl LanguageScope {
1258    pub fn collapsed_placeholder(&self) -> &str {
1259        self.language.config.collapsed_placeholder.as_ref()
1260    }
1261
1262    /// Returns line prefix that is inserted in e.g. line continuations or
1263    /// in `toggle comments` action.
1264    pub fn line_comment_prefixes(&self) -> Option<&Vec<Arc<str>>> {
1265        Override::as_option(
1266            self.config_override().map(|o| &o.line_comments),
1267            Some(&self.language.config.line_comments),
1268        )
1269    }
1270
1271    pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1272        Override::as_option(
1273            self.config_override().map(|o| &o.block_comment),
1274            self.language.config.block_comment.as_ref(),
1275        )
1276        .map(|e| (&e.0, &e.1))
1277    }
1278
1279    /// Returns a list of language-specific word characters.
1280    ///
1281    /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1282    /// the purpose of actions like 'move to next word end` or whole-word search.
1283    /// It additionally accounts for language's additional word characters.
1284    pub fn word_characters(&self) -> Option<&HashSet<char>> {
1285        Override::as_option(
1286            self.config_override().map(|o| &o.word_characters),
1287            Some(&self.language.config.word_characters),
1288        )
1289    }
1290
1291    /// Returns a list of bracket pairs for a given language with an additional
1292    /// piece of information about whether the particular bracket pair is currently active for a given language.
1293    pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1294        let mut disabled_ids = self
1295            .config_override()
1296            .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1297        self.language
1298            .config
1299            .brackets
1300            .pairs
1301            .iter()
1302            .enumerate()
1303            .map(move |(ix, bracket)| {
1304                let mut is_enabled = true;
1305                if let Some(next_disabled_ix) = disabled_ids.first() {
1306                    if ix == *next_disabled_ix as usize {
1307                        disabled_ids = &disabled_ids[1..];
1308                        is_enabled = false;
1309                    }
1310                }
1311                (bracket, is_enabled)
1312            })
1313    }
1314
1315    pub fn should_autoclose_before(&self, c: char) -> bool {
1316        c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1317    }
1318
1319    pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1320        let config = &self.language.config;
1321        let opt_in_servers = &config.scope_opt_in_language_servers;
1322        if opt_in_servers.iter().any(|o| *o == *name.0) {
1323            if let Some(over) = self.config_override() {
1324                over.opt_into_language_servers.iter().any(|o| *o == *name.0)
1325            } else {
1326                false
1327            }
1328        } else {
1329            true
1330        }
1331    }
1332
1333    fn config_override(&self) -> Option<&LanguageConfigOverride> {
1334        let id = self.override_id?;
1335        let grammar = self.language.grammar.as_ref()?;
1336        let override_config = grammar.override_config.as_ref()?;
1337        override_config.values.get(&id).map(|e| &e.1)
1338    }
1339}
1340
1341impl Hash for Language {
1342    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1343        self.id.hash(state)
1344    }
1345}
1346
1347impl PartialEq for Language {
1348    fn eq(&self, other: &Self) -> bool {
1349        self.id.eq(&other.id)
1350    }
1351}
1352
1353impl Eq for Language {}
1354
1355impl Debug for Language {
1356    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1357        f.debug_struct("Language")
1358            .field("name", &self.config.name)
1359            .finish()
1360    }
1361}
1362
1363impl Grammar {
1364    pub fn id(&self) -> GrammarId {
1365        self.id
1366    }
1367
1368    fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1369        PARSER.with(|parser| {
1370            let mut parser = parser.borrow_mut();
1371            parser
1372                .set_language(&self.ts_language)
1373                .expect("incompatible grammar");
1374            let mut chunks = text.chunks_in_range(0..text.len());
1375            parser
1376                .parse_with(
1377                    &mut move |offset, _| {
1378                        chunks.seek(offset);
1379                        chunks.next().unwrap_or("").as_bytes()
1380                    },
1381                    old_tree.as_ref(),
1382                )
1383                .unwrap()
1384        })
1385    }
1386
1387    pub fn highlight_map(&self) -> HighlightMap {
1388        self.highlight_map.lock().clone()
1389    }
1390
1391    pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1392        let capture_id = self
1393            .highlights_query
1394            .as_ref()?
1395            .capture_index_for_name(name)?;
1396        Some(self.highlight_map.lock().get(capture_id))
1397    }
1398}
1399
1400impl CodeLabel {
1401    pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1402        let mut result = Self {
1403            runs: Vec::new(),
1404            filter_range: 0..text.len(),
1405            text,
1406        };
1407        if let Some(filter_text) = filter_text {
1408            if let Some(ix) = result.text.find(filter_text) {
1409                result.filter_range = ix..ix + filter_text.len();
1410            }
1411        }
1412        result
1413    }
1414}
1415
1416impl Ord for LanguageMatcher {
1417    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1418        self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
1419            self.first_line_pattern
1420                .as_ref()
1421                .map(Regex::as_str)
1422                .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
1423        })
1424    }
1425}
1426
1427impl PartialOrd for LanguageMatcher {
1428    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1429        Some(self.cmp(other))
1430    }
1431}
1432
1433impl Eq for LanguageMatcher {}
1434
1435impl PartialEq for LanguageMatcher {
1436    fn eq(&self, other: &Self) -> bool {
1437        self.path_suffixes == other.path_suffixes
1438            && self.first_line_pattern.as_ref().map(Regex::as_str)
1439                == other.first_line_pattern.as_ref().map(Regex::as_str)
1440    }
1441}
1442
1443#[cfg(any(test, feature = "test-support"))]
1444impl Default for FakeLspAdapter {
1445    fn default() -> Self {
1446        Self {
1447            name: "the-fake-language-server",
1448            capabilities: lsp::LanguageServer::full_capabilities(),
1449            initializer: None,
1450            disk_based_diagnostics_progress_token: None,
1451            initialization_options: None,
1452            disk_based_diagnostics_sources: Vec::new(),
1453            prettier_plugins: Vec::new(),
1454            language_server_binary: LanguageServerBinary {
1455                path: "/the/fake/lsp/path".into(),
1456                arguments: vec![],
1457                env: Default::default(),
1458            },
1459        }
1460    }
1461}
1462
1463#[cfg(any(test, feature = "test-support"))]
1464#[async_trait]
1465impl LspAdapter for FakeLspAdapter {
1466    fn name(&self) -> LanguageServerName {
1467        LanguageServerName(self.name.into())
1468    }
1469
1470    fn get_language_server_command<'a>(
1471        self: Arc<Self>,
1472        _: Arc<Language>,
1473        _: Arc<Path>,
1474        _: Arc<dyn LspAdapterDelegate>,
1475        _: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
1476        _: &'a mut AsyncAppContext,
1477    ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
1478        async move { Ok(self.language_server_binary.clone()) }.boxed_local()
1479    }
1480
1481    async fn fetch_latest_server_version(
1482        &self,
1483        _: &dyn LspAdapterDelegate,
1484    ) -> Result<Box<dyn 'static + Send + Any>> {
1485        unreachable!();
1486    }
1487
1488    async fn fetch_server_binary(
1489        &self,
1490        _: Box<dyn 'static + Send + Any>,
1491        _: PathBuf,
1492        _: &dyn LspAdapterDelegate,
1493    ) -> Result<LanguageServerBinary> {
1494        unreachable!();
1495    }
1496
1497    async fn cached_server_binary(
1498        &self,
1499        _: PathBuf,
1500        _: &dyn LspAdapterDelegate,
1501    ) -> Option<LanguageServerBinary> {
1502        unreachable!();
1503    }
1504
1505    async fn installation_test_binary(&self, _: PathBuf) -> Option<LanguageServerBinary> {
1506        unreachable!();
1507    }
1508
1509    fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
1510
1511    fn disk_based_diagnostic_sources(&self) -> Vec<String> {
1512        self.disk_based_diagnostics_sources.clone()
1513    }
1514
1515    fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
1516        self.disk_based_diagnostics_progress_token.clone()
1517    }
1518
1519    fn initialization_options(&self) -> Option<Value> {
1520        self.initialization_options.clone()
1521    }
1522
1523    fn prettier_plugins(&self) -> &[&'static str] {
1524        &self.prettier_plugins
1525    }
1526
1527    fn as_fake(&self) -> Option<&FakeLspAdapter> {
1528        Some(self)
1529    }
1530}
1531
1532fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
1533    for (ix, name) in query.capture_names().iter().enumerate() {
1534        for (capture_name, index) in captures.iter_mut() {
1535            if capture_name == name {
1536                **index = Some(ix as u32);
1537                break;
1538            }
1539        }
1540    }
1541}
1542
1543pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
1544    lsp::Position::new(point.row, point.column)
1545}
1546
1547pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
1548    Unclipped(PointUtf16::new(point.line, point.character))
1549}
1550
1551pub fn range_to_lsp(range: Range<PointUtf16>) -> lsp::Range {
1552    lsp::Range {
1553        start: point_to_lsp(range.start),
1554        end: point_to_lsp(range.end),
1555    }
1556}
1557
1558pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
1559    let mut start = point_from_lsp(range.start);
1560    let mut end = point_from_lsp(range.end);
1561    if start > end {
1562        mem::swap(&mut start, &mut end);
1563    }
1564    start..end
1565}
1566
1567#[cfg(test)]
1568mod tests {
1569    use super::*;
1570    use gpui::TestAppContext;
1571
1572    #[gpui::test(iterations = 10)]
1573    async fn test_first_line_pattern(cx: &mut TestAppContext) {
1574        let mut languages = LanguageRegistry::test();
1575
1576        languages.set_executor(cx.executor());
1577        let languages = Arc::new(languages);
1578        languages.register_test_language(LanguageConfig {
1579            name: "JavaScript".into(),
1580            matcher: LanguageMatcher {
1581                path_suffixes: vec!["js".into()],
1582                first_line_pattern: Some(Regex::new(r"\bnode\b").unwrap()),
1583            },
1584            ..Default::default()
1585        });
1586
1587        languages
1588            .language_for_file("the/script".as_ref(), None)
1589            .await
1590            .unwrap_err();
1591        languages
1592            .language_for_file("the/script".as_ref(), Some(&"nothing".into()))
1593            .await
1594            .unwrap_err();
1595        assert_eq!(
1596            languages
1597                .language_for_file("the/script".as_ref(), Some(&"#!/bin/env node".into()))
1598                .await
1599                .unwrap()
1600                .name()
1601                .as_ref(),
1602            "JavaScript"
1603        );
1604    }
1605
1606    #[gpui::test(iterations = 10)]
1607    async fn test_language_loading(cx: &mut TestAppContext) {
1608        let mut languages = LanguageRegistry::test();
1609        languages.set_executor(cx.executor());
1610        let languages = Arc::new(languages);
1611        languages.register_native_grammars([
1612            ("json", tree_sitter_json::language()),
1613            ("rust", tree_sitter_rust::language()),
1614        ]);
1615        languages.register_test_language(LanguageConfig {
1616            name: "JSON".into(),
1617            grammar: Some("json".into()),
1618            matcher: LanguageMatcher {
1619                path_suffixes: vec!["json".into()],
1620                ..Default::default()
1621            },
1622            ..Default::default()
1623        });
1624        languages.register_test_language(LanguageConfig {
1625            name: "Rust".into(),
1626            grammar: Some("rust".into()),
1627            matcher: LanguageMatcher {
1628                path_suffixes: vec!["rs".into()],
1629                ..Default::default()
1630            },
1631            ..Default::default()
1632        });
1633        assert_eq!(
1634            languages.language_names(),
1635            &[
1636                "JSON".to_string(),
1637                "Plain Text".to_string(),
1638                "Rust".to_string(),
1639            ]
1640        );
1641
1642        let rust1 = languages.language_for_name("Rust");
1643        let rust2 = languages.language_for_name("Rust");
1644
1645        // Ensure language is still listed even if it's being loaded.
1646        assert_eq!(
1647            languages.language_names(),
1648            &[
1649                "JSON".to_string(),
1650                "Plain Text".to_string(),
1651                "Rust".to_string(),
1652            ]
1653        );
1654
1655        let (rust1, rust2) = futures::join!(rust1, rust2);
1656        assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
1657
1658        // Ensure language is still listed even after loading it.
1659        assert_eq!(
1660            languages.language_names(),
1661            &[
1662                "JSON".to_string(),
1663                "Plain Text".to_string(),
1664                "Rust".to_string(),
1665            ]
1666        );
1667
1668        // Loading an unknown language returns an error.
1669        assert!(languages.language_for_name("Unknown").await.is_err());
1670    }
1671}