language.rs

   1mod buffer;
   2mod diagnostic_set;
   3mod highlight_map;
   4pub mod language_settings;
   5mod outline;
   6pub mod proto;
   7mod syntax_map;
   8
   9#[cfg(test)]
  10mod buffer_tests;
  11
  12use anyhow::{anyhow, Context, Result};
  13use async_trait::async_trait;
  14use collections::HashMap;
  15use futures::{
  16    channel::oneshot,
  17    future::{BoxFuture, Shared},
  18    FutureExt, TryFutureExt as _,
  19};
  20use gpui::{executor::Background, AppContext, AsyncAppContext, Task};
  21use highlight_map::HighlightMap;
  22use lazy_static::lazy_static;
  23use lsp::CodeActionKind;
  24use parking_lot::{Mutex, RwLock};
  25use postage::watch;
  26use regex::Regex;
  27use serde::{de, Deserialize, Deserializer};
  28use serde_json::Value;
  29use std::{
  30    any::Any,
  31    borrow::Cow,
  32    cell::RefCell,
  33    ffi::OsString,
  34    fmt::Debug,
  35    hash::Hash,
  36    mem,
  37    ops::{Not, Range},
  38    path::{Path, PathBuf},
  39    str,
  40    sync::{
  41        atomic::{AtomicUsize, Ordering::SeqCst},
  42        Arc,
  43    },
  44};
  45use syntax_map::SyntaxSnapshot;
  46use theme::{SyntaxTheme, Theme};
  47use tree_sitter::{self, Query};
  48use unicase::UniCase;
  49use util::http::HttpClient;
  50use util::{merge_json_value_into, post_inc, ResultExt, TryFutureExt as _, UnwrapFuture};
  51
  52#[cfg(any(test, feature = "test-support"))]
  53use futures::channel::mpsc;
  54
  55pub use buffer::Operation;
  56pub use buffer::*;
  57pub use diagnostic_set::DiagnosticEntry;
  58pub use lsp::LanguageServerId;
  59pub use outline::{Outline, OutlineItem};
  60pub use syntax_map::{OwnedSyntaxLayerInfo, SyntaxLayerInfo};
  61pub use tree_sitter::{Parser, Tree};
  62
  63pub fn init(cx: &mut AppContext) {
  64    language_settings::init(cx);
  65}
  66
  67thread_local! {
  68    static PARSER: RefCell<Parser> = RefCell::new(Parser::new());
  69}
  70
  71lazy_static! {
  72    pub static ref NEXT_GRAMMAR_ID: AtomicUsize = Default::default();
  73    pub static ref PLAIN_TEXT: Arc<Language> = Arc::new(Language::new(
  74        LanguageConfig {
  75            name: "Plain Text".into(),
  76            ..Default::default()
  77        },
  78        None,
  79    ));
  80}
  81
  82pub trait ToLspPosition {
  83    fn to_lsp_position(self) -> lsp::Position;
  84}
  85
  86#[derive(Clone, Debug, PartialEq, Eq, Hash)]
  87pub struct LanguageServerName(pub Arc<str>);
  88
  89#[derive(Debug, Clone, Deserialize)]
  90pub struct LanguageServerBinary {
  91    pub path: PathBuf,
  92    pub arguments: Vec<OsString>,
  93}
  94
  95/// Represents a Language Server, with certain cached sync properties.
  96/// Uses [`LspAdapter`] under the hood, but calls all 'static' methods
  97/// once at startup, and caches the results.
  98pub struct CachedLspAdapter {
  99    pub name: LanguageServerName,
 100    pub initialization_options: Option<Value>,
 101    pub disk_based_diagnostic_sources: Vec<String>,
 102    pub disk_based_diagnostics_progress_token: Option<String>,
 103    pub language_ids: HashMap<String, String>,
 104    pub adapter: Arc<dyn LspAdapter>,
 105}
 106
 107impl CachedLspAdapter {
 108    pub async fn new(adapter: Arc<dyn LspAdapter>) -> Arc<Self> {
 109        let name = adapter.name().await;
 110        let initialization_options = adapter.initialization_options().await;
 111        let disk_based_diagnostic_sources = adapter.disk_based_diagnostic_sources().await;
 112        let disk_based_diagnostics_progress_token =
 113            adapter.disk_based_diagnostics_progress_token().await;
 114        let language_ids = adapter.language_ids().await;
 115
 116        Arc::new(CachedLspAdapter {
 117            name,
 118            initialization_options,
 119            disk_based_diagnostic_sources,
 120            disk_based_diagnostics_progress_token,
 121            language_ids,
 122            adapter,
 123        })
 124    }
 125
 126    pub async fn fetch_latest_server_version(
 127        &self,
 128        delegate: &dyn LspAdapterDelegate,
 129    ) -> Result<Box<dyn 'static + Send + Any>> {
 130        self.adapter.fetch_latest_server_version(delegate).await
 131    }
 132
 133    pub fn will_fetch_server(
 134        &self,
 135        delegate: &Arc<dyn LspAdapterDelegate>,
 136        cx: &mut AsyncAppContext,
 137    ) -> Option<Task<Result<()>>> {
 138        self.adapter.will_fetch_server(delegate, cx)
 139    }
 140
 141    pub fn will_start_server(
 142        &self,
 143        delegate: &Arc<dyn LspAdapterDelegate>,
 144        cx: &mut AsyncAppContext,
 145    ) -> Option<Task<Result<()>>> {
 146        self.adapter.will_start_server(delegate, cx)
 147    }
 148
 149    pub async fn fetch_server_binary(
 150        &self,
 151        version: Box<dyn 'static + Send + Any>,
 152        container_dir: PathBuf,
 153        delegate: &dyn LspAdapterDelegate,
 154    ) -> Result<LanguageServerBinary> {
 155        self.adapter
 156            .fetch_server_binary(version, container_dir, delegate)
 157            .await
 158    }
 159
 160    pub async fn cached_server_binary(
 161        &self,
 162        container_dir: PathBuf,
 163        delegate: &dyn LspAdapterDelegate,
 164    ) -> Option<LanguageServerBinary> {
 165        self.adapter
 166            .cached_server_binary(container_dir, delegate)
 167            .await
 168    }
 169
 170    pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
 171        self.adapter.code_action_kinds()
 172    }
 173
 174    pub fn workspace_configuration(
 175        &self,
 176        cx: &mut AppContext,
 177    ) -> Option<BoxFuture<'static, Value>> {
 178        self.adapter.workspace_configuration(cx)
 179    }
 180
 181    pub async fn process_diagnostics(&self, params: &mut lsp::PublishDiagnosticsParams) {
 182        self.adapter.process_diagnostics(params).await
 183    }
 184
 185    pub async fn process_completion(&self, completion_item: &mut lsp::CompletionItem) {
 186        self.adapter.process_completion(completion_item).await
 187    }
 188
 189    pub async fn label_for_completion(
 190        &self,
 191        completion_item: &lsp::CompletionItem,
 192        language: &Arc<Language>,
 193    ) -> Option<CodeLabel> {
 194        self.adapter
 195            .label_for_completion(completion_item, language)
 196            .await
 197    }
 198
 199    pub async fn label_for_symbol(
 200        &self,
 201        name: &str,
 202        kind: lsp::SymbolKind,
 203        language: &Arc<Language>,
 204    ) -> Option<CodeLabel> {
 205        self.adapter.label_for_symbol(name, kind, language).await
 206    }
 207}
 208
 209pub trait LspAdapterDelegate: Send + Sync {
 210    fn show_notification(&self, message: &str, cx: &mut AppContext);
 211    fn http_client(&self) -> Arc<dyn HttpClient>;
 212}
 213
 214#[async_trait]
 215pub trait LspAdapter: 'static + Send + Sync {
 216    async fn name(&self) -> LanguageServerName;
 217
 218    async fn fetch_latest_server_version(
 219        &self,
 220        delegate: &dyn LspAdapterDelegate,
 221    ) -> Result<Box<dyn 'static + Send + Any>>;
 222
 223    fn will_fetch_server(
 224        &self,
 225        _: &Arc<dyn LspAdapterDelegate>,
 226        _: &mut AsyncAppContext,
 227    ) -> Option<Task<Result<()>>> {
 228        None
 229    }
 230
 231    fn will_start_server(
 232        &self,
 233        _: &Arc<dyn LspAdapterDelegate>,
 234        _: &mut AsyncAppContext,
 235    ) -> Option<Task<Result<()>>> {
 236        None
 237    }
 238
 239    async fn fetch_server_binary(
 240        &self,
 241        version: Box<dyn 'static + Send + Any>,
 242        container_dir: PathBuf,
 243        delegate: &dyn LspAdapterDelegate,
 244    ) -> Result<LanguageServerBinary>;
 245
 246    async fn cached_server_binary(
 247        &self,
 248        container_dir: PathBuf,
 249        delegate: &dyn LspAdapterDelegate,
 250    ) -> Option<LanguageServerBinary>;
 251
 252    async fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
 253
 254    async fn process_completion(&self, _: &mut lsp::CompletionItem) {}
 255
 256    async fn label_for_completion(
 257        &self,
 258        _: &lsp::CompletionItem,
 259        _: &Arc<Language>,
 260    ) -> Option<CodeLabel> {
 261        None
 262    }
 263
 264    async fn label_for_symbol(
 265        &self,
 266        _: &str,
 267        _: lsp::SymbolKind,
 268        _: &Arc<Language>,
 269    ) -> Option<CodeLabel> {
 270        None
 271    }
 272
 273    async fn initialization_options(&self) -> Option<Value> {
 274        None
 275    }
 276
 277    fn workspace_configuration(&self, _: &mut AppContext) -> Option<BoxFuture<'static, Value>> {
 278        None
 279    }
 280
 281    fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
 282        Some(vec![
 283            CodeActionKind::EMPTY,
 284            CodeActionKind::QUICKFIX,
 285            CodeActionKind::REFACTOR,
 286            CodeActionKind::REFACTOR_EXTRACT,
 287            CodeActionKind::SOURCE,
 288        ])
 289    }
 290
 291    async fn disk_based_diagnostic_sources(&self) -> Vec<String> {
 292        Default::default()
 293    }
 294
 295    async fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
 296        None
 297    }
 298
 299    async fn language_ids(&self) -> HashMap<String, String> {
 300        Default::default()
 301    }
 302}
 303
 304#[derive(Clone, Debug, PartialEq, Eq)]
 305pub struct CodeLabel {
 306    pub text: String,
 307    pub runs: Vec<(Range<usize>, HighlightId)>,
 308    pub filter_range: Range<usize>,
 309}
 310
 311#[derive(Clone, Deserialize)]
 312pub struct LanguageConfig {
 313    pub name: Arc<str>,
 314    pub path_suffixes: Vec<String>,
 315    pub brackets: BracketPairConfig,
 316    #[serde(default, deserialize_with = "deserialize_regex")]
 317    pub first_line_pattern: Option<Regex>,
 318    #[serde(default = "auto_indent_using_last_non_empty_line_default")]
 319    pub auto_indent_using_last_non_empty_line: bool,
 320    #[serde(default, deserialize_with = "deserialize_regex")]
 321    pub increase_indent_pattern: Option<Regex>,
 322    #[serde(default, deserialize_with = "deserialize_regex")]
 323    pub decrease_indent_pattern: Option<Regex>,
 324    #[serde(default)]
 325    pub autoclose_before: String,
 326    #[serde(default)]
 327    pub line_comment: Option<Arc<str>>,
 328    #[serde(default)]
 329    pub block_comment: Option<(Arc<str>, Arc<str>)>,
 330    #[serde(default)]
 331    pub overrides: HashMap<String, LanguageConfigOverride>,
 332}
 333
 334#[derive(Debug, Default)]
 335pub struct LanguageQueries {
 336    pub highlights: Option<Cow<'static, str>>,
 337    pub brackets: Option<Cow<'static, str>>,
 338    pub indents: Option<Cow<'static, str>>,
 339    pub outline: Option<Cow<'static, str>>,
 340    pub injections: Option<Cow<'static, str>>,
 341    pub overrides: Option<Cow<'static, str>>,
 342}
 343
 344#[derive(Clone, Debug)]
 345pub struct LanguageScope {
 346    language: Arc<Language>,
 347    override_id: Option<u32>,
 348}
 349
 350#[derive(Clone, Deserialize, Default, Debug)]
 351pub struct LanguageConfigOverride {
 352    #[serde(default)]
 353    pub line_comment: Override<Arc<str>>,
 354    #[serde(default)]
 355    pub block_comment: Override<(Arc<str>, Arc<str>)>,
 356    #[serde(skip_deserializing)]
 357    pub disabled_bracket_ixs: Vec<u16>,
 358}
 359
 360#[derive(Clone, Deserialize, Debug)]
 361#[serde(untagged)]
 362pub enum Override<T> {
 363    Remove { remove: bool },
 364    Set(T),
 365}
 366
 367impl<T> Default for Override<T> {
 368    fn default() -> Self {
 369        Override::Remove { remove: false }
 370    }
 371}
 372
 373impl<T> Override<T> {
 374    fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
 375        match this {
 376            Some(Self::Set(value)) => Some(value),
 377            Some(Self::Remove { remove: true }) => None,
 378            Some(Self::Remove { remove: false }) | None => original,
 379        }
 380    }
 381}
 382
 383impl Default for LanguageConfig {
 384    fn default() -> Self {
 385        Self {
 386            name: "".into(),
 387            path_suffixes: Default::default(),
 388            brackets: Default::default(),
 389            auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
 390            first_line_pattern: Default::default(),
 391            increase_indent_pattern: Default::default(),
 392            decrease_indent_pattern: Default::default(),
 393            autoclose_before: Default::default(),
 394            line_comment: Default::default(),
 395            block_comment: Default::default(),
 396            overrides: Default::default(),
 397        }
 398    }
 399}
 400
 401fn auto_indent_using_last_non_empty_line_default() -> bool {
 402    true
 403}
 404
 405fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
 406    let source = Option::<String>::deserialize(d)?;
 407    if let Some(source) = source {
 408        Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
 409    } else {
 410        Ok(None)
 411    }
 412}
 413
 414#[cfg(any(test, feature = "test-support"))]
 415pub struct FakeLspAdapter {
 416    pub name: &'static str,
 417    pub capabilities: lsp::ServerCapabilities,
 418    pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
 419    pub disk_based_diagnostics_progress_token: Option<String>,
 420    pub disk_based_diagnostics_sources: Vec<String>,
 421}
 422
 423#[derive(Clone, Debug, Default)]
 424pub struct BracketPairConfig {
 425    pub pairs: Vec<BracketPair>,
 426    pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
 427}
 428
 429impl<'de> Deserialize<'de> for BracketPairConfig {
 430    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
 431    where
 432        D: Deserializer<'de>,
 433    {
 434        #[derive(Deserialize)]
 435        pub struct Entry {
 436            #[serde(flatten)]
 437            pub bracket_pair: BracketPair,
 438            #[serde(default)]
 439            pub not_in: Vec<String>,
 440        }
 441
 442        let result = Vec::<Entry>::deserialize(deserializer)?;
 443        let mut brackets = Vec::with_capacity(result.len());
 444        let mut disabled_scopes_by_bracket_ix = Vec::with_capacity(result.len());
 445        for entry in result {
 446            brackets.push(entry.bracket_pair);
 447            disabled_scopes_by_bracket_ix.push(entry.not_in);
 448        }
 449
 450        Ok(BracketPairConfig {
 451            pairs: brackets,
 452            disabled_scopes_by_bracket_ix,
 453        })
 454    }
 455}
 456
 457#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
 458pub struct BracketPair {
 459    pub start: String,
 460    pub end: String,
 461    pub close: bool,
 462    pub newline: bool,
 463}
 464
 465pub struct Language {
 466    pub(crate) config: LanguageConfig,
 467    pub(crate) grammar: Option<Arc<Grammar>>,
 468    pub(crate) adapters: Vec<Arc<CachedLspAdapter>>,
 469
 470    #[cfg(any(test, feature = "test-support"))]
 471    fake_adapter: Option<(
 472        mpsc::UnboundedSender<lsp::FakeLanguageServer>,
 473        Arc<FakeLspAdapter>,
 474    )>,
 475}
 476
 477pub struct Grammar {
 478    id: usize,
 479    pub(crate) ts_language: tree_sitter::Language,
 480    pub(crate) error_query: Query,
 481    pub(crate) highlights_query: Option<Query>,
 482    pub(crate) brackets_config: Option<BracketConfig>,
 483    pub(crate) indents_config: Option<IndentConfig>,
 484    pub(crate) outline_config: Option<OutlineConfig>,
 485    pub(crate) injection_config: Option<InjectionConfig>,
 486    pub(crate) override_config: Option<OverrideConfig>,
 487    pub(crate) highlight_map: Mutex<HighlightMap>,
 488}
 489
 490struct IndentConfig {
 491    query: Query,
 492    indent_capture_ix: u32,
 493    start_capture_ix: Option<u32>,
 494    end_capture_ix: Option<u32>,
 495    outdent_capture_ix: Option<u32>,
 496}
 497
 498struct OutlineConfig {
 499    query: Query,
 500    item_capture_ix: u32,
 501    name_capture_ix: u32,
 502    context_capture_ix: Option<u32>,
 503    extra_context_capture_ix: Option<u32>,
 504}
 505
 506struct InjectionConfig {
 507    query: Query,
 508    content_capture_ix: u32,
 509    language_capture_ix: Option<u32>,
 510    patterns: Vec<InjectionPatternConfig>,
 511}
 512
 513struct OverrideConfig {
 514    query: Query,
 515    values: HashMap<u32, (String, LanguageConfigOverride)>,
 516}
 517
 518#[derive(Default, Clone)]
 519struct InjectionPatternConfig {
 520    language: Option<Box<str>>,
 521    combined: bool,
 522}
 523
 524struct BracketConfig {
 525    query: Query,
 526    open_capture_ix: u32,
 527    close_capture_ix: u32,
 528}
 529
 530#[derive(Clone)]
 531pub enum LanguageServerBinaryStatus {
 532    CheckingForUpdate,
 533    Downloading,
 534    Downloaded,
 535    Cached,
 536    Failed { error: String },
 537}
 538
 539type AvailableLanguageId = usize;
 540
 541#[derive(Clone)]
 542struct AvailableLanguage {
 543    id: AvailableLanguageId,
 544    path: &'static str,
 545    config: LanguageConfig,
 546    grammar: tree_sitter::Language,
 547    lsp_adapters: Vec<Arc<dyn LspAdapter>>,
 548    get_queries: fn(&str) -> LanguageQueries,
 549    loaded: bool,
 550}
 551
 552pub struct LanguageRegistry {
 553    state: RwLock<LanguageRegistryState>,
 554    language_server_download_dir: Option<Arc<Path>>,
 555    lsp_binary_statuses_tx: async_broadcast::Sender<(Arc<Language>, LanguageServerBinaryStatus)>,
 556    lsp_binary_statuses_rx: async_broadcast::Receiver<(Arc<Language>, LanguageServerBinaryStatus)>,
 557    login_shell_env_loaded: Shared<Task<()>>,
 558    #[allow(clippy::type_complexity)]
 559    lsp_binary_paths: Mutex<
 560        HashMap<LanguageServerName, Shared<Task<Result<LanguageServerBinary, Arc<anyhow::Error>>>>>,
 561    >,
 562    executor: Option<Arc<Background>>,
 563}
 564
 565struct LanguageRegistryState {
 566    next_language_server_id: usize,
 567    languages: Vec<Arc<Language>>,
 568    available_languages: Vec<AvailableLanguage>,
 569    next_available_language_id: AvailableLanguageId,
 570    loading_languages: HashMap<AvailableLanguageId, Vec<oneshot::Sender<Result<Arc<Language>>>>>,
 571    subscription: (watch::Sender<()>, watch::Receiver<()>),
 572    theme: Option<Arc<Theme>>,
 573    version: usize,
 574    reload_count: usize,
 575}
 576
 577pub struct PendingLanguageServer {
 578    pub server_id: LanguageServerId,
 579    pub task: Task<Result<lsp::LanguageServer>>,
 580}
 581
 582impl LanguageRegistry {
 583    pub fn new(login_shell_env_loaded: Task<()>) -> Self {
 584        let (lsp_binary_statuses_tx, lsp_binary_statuses_rx) = async_broadcast::broadcast(16);
 585        Self {
 586            state: RwLock::new(LanguageRegistryState {
 587                next_language_server_id: 0,
 588                languages: vec![PLAIN_TEXT.clone()],
 589                available_languages: Default::default(),
 590                next_available_language_id: 0,
 591                loading_languages: Default::default(),
 592                subscription: watch::channel(),
 593                theme: Default::default(),
 594                version: 0,
 595                reload_count: 0,
 596            }),
 597            language_server_download_dir: None,
 598            lsp_binary_statuses_tx,
 599            lsp_binary_statuses_rx,
 600            login_shell_env_loaded: login_shell_env_loaded.shared(),
 601            lsp_binary_paths: Default::default(),
 602            executor: None,
 603        }
 604    }
 605
 606    #[cfg(any(test, feature = "test-support"))]
 607    pub fn test() -> Self {
 608        Self::new(Task::ready(()))
 609    }
 610
 611    pub fn set_executor(&mut self, executor: Arc<Background>) {
 612        self.executor = Some(executor);
 613    }
 614
 615    /// Clear out all of the loaded languages and reload them from scratch.
 616    ///
 617    /// This is useful in development, when queries have changed.
 618    #[cfg(debug_assertions)]
 619    pub fn reload(&self) {
 620        self.state.write().reload();
 621    }
 622
 623    pub fn register(
 624        &self,
 625        path: &'static str,
 626        config: LanguageConfig,
 627        grammar: tree_sitter::Language,
 628        lsp_adapters: Vec<Arc<dyn LspAdapter>>,
 629        get_queries: fn(&str) -> LanguageQueries,
 630    ) {
 631        let state = &mut *self.state.write();
 632        state.available_languages.push(AvailableLanguage {
 633            id: post_inc(&mut state.next_available_language_id),
 634            path,
 635            config,
 636            grammar,
 637            lsp_adapters,
 638            get_queries,
 639            loaded: false,
 640        });
 641    }
 642
 643    pub fn language_names(&self) -> Vec<String> {
 644        let state = self.state.read();
 645        let mut result = state
 646            .available_languages
 647            .iter()
 648            .filter_map(|l| l.loaded.not().then_some(l.config.name.to_string()))
 649            .chain(state.languages.iter().map(|l| l.config.name.to_string()))
 650            .collect::<Vec<_>>();
 651        result.sort_unstable_by_key(|language_name| language_name.to_lowercase());
 652        result
 653    }
 654
 655    pub fn workspace_configuration(&self, cx: &mut AppContext) -> Task<serde_json::Value> {
 656        let lsp_adapters = {
 657            let state = self.state.read();
 658            state
 659                .available_languages
 660                .iter()
 661                .filter(|l| !l.loaded)
 662                .flat_map(|l| l.lsp_adapters.clone())
 663                .chain(
 664                    state
 665                        .languages
 666                        .iter()
 667                        .flat_map(|language| &language.adapters)
 668                        .map(|adapter| adapter.adapter.clone()),
 669                )
 670                .collect::<Vec<_>>()
 671        };
 672
 673        let mut language_configs = Vec::new();
 674        for adapter in &lsp_adapters {
 675            if let Some(language_config) = adapter.workspace_configuration(cx) {
 676                language_configs.push(language_config);
 677            }
 678        }
 679
 680        cx.background().spawn(async move {
 681            let mut config = serde_json::json!({});
 682            let language_configs = futures::future::join_all(language_configs).await;
 683            for language_config in language_configs {
 684                merge_json_value_into(language_config, &mut config);
 685            }
 686            config
 687        })
 688    }
 689
 690    pub fn add(&self, language: Arc<Language>) {
 691        self.state.write().add(language);
 692    }
 693
 694    pub fn subscribe(&self) -> watch::Receiver<()> {
 695        self.state.read().subscription.1.clone()
 696    }
 697
 698    /// The number of times that the registry has been changed,
 699    /// by adding languages or reloading.
 700    pub fn version(&self) -> usize {
 701        self.state.read().version
 702    }
 703
 704    /// The number of times that the registry has been reloaded.
 705    pub fn reload_count(&self) -> usize {
 706        self.state.read().reload_count
 707    }
 708
 709    pub fn set_theme(&self, theme: Arc<Theme>) {
 710        let mut state = self.state.write();
 711        state.theme = Some(theme.clone());
 712        for language in &state.languages {
 713            language.set_theme(&theme.editor.syntax);
 714        }
 715    }
 716
 717    pub fn set_language_server_download_dir(&mut self, path: impl Into<Arc<Path>>) {
 718        self.language_server_download_dir = Some(path.into());
 719    }
 720
 721    pub fn language_for_name(
 722        self: &Arc<Self>,
 723        name: &str,
 724    ) -> UnwrapFuture<oneshot::Receiver<Result<Arc<Language>>>> {
 725        let name = UniCase::new(name);
 726        self.get_or_load_language(|config| UniCase::new(config.name.as_ref()) == name)
 727    }
 728
 729    pub fn language_for_name_or_extension(
 730        self: &Arc<Self>,
 731        string: &str,
 732    ) -> UnwrapFuture<oneshot::Receiver<Result<Arc<Language>>>> {
 733        let string = UniCase::new(string);
 734        self.get_or_load_language(|config| {
 735            UniCase::new(config.name.as_ref()) == string
 736                || config
 737                    .path_suffixes
 738                    .iter()
 739                    .any(|suffix| UniCase::new(suffix) == string)
 740        })
 741    }
 742
 743    pub fn language_for_file(
 744        self: &Arc<Self>,
 745        path: impl AsRef<Path>,
 746        content: Option<&Rope>,
 747    ) -> UnwrapFuture<oneshot::Receiver<Result<Arc<Language>>>> {
 748        let path = path.as_ref();
 749        let filename = path.file_name().and_then(|name| name.to_str());
 750        let extension = path.extension().and_then(|name| name.to_str());
 751        let path_suffixes = [extension, filename];
 752        self.get_or_load_language(|config| {
 753            let path_matches = config
 754                .path_suffixes
 755                .iter()
 756                .any(|suffix| path_suffixes.contains(&Some(suffix.as_str())));
 757            let content_matches = content.zip(config.first_line_pattern.as_ref()).map_or(
 758                false,
 759                |(content, pattern)| {
 760                    let end = content.clip_point(Point::new(0, 256), Bias::Left);
 761                    let end = content.point_to_offset(end);
 762                    let text = content.chunks_in_range(0..end).collect::<String>();
 763                    pattern.is_match(&text)
 764                },
 765            );
 766            path_matches || content_matches
 767        })
 768    }
 769
 770    fn get_or_load_language(
 771        self: &Arc<Self>,
 772        callback: impl Fn(&LanguageConfig) -> bool,
 773    ) -> UnwrapFuture<oneshot::Receiver<Result<Arc<Language>>>> {
 774        let (tx, rx) = oneshot::channel();
 775
 776        let mut state = self.state.write();
 777        if let Some(language) = state
 778            .languages
 779            .iter()
 780            .find(|language| callback(&language.config))
 781        {
 782            let _ = tx.send(Ok(language.clone()));
 783        } else if let Some(executor) = self.executor.clone() {
 784            if let Some(language) = state
 785                .available_languages
 786                .iter()
 787                .find(|l| !l.loaded && callback(&l.config))
 788                .cloned()
 789            {
 790                let txs = state
 791                    .loading_languages
 792                    .entry(language.id)
 793                    .or_insert_with(|| {
 794                        let this = self.clone();
 795                        executor
 796                            .spawn(async move {
 797                                let id = language.id;
 798                                let queries = (language.get_queries)(&language.path);
 799                                let language =
 800                                    Language::new(language.config, Some(language.grammar))
 801                                        .with_lsp_adapters(language.lsp_adapters)
 802                                        .await;
 803                                let name = language.name();
 804                                match language.with_queries(queries) {
 805                                    Ok(language) => {
 806                                        let language = Arc::new(language);
 807                                        let mut state = this.state.write();
 808                                        state.add(language.clone());
 809                                        state.mark_language_loaded(id);
 810                                        if let Some(mut txs) = state.loading_languages.remove(&id) {
 811                                            for tx in txs.drain(..) {
 812                                                let _ = tx.send(Ok(language.clone()));
 813                                            }
 814                                        }
 815                                    }
 816                                    Err(err) => {
 817                                        log::error!("failed to load language {name} - {err}");
 818                                        let mut state = this.state.write();
 819                                        state.mark_language_loaded(id);
 820                                        if let Some(mut txs) = state.loading_languages.remove(&id) {
 821                                            for tx in txs.drain(..) {
 822                                                let _ = tx.send(Err(anyhow!(
 823                                                    "failed to load language {}: {}",
 824                                                    name,
 825                                                    err
 826                                                )));
 827                                            }
 828                                        }
 829                                    }
 830                                };
 831                            })
 832                            .detach();
 833
 834                        Vec::new()
 835                    });
 836                txs.push(tx);
 837            } else {
 838                let _ = tx.send(Err(anyhow!("language not found")));
 839            }
 840        } else {
 841            let _ = tx.send(Err(anyhow!("executor does not exist")));
 842        }
 843
 844        rx.unwrap()
 845    }
 846
 847    pub fn to_vec(&self) -> Vec<Arc<Language>> {
 848        self.state.read().languages.iter().cloned().collect()
 849    }
 850
 851    pub fn start_language_server(
 852        self: &Arc<Self>,
 853        language: Arc<Language>,
 854        adapter: Arc<CachedLspAdapter>,
 855        root_path: Arc<Path>,
 856        delegate: Arc<dyn LspAdapterDelegate>,
 857        cx: &mut AppContext,
 858    ) -> Option<PendingLanguageServer> {
 859        let server_id = self.state.write().next_language_server_id();
 860        log::info!(
 861            "starting language server name:{}, path:{root_path:?}, id:{server_id}",
 862            adapter.name.0
 863        );
 864
 865        #[cfg(any(test, feature = "test-support"))]
 866        if language.fake_adapter.is_some() {
 867            let task = cx.spawn(|cx| async move {
 868                let (servers_tx, fake_adapter) = language.fake_adapter.as_ref().unwrap();
 869                let (server, mut fake_server) = lsp::LanguageServer::fake(
 870                    fake_adapter.name.to_string(),
 871                    fake_adapter.capabilities.clone(),
 872                    cx.clone(),
 873                );
 874
 875                if let Some(initializer) = &fake_adapter.initializer {
 876                    initializer(&mut fake_server);
 877                }
 878
 879                let servers_tx = servers_tx.clone();
 880                cx.background()
 881                    .spawn(async move {
 882                        if fake_server
 883                            .try_receive_notification::<lsp::notification::Initialized>()
 884                            .await
 885                            .is_some()
 886                        {
 887                            servers_tx.unbounded_send(fake_server).ok();
 888                        }
 889                    })
 890                    .detach();
 891                Ok(server)
 892            });
 893
 894            return Some(PendingLanguageServer { server_id, task });
 895        }
 896
 897        let download_dir = self
 898            .language_server_download_dir
 899            .clone()
 900            .ok_or_else(|| anyhow!("language server download directory has not been assigned"))
 901            .log_err()?;
 902        let this = self.clone();
 903        let language = language.clone();
 904        let download_dir = download_dir.clone();
 905        let root_path = root_path.clone();
 906        let adapter = adapter.clone();
 907        let lsp_binary_statuses = self.lsp_binary_statuses_tx.clone();
 908        let login_shell_env_loaded = self.login_shell_env_loaded.clone();
 909
 910        let task = cx.spawn(|mut cx| async move {
 911            login_shell_env_loaded.await;
 912
 913            let entry = this
 914                .lsp_binary_paths
 915                .lock()
 916                .entry(adapter.name.clone())
 917                .or_insert_with(|| {
 918                    cx.spawn(|cx| {
 919                        get_binary(
 920                            adapter.clone(),
 921                            language.clone(),
 922                            delegate.clone(),
 923                            download_dir,
 924                            lsp_binary_statuses,
 925                            cx,
 926                        )
 927                        .map_err(Arc::new)
 928                    })
 929                    .shared()
 930                })
 931                .clone();
 932            let binary = entry.clone().map_err(|e| anyhow!(e)).await?;
 933
 934            if let Some(task) = adapter.will_start_server(&delegate, &mut cx) {
 935                task.await?;
 936            }
 937
 938            let server = lsp::LanguageServer::new(
 939                server_id,
 940                &binary.path,
 941                &binary.arguments,
 942                &root_path,
 943                adapter.code_action_kinds(),
 944                cx,
 945            )?;
 946
 947            Ok(server)
 948        });
 949
 950        Some(PendingLanguageServer { server_id, task })
 951    }
 952
 953    pub fn language_server_binary_statuses(
 954        &self,
 955    ) -> async_broadcast::Receiver<(Arc<Language>, LanguageServerBinaryStatus)> {
 956        self.lsp_binary_statuses_rx.clone()
 957    }
 958}
 959
 960impl LanguageRegistryState {
 961    fn next_language_server_id(&mut self) -> LanguageServerId {
 962        LanguageServerId(post_inc(&mut self.next_language_server_id))
 963    }
 964
 965    fn add(&mut self, language: Arc<Language>) {
 966        if let Some(theme) = self.theme.as_ref() {
 967            language.set_theme(&theme.editor.syntax);
 968        }
 969        self.languages.push(language);
 970        self.version += 1;
 971        *self.subscription.0.borrow_mut() = ();
 972    }
 973
 974    #[cfg(debug_assertions)]
 975    fn reload(&mut self) {
 976        self.languages.clear();
 977        self.version += 1;
 978        self.reload_count += 1;
 979        for language in &mut self.available_languages {
 980            language.loaded = false;
 981        }
 982        *self.subscription.0.borrow_mut() = ();
 983    }
 984
 985    /// Mark the given language a having been loaded, so that the
 986    /// language registry won't try to load it again.
 987    fn mark_language_loaded(&mut self, id: AvailableLanguageId) {
 988        for language in &mut self.available_languages {
 989            if language.id == id {
 990                language.loaded = true;
 991                break;
 992            }
 993        }
 994    }
 995}
 996
 997#[cfg(any(test, feature = "test-support"))]
 998impl Default for LanguageRegistry {
 999    fn default() -> Self {
1000        Self::test()
1001    }
1002}
1003
1004async fn get_binary(
1005    adapter: Arc<CachedLspAdapter>,
1006    language: Arc<Language>,
1007    delegate: Arc<dyn LspAdapterDelegate>,
1008    download_dir: Arc<Path>,
1009    statuses: async_broadcast::Sender<(Arc<Language>, LanguageServerBinaryStatus)>,
1010    mut cx: AsyncAppContext,
1011) -> Result<LanguageServerBinary> {
1012    let container_dir = download_dir.join(adapter.name.0.as_ref());
1013    if !container_dir.exists() {
1014        smol::fs::create_dir_all(&container_dir)
1015            .await
1016            .context("failed to create container directory")?;
1017    }
1018
1019    if let Some(task) = adapter.will_fetch_server(&delegate, &mut cx) {
1020        task.await?;
1021    }
1022
1023    let binary = fetch_latest_binary(
1024        adapter.clone(),
1025        language.clone(),
1026        delegate.as_ref(),
1027        &container_dir,
1028        statuses.clone(),
1029    )
1030    .await;
1031
1032    if let Err(error) = binary.as_ref() {
1033        if let Some(cached) = adapter
1034            .cached_server_binary(container_dir, delegate.as_ref())
1035            .await
1036        {
1037            statuses
1038                .broadcast((language.clone(), LanguageServerBinaryStatus::Cached))
1039                .await?;
1040            return Ok(cached);
1041        } else {
1042            statuses
1043                .broadcast((
1044                    language.clone(),
1045                    LanguageServerBinaryStatus::Failed {
1046                        error: format!("{:?}", error),
1047                    },
1048                ))
1049                .await?;
1050        }
1051    }
1052    binary
1053}
1054
1055async fn fetch_latest_binary(
1056    adapter: Arc<CachedLspAdapter>,
1057    language: Arc<Language>,
1058    delegate: &dyn LspAdapterDelegate,
1059    container_dir: &Path,
1060    lsp_binary_statuses_tx: async_broadcast::Sender<(Arc<Language>, LanguageServerBinaryStatus)>,
1061) -> Result<LanguageServerBinary> {
1062    let container_dir: Arc<Path> = container_dir.into();
1063    lsp_binary_statuses_tx
1064        .broadcast((
1065            language.clone(),
1066            LanguageServerBinaryStatus::CheckingForUpdate,
1067        ))
1068        .await?;
1069    let version_info = adapter.fetch_latest_server_version(delegate).await?;
1070    lsp_binary_statuses_tx
1071        .broadcast((language.clone(), LanguageServerBinaryStatus::Downloading))
1072        .await?;
1073    let binary = adapter
1074        .fetch_server_binary(version_info, container_dir.to_path_buf(), delegate)
1075        .await?;
1076    lsp_binary_statuses_tx
1077        .broadcast((language.clone(), LanguageServerBinaryStatus::Downloaded))
1078        .await?;
1079    Ok(binary)
1080}
1081
1082impl Language {
1083    pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
1084        Self {
1085            config,
1086            grammar: ts_language.map(|ts_language| {
1087                Arc::new(Grammar {
1088                    id: NEXT_GRAMMAR_ID.fetch_add(1, SeqCst),
1089                    highlights_query: None,
1090                    brackets_config: None,
1091                    outline_config: None,
1092                    indents_config: None,
1093                    injection_config: None,
1094                    override_config: None,
1095                    error_query: Query::new(ts_language, "(ERROR) @error").unwrap(),
1096                    ts_language,
1097                    highlight_map: Default::default(),
1098                })
1099            }),
1100            adapters: Vec::new(),
1101
1102            #[cfg(any(test, feature = "test-support"))]
1103            fake_adapter: None,
1104        }
1105    }
1106
1107    pub fn lsp_adapters(&self) -> &[Arc<CachedLspAdapter>] {
1108        &self.adapters
1109    }
1110
1111    pub fn id(&self) -> Option<usize> {
1112        self.grammar.as_ref().map(|g| g.id)
1113    }
1114
1115    pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
1116        if let Some(query) = queries.highlights {
1117            self = self.with_highlights_query(query.as_ref())?;
1118        }
1119        if let Some(query) = queries.brackets {
1120            self = self.with_brackets_query(query.as_ref())?;
1121        }
1122        if let Some(query) = queries.indents {
1123            self = self.with_indents_query(query.as_ref())?;
1124        }
1125        if let Some(query) = queries.outline {
1126            self = self.with_outline_query(query.as_ref())?;
1127        }
1128        if let Some(query) = queries.injections {
1129            self = self.with_injection_query(query.as_ref())?;
1130        }
1131        if let Some(query) = queries.overrides {
1132            self = self.with_override_query(query.as_ref())?;
1133        }
1134        Ok(self)
1135    }
1136    pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1137        let grammar = self.grammar_mut();
1138        grammar.highlights_query = Some(Query::new(grammar.ts_language, source)?);
1139        Ok(self)
1140    }
1141
1142    pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1143        let grammar = self.grammar_mut();
1144        let query = Query::new(grammar.ts_language, source)?;
1145        let mut item_capture_ix = None;
1146        let mut name_capture_ix = None;
1147        let mut context_capture_ix = None;
1148        let mut extra_context_capture_ix = None;
1149        get_capture_indices(
1150            &query,
1151            &mut [
1152                ("item", &mut item_capture_ix),
1153                ("name", &mut name_capture_ix),
1154                ("context", &mut context_capture_ix),
1155                ("context.extra", &mut extra_context_capture_ix),
1156            ],
1157        );
1158        if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
1159            grammar.outline_config = Some(OutlineConfig {
1160                query,
1161                item_capture_ix,
1162                name_capture_ix,
1163                context_capture_ix,
1164                extra_context_capture_ix,
1165            });
1166        }
1167        Ok(self)
1168    }
1169
1170    pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1171        let grammar = self.grammar_mut();
1172        let query = Query::new(grammar.ts_language, source)?;
1173        let mut open_capture_ix = None;
1174        let mut close_capture_ix = None;
1175        get_capture_indices(
1176            &query,
1177            &mut [
1178                ("open", &mut open_capture_ix),
1179                ("close", &mut close_capture_ix),
1180            ],
1181        );
1182        if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1183            grammar.brackets_config = Some(BracketConfig {
1184                query,
1185                open_capture_ix,
1186                close_capture_ix,
1187            });
1188        }
1189        Ok(self)
1190    }
1191
1192    pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1193        let grammar = self.grammar_mut();
1194        let query = Query::new(grammar.ts_language, source)?;
1195        let mut indent_capture_ix = None;
1196        let mut start_capture_ix = None;
1197        let mut end_capture_ix = None;
1198        let mut outdent_capture_ix = None;
1199        get_capture_indices(
1200            &query,
1201            &mut [
1202                ("indent", &mut indent_capture_ix),
1203                ("start", &mut start_capture_ix),
1204                ("end", &mut end_capture_ix),
1205                ("outdent", &mut outdent_capture_ix),
1206            ],
1207        );
1208        if let Some(indent_capture_ix) = indent_capture_ix {
1209            grammar.indents_config = Some(IndentConfig {
1210                query,
1211                indent_capture_ix,
1212                start_capture_ix,
1213                end_capture_ix,
1214                outdent_capture_ix,
1215            });
1216        }
1217        Ok(self)
1218    }
1219
1220    pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1221        let grammar = self.grammar_mut();
1222        let query = Query::new(grammar.ts_language, source)?;
1223        let mut language_capture_ix = None;
1224        let mut content_capture_ix = None;
1225        get_capture_indices(
1226            &query,
1227            &mut [
1228                ("language", &mut language_capture_ix),
1229                ("content", &mut content_capture_ix),
1230            ],
1231        );
1232        let patterns = (0..query.pattern_count())
1233            .map(|ix| {
1234                let mut config = InjectionPatternConfig::default();
1235                for setting in query.property_settings(ix) {
1236                    match setting.key.as_ref() {
1237                        "language" => {
1238                            config.language = setting.value.clone();
1239                        }
1240                        "combined" => {
1241                            config.combined = true;
1242                        }
1243                        _ => {}
1244                    }
1245                }
1246                config
1247            })
1248            .collect();
1249        if let Some(content_capture_ix) = content_capture_ix {
1250            grammar.injection_config = Some(InjectionConfig {
1251                query,
1252                language_capture_ix,
1253                content_capture_ix,
1254                patterns,
1255            });
1256        }
1257        Ok(self)
1258    }
1259
1260    pub fn with_override_query(mut self, source: &str) -> Result<Self> {
1261        let query = Query::new(self.grammar_mut().ts_language, source)?;
1262
1263        let mut override_configs_by_id = HashMap::default();
1264        for (ix, name) in query.capture_names().iter().enumerate() {
1265            if !name.starts_with('_') {
1266                let value = self.config.overrides.remove(name).unwrap_or_default();
1267                override_configs_by_id.insert(ix as u32, (name.clone(), value));
1268            }
1269        }
1270
1271        if !self.config.overrides.is_empty() {
1272            let keys = self.config.overrides.keys().collect::<Vec<_>>();
1273            Err(anyhow!(
1274                "language {:?} has overrides in config not in query: {keys:?}",
1275                self.config.name
1276            ))?;
1277        }
1278
1279        for disabled_scope_name in self
1280            .config
1281            .brackets
1282            .disabled_scopes_by_bracket_ix
1283            .iter()
1284            .flatten()
1285        {
1286            if !override_configs_by_id
1287                .values()
1288                .any(|(scope_name, _)| scope_name == disabled_scope_name)
1289            {
1290                Err(anyhow!(
1291                    "language {:?} has overrides in config not in query: {disabled_scope_name:?}",
1292                    self.config.name
1293                ))?;
1294            }
1295        }
1296
1297        for (name, override_config) in override_configs_by_id.values_mut() {
1298            override_config.disabled_bracket_ixs = self
1299                .config
1300                .brackets
1301                .disabled_scopes_by_bracket_ix
1302                .iter()
1303                .enumerate()
1304                .filter_map(|(ix, disabled_scope_names)| {
1305                    if disabled_scope_names.contains(name) {
1306                        Some(ix as u16)
1307                    } else {
1308                        None
1309                    }
1310                })
1311                .collect();
1312        }
1313
1314        self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1315        self.grammar_mut().override_config = Some(OverrideConfig {
1316            query,
1317            values: override_configs_by_id,
1318        });
1319        Ok(self)
1320    }
1321
1322    fn grammar_mut(&mut self) -> &mut Grammar {
1323        Arc::get_mut(self.grammar.as_mut().unwrap()).unwrap()
1324    }
1325
1326    pub async fn with_lsp_adapters(mut self, lsp_adapters: Vec<Arc<dyn LspAdapter>>) -> Self {
1327        for adapter in lsp_adapters {
1328            self.adapters.push(CachedLspAdapter::new(adapter).await);
1329        }
1330        self
1331    }
1332
1333    #[cfg(any(test, feature = "test-support"))]
1334    pub async fn set_fake_lsp_adapter(
1335        &mut self,
1336        fake_lsp_adapter: Arc<FakeLspAdapter>,
1337    ) -> mpsc::UnboundedReceiver<lsp::FakeLanguageServer> {
1338        let (servers_tx, servers_rx) = mpsc::unbounded();
1339        self.fake_adapter = Some((servers_tx, fake_lsp_adapter.clone()));
1340        let adapter = CachedLspAdapter::new(Arc::new(fake_lsp_adapter)).await;
1341        self.adapters = vec![adapter];
1342        servers_rx
1343    }
1344
1345    pub fn name(&self) -> Arc<str> {
1346        self.config.name.clone()
1347    }
1348
1349    pub async fn disk_based_diagnostic_sources(&self) -> &[String] {
1350        match self.adapters.first().as_ref() {
1351            Some(adapter) => &adapter.disk_based_diagnostic_sources,
1352            None => &[],
1353        }
1354    }
1355
1356    pub async fn disk_based_diagnostics_progress_token(&self) -> Option<&str> {
1357        for adapter in &self.adapters {
1358            let token = adapter.disk_based_diagnostics_progress_token.as_deref();
1359            if token.is_some() {
1360                return token;
1361            }
1362        }
1363
1364        None
1365    }
1366
1367    pub async fn process_diagnostics(&self, diagnostics: &mut lsp::PublishDiagnosticsParams) {
1368        for adapter in &self.adapters {
1369            adapter.process_diagnostics(diagnostics).await;
1370        }
1371    }
1372
1373    pub async fn process_completion(self: &Arc<Self>, completion: &mut lsp::CompletionItem) {
1374        for adapter in &self.adapters {
1375            adapter.process_completion(completion).await;
1376        }
1377    }
1378
1379    pub async fn label_for_completion(
1380        self: &Arc<Self>,
1381        completion: &lsp::CompletionItem,
1382    ) -> Option<CodeLabel> {
1383        self.adapters
1384            .first()
1385            .as_ref()?
1386            .label_for_completion(completion, self)
1387            .await
1388    }
1389
1390    pub async fn label_for_symbol(
1391        self: &Arc<Self>,
1392        name: &str,
1393        kind: lsp::SymbolKind,
1394    ) -> Option<CodeLabel> {
1395        self.adapters
1396            .first()
1397            .as_ref()?
1398            .label_for_symbol(name, kind, self)
1399            .await
1400    }
1401
1402    pub fn highlight_text<'a>(
1403        self: &'a Arc<Self>,
1404        text: &'a Rope,
1405        range: Range<usize>,
1406    ) -> Vec<(Range<usize>, HighlightId)> {
1407        let mut result = Vec::new();
1408        if let Some(grammar) = &self.grammar {
1409            let tree = grammar.parse_text(text, None);
1410            let captures =
1411                SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1412                    grammar.highlights_query.as_ref()
1413                });
1414            let highlight_maps = vec![grammar.highlight_map()];
1415            let mut offset = 0;
1416            for chunk in BufferChunks::new(text, range, Some((captures, highlight_maps)), vec![]) {
1417                let end_offset = offset + chunk.text.len();
1418                if let Some(highlight_id) = chunk.syntax_highlight_id {
1419                    if !highlight_id.is_default() {
1420                        result.push((offset..end_offset, highlight_id));
1421                    }
1422                }
1423                offset = end_offset;
1424            }
1425        }
1426        result
1427    }
1428
1429    pub fn path_suffixes(&self) -> &[String] {
1430        &self.config.path_suffixes
1431    }
1432
1433    pub fn should_autoclose_before(&self, c: char) -> bool {
1434        c.is_whitespace() || self.config.autoclose_before.contains(c)
1435    }
1436
1437    pub fn set_theme(&self, theme: &SyntaxTheme) {
1438        if let Some(grammar) = self.grammar.as_ref() {
1439            if let Some(highlights_query) = &grammar.highlights_query {
1440                *grammar.highlight_map.lock() =
1441                    HighlightMap::new(highlights_query.capture_names(), theme);
1442            }
1443        }
1444    }
1445
1446    pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1447        self.grammar.as_ref()
1448    }
1449}
1450
1451impl LanguageScope {
1452    pub fn line_comment_prefix(&self) -> Option<&Arc<str>> {
1453        Override::as_option(
1454            self.config_override().map(|o| &o.line_comment),
1455            self.language.config.line_comment.as_ref(),
1456        )
1457    }
1458
1459    pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1460        Override::as_option(
1461            self.config_override().map(|o| &o.block_comment),
1462            self.language.config.block_comment.as_ref(),
1463        )
1464        .map(|e| (&e.0, &e.1))
1465    }
1466
1467    pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1468        let mut disabled_ids = self
1469            .config_override()
1470            .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1471        self.language
1472            .config
1473            .brackets
1474            .pairs
1475            .iter()
1476            .enumerate()
1477            .map(move |(ix, bracket)| {
1478                let mut is_enabled = true;
1479                if let Some(next_disabled_ix) = disabled_ids.first() {
1480                    if ix == *next_disabled_ix as usize {
1481                        disabled_ids = &disabled_ids[1..];
1482                        is_enabled = false;
1483                    }
1484                }
1485                (bracket, is_enabled)
1486            })
1487    }
1488
1489    pub fn should_autoclose_before(&self, c: char) -> bool {
1490        c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1491    }
1492
1493    fn config_override(&self) -> Option<&LanguageConfigOverride> {
1494        let id = self.override_id?;
1495        let grammar = self.language.grammar.as_ref()?;
1496        let override_config = grammar.override_config.as_ref()?;
1497        override_config.values.get(&id).map(|e| &e.1)
1498    }
1499}
1500
1501impl Hash for Language {
1502    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1503        self.id().hash(state)
1504    }
1505}
1506
1507impl PartialEq for Language {
1508    fn eq(&self, other: &Self) -> bool {
1509        self.id().eq(&other.id())
1510    }
1511}
1512
1513impl Eq for Language {}
1514
1515impl Debug for Language {
1516    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1517        f.debug_struct("Language")
1518            .field("name", &self.config.name)
1519            .finish()
1520    }
1521}
1522
1523impl Grammar {
1524    pub fn id(&self) -> usize {
1525        self.id
1526    }
1527
1528    fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1529        PARSER.with(|parser| {
1530            let mut parser = parser.borrow_mut();
1531            parser
1532                .set_language(self.ts_language)
1533                .expect("incompatible grammar");
1534            let mut chunks = text.chunks_in_range(0..text.len());
1535            parser
1536                .parse_with(
1537                    &mut move |offset, _| {
1538                        chunks.seek(offset);
1539                        chunks.next().unwrap_or("").as_bytes()
1540                    },
1541                    old_tree.as_ref(),
1542                )
1543                .unwrap()
1544        })
1545    }
1546
1547    pub fn highlight_map(&self) -> HighlightMap {
1548        self.highlight_map.lock().clone()
1549    }
1550
1551    pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1552        let capture_id = self
1553            .highlights_query
1554            .as_ref()?
1555            .capture_index_for_name(name)?;
1556        Some(self.highlight_map.lock().get(capture_id))
1557    }
1558}
1559
1560impl CodeLabel {
1561    pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1562        let mut result = Self {
1563            runs: Vec::new(),
1564            filter_range: 0..text.len(),
1565            text,
1566        };
1567        if let Some(filter_text) = filter_text {
1568            if let Some(ix) = result.text.find(filter_text) {
1569                result.filter_range = ix..ix + filter_text.len();
1570            }
1571        }
1572        result
1573    }
1574}
1575
1576#[cfg(any(test, feature = "test-support"))]
1577impl Default for FakeLspAdapter {
1578    fn default() -> Self {
1579        Self {
1580            name: "the-fake-language-server",
1581            capabilities: lsp::LanguageServer::full_capabilities(),
1582            initializer: None,
1583            disk_based_diagnostics_progress_token: None,
1584            disk_based_diagnostics_sources: Vec::new(),
1585        }
1586    }
1587}
1588
1589#[cfg(any(test, feature = "test-support"))]
1590#[async_trait]
1591impl LspAdapter for Arc<FakeLspAdapter> {
1592    async fn name(&self) -> LanguageServerName {
1593        LanguageServerName(self.name.into())
1594    }
1595
1596    async fn fetch_latest_server_version(
1597        &self,
1598        _: &dyn LspAdapterDelegate,
1599    ) -> Result<Box<dyn 'static + Send + Any>> {
1600        unreachable!();
1601    }
1602
1603    async fn fetch_server_binary(
1604        &self,
1605        _: Box<dyn 'static + Send + Any>,
1606        _: PathBuf,
1607        _: &dyn LspAdapterDelegate,
1608    ) -> Result<LanguageServerBinary> {
1609        unreachable!();
1610    }
1611
1612    async fn cached_server_binary(
1613        &self,
1614        _: PathBuf,
1615        _: &dyn LspAdapterDelegate,
1616    ) -> Option<LanguageServerBinary> {
1617        unreachable!();
1618    }
1619
1620    async fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
1621
1622    async fn disk_based_diagnostic_sources(&self) -> Vec<String> {
1623        self.disk_based_diagnostics_sources.clone()
1624    }
1625
1626    async fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
1627        self.disk_based_diagnostics_progress_token.clone()
1628    }
1629}
1630
1631fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
1632    for (ix, name) in query.capture_names().iter().enumerate() {
1633        for (capture_name, index) in captures.iter_mut() {
1634            if capture_name == name {
1635                **index = Some(ix as u32);
1636                break;
1637            }
1638        }
1639    }
1640}
1641
1642pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
1643    lsp::Position::new(point.row, point.column)
1644}
1645
1646pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
1647    Unclipped(PointUtf16::new(point.line, point.character))
1648}
1649
1650pub fn range_to_lsp(range: Range<PointUtf16>) -> lsp::Range {
1651    lsp::Range {
1652        start: point_to_lsp(range.start),
1653        end: point_to_lsp(range.end),
1654    }
1655}
1656
1657pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
1658    let mut start = point_from_lsp(range.start);
1659    let mut end = point_from_lsp(range.end);
1660    if start > end {
1661        mem::swap(&mut start, &mut end);
1662    }
1663    start..end
1664}
1665
1666#[cfg(test)]
1667mod tests {
1668    use super::*;
1669    use gpui::TestAppContext;
1670
1671    #[gpui::test(iterations = 10)]
1672    async fn test_first_line_pattern(cx: &mut TestAppContext) {
1673        let mut languages = LanguageRegistry::test();
1674        languages.set_executor(cx.background());
1675        let languages = Arc::new(languages);
1676        languages.register(
1677            "/javascript",
1678            LanguageConfig {
1679                name: "JavaScript".into(),
1680                path_suffixes: vec!["js".into()],
1681                first_line_pattern: Some(Regex::new(r"\bnode\b").unwrap()),
1682                ..Default::default()
1683            },
1684            tree_sitter_javascript::language(),
1685            vec![],
1686            |_| Default::default(),
1687        );
1688
1689        languages
1690            .language_for_file("the/script", None)
1691            .await
1692            .unwrap_err();
1693        languages
1694            .language_for_file("the/script", Some(&"nothing".into()))
1695            .await
1696            .unwrap_err();
1697        assert_eq!(
1698            languages
1699                .language_for_file("the/script", Some(&"#!/bin/env node".into()))
1700                .await
1701                .unwrap()
1702                .name()
1703                .as_ref(),
1704            "JavaScript"
1705        );
1706    }
1707
1708    #[gpui::test(iterations = 10)]
1709    async fn test_language_loading(cx: &mut TestAppContext) {
1710        let mut languages = LanguageRegistry::test();
1711        languages.set_executor(cx.background());
1712        let languages = Arc::new(languages);
1713        languages.register(
1714            "/JSON",
1715            LanguageConfig {
1716                name: "JSON".into(),
1717                path_suffixes: vec!["json".into()],
1718                ..Default::default()
1719            },
1720            tree_sitter_json::language(),
1721            vec![],
1722            |_| Default::default(),
1723        );
1724        languages.register(
1725            "/rust",
1726            LanguageConfig {
1727                name: "Rust".into(),
1728                path_suffixes: vec!["rs".into()],
1729                ..Default::default()
1730            },
1731            tree_sitter_rust::language(),
1732            vec![],
1733            |_| Default::default(),
1734        );
1735        assert_eq!(
1736            languages.language_names(),
1737            &[
1738                "JSON".to_string(),
1739                "Plain Text".to_string(),
1740                "Rust".to_string(),
1741            ]
1742        );
1743
1744        let rust1 = languages.language_for_name("Rust");
1745        let rust2 = languages.language_for_name("Rust");
1746
1747        // Ensure language is still listed even if it's being loaded.
1748        assert_eq!(
1749            languages.language_names(),
1750            &[
1751                "JSON".to_string(),
1752                "Plain Text".to_string(),
1753                "Rust".to_string(),
1754            ]
1755        );
1756
1757        let (rust1, rust2) = futures::join!(rust1, rust2);
1758        assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
1759
1760        // Ensure language is still listed even after loading it.
1761        assert_eq!(
1762            languages.language_names(),
1763            &[
1764                "JSON".to_string(),
1765                "Plain Text".to_string(),
1766                "Rust".to_string(),
1767            ]
1768        );
1769
1770        // Loading an unknown language returns an error.
1771        assert!(languages.language_for_name("Unknown").await.is_err());
1772    }
1773}