language.rs

   1mod buffer;
   2mod diagnostic_set;
   3mod highlight_map;
   4mod outline;
   5pub mod proto;
   6mod syntax_map;
   7
   8#[cfg(test)]
   9mod buffer_tests;
  10
  11use anyhow::{anyhow, Context, Result};
  12use async_trait::async_trait;
  13use client::http::HttpClient;
  14use collections::HashMap;
  15use futures::{
  16    channel::oneshot,
  17    future::{BoxFuture, Shared},
  18    FutureExt, TryFutureExt as _,
  19};
  20use gpui::{executor::Background, MutableAppContext, Task};
  21use highlight_map::HighlightMap;
  22use lazy_static::lazy_static;
  23use parking_lot::{Mutex, RwLock};
  24use postage::watch;
  25use regex::Regex;
  26use serde::{de, Deserialize, Deserializer};
  27use serde_json::Value;
  28use std::{
  29    any::Any,
  30    borrow::Cow,
  31    cell::RefCell,
  32    fmt::Debug,
  33    hash::Hash,
  34    mem,
  35    ops::Range,
  36    path::{Path, PathBuf},
  37    str,
  38    sync::{
  39        atomic::{AtomicUsize, Ordering::SeqCst},
  40        Arc,
  41    },
  42};
  43use syntax_map::SyntaxSnapshot;
  44use theme::{SyntaxTheme, Theme};
  45use tree_sitter::{self, Query};
  46use unicase::UniCase;
  47use util::{ResultExt, TryFutureExt as _, UnwrapFuture};
  48
  49#[cfg(any(test, feature = "test-support"))]
  50use futures::channel::mpsc;
  51
  52pub use buffer::Operation;
  53pub use buffer::*;
  54pub use diagnostic_set::DiagnosticEntry;
  55pub use outline::{Outline, OutlineItem};
  56pub use tree_sitter::{Parser, Tree};
  57
  58thread_local! {
  59    static PARSER: RefCell<Parser> = RefCell::new(Parser::new());
  60}
  61
  62lazy_static! {
  63    pub static ref NEXT_GRAMMAR_ID: AtomicUsize = Default::default();
  64    pub static ref PLAIN_TEXT: Arc<Language> = Arc::new(Language::new(
  65        LanguageConfig {
  66            name: "Plain Text".into(),
  67            ..Default::default()
  68        },
  69        None,
  70    ));
  71}
  72
  73pub trait ToLspPosition {
  74    fn to_lsp_position(self) -> lsp::Position;
  75}
  76
  77#[derive(Clone, Debug, PartialEq, Eq, Hash)]
  78pub struct LanguageServerName(pub Arc<str>);
  79
  80/// Represents a Language Server, with certain cached sync properties.
  81/// Uses [`LspAdapter`] under the hood, but calls all 'static' methods
  82/// once at startup, and caches the results.
  83pub struct CachedLspAdapter {
  84    pub name: LanguageServerName,
  85    pub server_args: Vec<String>,
  86    pub initialization_options: Option<Value>,
  87    pub disk_based_diagnostic_sources: Vec<String>,
  88    pub disk_based_diagnostics_progress_token: Option<String>,
  89    pub language_ids: HashMap<String, String>,
  90    pub adapter: Box<dyn LspAdapter>,
  91}
  92
  93impl CachedLspAdapter {
  94    pub async fn new(adapter: Box<dyn LspAdapter>) -> Arc<Self> {
  95        let name = adapter.name().await;
  96        let server_args = adapter.server_args().await;
  97        let initialization_options = adapter.initialization_options().await;
  98        let disk_based_diagnostic_sources = adapter.disk_based_diagnostic_sources().await;
  99        let disk_based_diagnostics_progress_token =
 100            adapter.disk_based_diagnostics_progress_token().await;
 101        let language_ids = adapter.language_ids().await;
 102
 103        Arc::new(CachedLspAdapter {
 104            name,
 105            server_args,
 106            initialization_options,
 107            disk_based_diagnostic_sources,
 108            disk_based_diagnostics_progress_token,
 109            language_ids,
 110            adapter,
 111        })
 112    }
 113
 114    pub async fn fetch_latest_server_version(
 115        &self,
 116        http: Arc<dyn HttpClient>,
 117    ) -> Result<Box<dyn 'static + Send + Any>> {
 118        self.adapter.fetch_latest_server_version(http).await
 119    }
 120
 121    pub async fn fetch_server_binary(
 122        &self,
 123        version: Box<dyn 'static + Send + Any>,
 124        http: Arc<dyn HttpClient>,
 125        container_dir: PathBuf,
 126    ) -> Result<PathBuf> {
 127        self.adapter
 128            .fetch_server_binary(version, http, container_dir)
 129            .await
 130    }
 131
 132    pub async fn cached_server_binary(&self, container_dir: PathBuf) -> Option<PathBuf> {
 133        self.adapter.cached_server_binary(container_dir).await
 134    }
 135
 136    pub async fn process_diagnostics(&self, params: &mut lsp::PublishDiagnosticsParams) {
 137        self.adapter.process_diagnostics(params).await
 138    }
 139
 140    pub async fn process_completion(&self, completion_item: &mut lsp::CompletionItem) {
 141        self.adapter.process_completion(completion_item).await
 142    }
 143
 144    pub async fn label_for_completion(
 145        &self,
 146        completion_item: &lsp::CompletionItem,
 147        language: &Arc<Language>,
 148    ) -> Option<CodeLabel> {
 149        self.adapter
 150            .label_for_completion(completion_item, language)
 151            .await
 152    }
 153
 154    pub async fn label_for_symbol(
 155        &self,
 156        name: &str,
 157        kind: lsp::SymbolKind,
 158        language: &Arc<Language>,
 159    ) -> Option<CodeLabel> {
 160        self.adapter.label_for_symbol(name, kind, language).await
 161    }
 162}
 163
 164#[async_trait]
 165pub trait LspAdapter: 'static + Send + Sync {
 166    async fn name(&self) -> LanguageServerName;
 167
 168    async fn fetch_latest_server_version(
 169        &self,
 170        http: Arc<dyn HttpClient>,
 171    ) -> Result<Box<dyn 'static + Send + Any>>;
 172
 173    async fn fetch_server_binary(
 174        &self,
 175        version: Box<dyn 'static + Send + Any>,
 176        http: Arc<dyn HttpClient>,
 177        container_dir: PathBuf,
 178    ) -> Result<PathBuf>;
 179
 180    async fn cached_server_binary(&self, container_dir: PathBuf) -> Option<PathBuf>;
 181
 182    async fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
 183
 184    async fn process_completion(&self, _: &mut lsp::CompletionItem) {}
 185
 186    async fn label_for_completion(
 187        &self,
 188        _: &lsp::CompletionItem,
 189        _: &Arc<Language>,
 190    ) -> Option<CodeLabel> {
 191        None
 192    }
 193
 194    async fn label_for_symbol(
 195        &self,
 196        _: &str,
 197        _: lsp::SymbolKind,
 198        _: &Arc<Language>,
 199    ) -> Option<CodeLabel> {
 200        None
 201    }
 202
 203    async fn server_args(&self) -> Vec<String> {
 204        Vec::new()
 205    }
 206
 207    async fn initialization_options(&self) -> Option<Value> {
 208        None
 209    }
 210
 211    async fn disk_based_diagnostic_sources(&self) -> Vec<String> {
 212        Default::default()
 213    }
 214
 215    async fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
 216        None
 217    }
 218
 219    async fn language_ids(&self) -> HashMap<String, String> {
 220        Default::default()
 221    }
 222}
 223
 224#[derive(Clone, Debug, PartialEq, Eq)]
 225pub struct CodeLabel {
 226    pub text: String,
 227    pub runs: Vec<(Range<usize>, HighlightId)>,
 228    pub filter_range: Range<usize>,
 229}
 230
 231#[derive(Deserialize)]
 232pub struct LanguageConfig {
 233    pub name: Arc<str>,
 234    pub path_suffixes: Vec<String>,
 235    pub brackets: BracketPairConfig,
 236    #[serde(default = "auto_indent_using_last_non_empty_line_default")]
 237    pub auto_indent_using_last_non_empty_line: bool,
 238    #[serde(default, deserialize_with = "deserialize_regex")]
 239    pub increase_indent_pattern: Option<Regex>,
 240    #[serde(default, deserialize_with = "deserialize_regex")]
 241    pub decrease_indent_pattern: Option<Regex>,
 242    #[serde(default)]
 243    pub autoclose_before: String,
 244    #[serde(default)]
 245    pub line_comment: Option<Arc<str>>,
 246    #[serde(default)]
 247    pub block_comment: Option<(Arc<str>, Arc<str>)>,
 248    #[serde(default)]
 249    pub overrides: HashMap<String, LanguageConfigOverride>,
 250}
 251
 252#[derive(Debug, Default)]
 253pub struct LanguageQueries {
 254    pub highlights: Option<Cow<'static, str>>,
 255    pub brackets: Option<Cow<'static, str>>,
 256    pub indents: Option<Cow<'static, str>>,
 257    pub outline: Option<Cow<'static, str>>,
 258    pub injections: Option<Cow<'static, str>>,
 259    pub overrides: Option<Cow<'static, str>>,
 260}
 261
 262#[derive(Clone, Debug)]
 263pub struct LanguageScope {
 264    language: Arc<Language>,
 265    override_id: Option<u32>,
 266}
 267
 268#[derive(Deserialize, Default, Debug)]
 269pub struct LanguageConfigOverride {
 270    #[serde(default)]
 271    pub line_comment: Override<Arc<str>>,
 272    #[serde(default)]
 273    pub block_comment: Override<(Arc<str>, Arc<str>)>,
 274    #[serde(skip_deserializing)]
 275    pub disabled_bracket_ixs: Vec<u16>,
 276}
 277
 278#[derive(Deserialize, Debug)]
 279#[serde(untagged)]
 280pub enum Override<T> {
 281    Remove { remove: bool },
 282    Set(T),
 283}
 284
 285impl<T> Default for Override<T> {
 286    fn default() -> Self {
 287        Override::Remove { remove: false }
 288    }
 289}
 290
 291impl<T> Override<T> {
 292    fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
 293        match this {
 294            Some(Self::Set(value)) => Some(value),
 295            Some(Self::Remove { remove: true }) => None,
 296            Some(Self::Remove { remove: false }) | None => original,
 297        }
 298    }
 299}
 300
 301impl Default for LanguageConfig {
 302    fn default() -> Self {
 303        Self {
 304            name: "".into(),
 305            path_suffixes: Default::default(),
 306            brackets: Default::default(),
 307            auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
 308            increase_indent_pattern: Default::default(),
 309            decrease_indent_pattern: Default::default(),
 310            autoclose_before: Default::default(),
 311            line_comment: Default::default(),
 312            block_comment: Default::default(),
 313            overrides: Default::default(),
 314        }
 315    }
 316}
 317
 318fn auto_indent_using_last_non_empty_line_default() -> bool {
 319    true
 320}
 321
 322fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
 323    let source = Option::<String>::deserialize(d)?;
 324    if let Some(source) = source {
 325        Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
 326    } else {
 327        Ok(None)
 328    }
 329}
 330
 331#[cfg(any(test, feature = "test-support"))]
 332pub struct FakeLspAdapter {
 333    pub name: &'static str,
 334    pub capabilities: lsp::ServerCapabilities,
 335    pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
 336    pub disk_based_diagnostics_progress_token: Option<String>,
 337    pub disk_based_diagnostics_sources: Vec<String>,
 338}
 339
 340#[derive(Clone, Debug, Default)]
 341pub struct BracketPairConfig {
 342    pub pairs: Vec<BracketPair>,
 343    pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
 344}
 345
 346impl<'de> Deserialize<'de> for BracketPairConfig {
 347    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
 348    where
 349        D: Deserializer<'de>,
 350    {
 351        #[derive(Deserialize)]
 352        pub struct Entry {
 353            #[serde(flatten)]
 354            pub bracket_pair: BracketPair,
 355            #[serde(default)]
 356            pub not_in: Vec<String>,
 357        }
 358
 359        let result = Vec::<Entry>::deserialize(deserializer)?;
 360        let mut brackets = Vec::with_capacity(result.len());
 361        let mut disabled_scopes_by_bracket_ix = Vec::with_capacity(result.len());
 362        for entry in result {
 363            brackets.push(entry.bracket_pair);
 364            disabled_scopes_by_bracket_ix.push(entry.not_in);
 365        }
 366
 367        Ok(BracketPairConfig {
 368            pairs: brackets,
 369            disabled_scopes_by_bracket_ix,
 370        })
 371    }
 372}
 373
 374#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
 375pub struct BracketPair {
 376    pub start: String,
 377    pub end: String,
 378    pub close: bool,
 379    pub newline: bool,
 380}
 381
 382pub struct Language {
 383    pub(crate) config: LanguageConfig,
 384    pub(crate) grammar: Option<Arc<Grammar>>,
 385    pub(crate) adapter: Option<Arc<CachedLspAdapter>>,
 386
 387    #[cfg(any(test, feature = "test-support"))]
 388    fake_adapter: Option<(
 389        mpsc::UnboundedSender<lsp::FakeLanguageServer>,
 390        Arc<FakeLspAdapter>,
 391    )>,
 392}
 393
 394pub struct Grammar {
 395    id: usize,
 396    pub(crate) ts_language: tree_sitter::Language,
 397    pub(crate) error_query: Query,
 398    pub(crate) highlights_query: Option<Query>,
 399    pub(crate) brackets_config: Option<BracketConfig>,
 400    pub(crate) indents_config: Option<IndentConfig>,
 401    pub(crate) outline_config: Option<OutlineConfig>,
 402    pub(crate) injection_config: Option<InjectionConfig>,
 403    pub(crate) override_config: Option<OverrideConfig>,
 404    pub(crate) highlight_map: Mutex<HighlightMap>,
 405}
 406
 407struct IndentConfig {
 408    query: Query,
 409    indent_capture_ix: u32,
 410    start_capture_ix: Option<u32>,
 411    end_capture_ix: Option<u32>,
 412    outdent_capture_ix: Option<u32>,
 413}
 414
 415struct OutlineConfig {
 416    query: Query,
 417    item_capture_ix: u32,
 418    name_capture_ix: u32,
 419    context_capture_ix: Option<u32>,
 420}
 421
 422struct InjectionConfig {
 423    query: Query,
 424    content_capture_ix: u32,
 425    language_capture_ix: Option<u32>,
 426    patterns: Vec<InjectionPatternConfig>,
 427}
 428
 429struct OverrideConfig {
 430    query: Query,
 431    values: HashMap<u32, (String, LanguageConfigOverride)>,
 432}
 433
 434#[derive(Default, Clone)]
 435struct InjectionPatternConfig {
 436    language: Option<Box<str>>,
 437    combined: bool,
 438}
 439
 440struct BracketConfig {
 441    query: Query,
 442    open_capture_ix: u32,
 443    close_capture_ix: u32,
 444}
 445
 446#[derive(Clone)]
 447pub enum LanguageServerBinaryStatus {
 448    CheckingForUpdate,
 449    Downloading,
 450    Downloaded,
 451    Cached,
 452    Failed { error: String },
 453}
 454
 455struct AvailableLanguage {
 456    path: &'static str,
 457    config: LanguageConfig,
 458    grammar: tree_sitter::Language,
 459    lsp_adapter: Option<Box<dyn LspAdapter>>,
 460    get_queries: fn(&str) -> LanguageQueries,
 461}
 462
 463pub struct LanguageRegistry {
 464    languages: RwLock<Vec<Arc<Language>>>,
 465    available_languages: RwLock<Vec<AvailableLanguage>>,
 466    language_server_download_dir: Option<Arc<Path>>,
 467    lsp_binary_statuses_tx: async_broadcast::Sender<(Arc<Language>, LanguageServerBinaryStatus)>,
 468    lsp_binary_statuses_rx: async_broadcast::Receiver<(Arc<Language>, LanguageServerBinaryStatus)>,
 469    login_shell_env_loaded: Shared<Task<()>>,
 470    #[allow(clippy::type_complexity)]
 471    lsp_binary_paths: Mutex<
 472        HashMap<
 473            LanguageServerName,
 474            Shared<BoxFuture<'static, Result<PathBuf, Arc<anyhow::Error>>>>,
 475        >,
 476    >,
 477    subscription: RwLock<(watch::Sender<()>, watch::Receiver<()>)>,
 478    theme: RwLock<Option<Arc<Theme>>>,
 479    executor: Option<Arc<Background>>,
 480    version: AtomicUsize,
 481}
 482
 483impl LanguageRegistry {
 484    pub fn new(login_shell_env_loaded: Task<()>) -> Self {
 485        let (lsp_binary_statuses_tx, lsp_binary_statuses_rx) = async_broadcast::broadcast(16);
 486        Self {
 487            language_server_download_dir: None,
 488            languages: RwLock::new(vec![PLAIN_TEXT.clone()]),
 489            available_languages: Default::default(),
 490            lsp_binary_statuses_tx,
 491            lsp_binary_statuses_rx,
 492            login_shell_env_loaded: login_shell_env_loaded.shared(),
 493            lsp_binary_paths: Default::default(),
 494            subscription: RwLock::new(watch::channel()),
 495            theme: Default::default(),
 496            version: Default::default(),
 497            executor: None,
 498        }
 499    }
 500
 501    #[cfg(any(test, feature = "test-support"))]
 502    pub fn test() -> Self {
 503        Self::new(Task::ready(()))
 504    }
 505
 506    pub fn set_executor(&mut self, executor: Arc<Background>) {
 507        self.executor = Some(executor);
 508    }
 509
 510    pub fn register(
 511        &self,
 512        path: &'static str,
 513        config: LanguageConfig,
 514        grammar: tree_sitter::Language,
 515        lsp_adapter: Option<Box<dyn LspAdapter>>,
 516        get_queries: fn(&str) -> LanguageQueries,
 517    ) {
 518        self.available_languages.write().push(AvailableLanguage {
 519            path,
 520            config,
 521            grammar,
 522            lsp_adapter,
 523            get_queries,
 524        });
 525    }
 526
 527    pub fn language_names(&self) -> Vec<String> {
 528        let mut result = self
 529            .available_languages
 530            .read()
 531            .iter()
 532            .map(|l| l.config.name.to_string())
 533            .chain(
 534                self.languages
 535                    .read()
 536                    .iter()
 537                    .map(|l| l.config.name.to_string()),
 538            )
 539            .collect::<Vec<_>>();
 540        result.sort_unstable();
 541        result
 542    }
 543
 544    pub fn add(&self, language: Arc<Language>) {
 545        if let Some(theme) = self.theme.read().clone() {
 546            language.set_theme(&theme.editor.syntax);
 547        }
 548        self.languages.write().push(language);
 549        self.version.fetch_add(1, SeqCst);
 550        *self.subscription.write().0.borrow_mut() = ();
 551    }
 552
 553    pub fn subscribe(&self) -> watch::Receiver<()> {
 554        self.subscription.read().1.clone()
 555    }
 556
 557    pub fn version(&self) -> usize {
 558        self.version.load(SeqCst)
 559    }
 560
 561    pub fn set_theme(&self, theme: Arc<Theme>) {
 562        *self.theme.write() = Some(theme.clone());
 563        for language in self.languages.read().iter() {
 564            language.set_theme(&theme.editor.syntax);
 565        }
 566    }
 567
 568    pub fn set_language_server_download_dir(&mut self, path: impl Into<Arc<Path>>) {
 569        self.language_server_download_dir = Some(path.into());
 570    }
 571
 572    pub fn language_for_name(
 573        self: &Arc<Self>,
 574        name: &str,
 575    ) -> UnwrapFuture<oneshot::Receiver<Result<Arc<Language>>>> {
 576        let name = UniCase::new(name);
 577        self.get_or_load_language(|config| UniCase::new(config.name.as_ref()) == name)
 578    }
 579
 580    pub fn language_for_name_or_extension(
 581        self: &Arc<Self>,
 582        string: &str,
 583    ) -> UnwrapFuture<oneshot::Receiver<Result<Arc<Language>>>> {
 584        let string = UniCase::new(string);
 585        self.get_or_load_language(|config| {
 586            UniCase::new(config.name.as_ref()) == string
 587                || config
 588                    .path_suffixes
 589                    .iter()
 590                    .any(|suffix| UniCase::new(suffix) == string)
 591        })
 592    }
 593
 594    pub fn language_for_path(
 595        self: &Arc<Self>,
 596        path: impl AsRef<Path>,
 597    ) -> UnwrapFuture<oneshot::Receiver<Result<Arc<Language>>>> {
 598        let path = path.as_ref();
 599        let filename = path.file_name().and_then(|name| name.to_str());
 600        let extension = path.extension().and_then(|name| name.to_str());
 601        let path_suffixes = [extension, filename];
 602        self.get_or_load_language(|config| {
 603            config
 604                .path_suffixes
 605                .iter()
 606                .any(|suffix| path_suffixes.contains(&Some(suffix.as_str())))
 607        })
 608    }
 609
 610    fn get_or_load_language(
 611        self: &Arc<Self>,
 612        callback: impl Fn(&LanguageConfig) -> bool,
 613    ) -> UnwrapFuture<oneshot::Receiver<Result<Arc<Language>>>> {
 614        let (tx, rx) = oneshot::channel();
 615
 616        if let Some(language) = self
 617            .languages
 618            .read()
 619            .iter()
 620            .find(|language| callback(&language.config))
 621        {
 622            let _ = tx.send(Ok(language.clone()));
 623        } else if let Some(executor) = self.executor.clone() {
 624            let mut available_languages = self.available_languages.write();
 625
 626            if let Some(ix) = available_languages.iter().position(|l| callback(&l.config)) {
 627                let language = available_languages.remove(ix);
 628                drop(available_languages);
 629                let name = language.config.name.clone();
 630                let this = self.clone();
 631                executor
 632                    .spawn(async move {
 633                        let queries = (language.get_queries)(&language.path);
 634                        let language = Language::new(language.config, Some(language.grammar))
 635                            .with_lsp_adapter(language.lsp_adapter)
 636                            .await;
 637                        match language.with_queries(queries) {
 638                            Ok(language) => {
 639                                let language = Arc::new(language);
 640                                this.add(language.clone());
 641                                let _ = tx.send(Ok(language));
 642                            }
 643                            Err(err) => {
 644                                let _ = tx.send(Err(anyhow!(
 645                                    "failed to load language {}: {}",
 646                                    name,
 647                                    err
 648                                )));
 649                            }
 650                        };
 651                    })
 652                    .detach();
 653            } else {
 654                let _ = tx.send(Err(anyhow!("language not found")));
 655            }
 656        } else {
 657            let _ = tx.send(Err(anyhow!("executor does not exist")));
 658        }
 659
 660        rx.unwrap()
 661    }
 662
 663    pub fn to_vec(&self) -> Vec<Arc<Language>> {
 664        self.languages.read().iter().cloned().collect()
 665    }
 666
 667    pub fn start_language_server(
 668        self: &Arc<Self>,
 669        server_id: usize,
 670        language: Arc<Language>,
 671        root_path: Arc<Path>,
 672        http_client: Arc<dyn HttpClient>,
 673        cx: &mut MutableAppContext,
 674    ) -> Option<Task<Result<lsp::LanguageServer>>> {
 675        #[cfg(any(test, feature = "test-support"))]
 676        if language.fake_adapter.is_some() {
 677            let language = language;
 678            return Some(cx.spawn(|cx| async move {
 679                let (servers_tx, fake_adapter) = language.fake_adapter.as_ref().unwrap();
 680                let (server, mut fake_server) = lsp::LanguageServer::fake(
 681                    fake_adapter.name.to_string(),
 682                    fake_adapter.capabilities.clone(),
 683                    cx.clone(),
 684                );
 685
 686                if let Some(initializer) = &fake_adapter.initializer {
 687                    initializer(&mut fake_server);
 688                }
 689
 690                let servers_tx = servers_tx.clone();
 691                cx.background()
 692                    .spawn(async move {
 693                        if fake_server
 694                            .try_receive_notification::<lsp::notification::Initialized>()
 695                            .await
 696                            .is_some()
 697                        {
 698                            servers_tx.unbounded_send(fake_server).ok();
 699                        }
 700                    })
 701                    .detach();
 702                Ok(server)
 703            }));
 704        }
 705
 706        let download_dir = self
 707            .language_server_download_dir
 708            .clone()
 709            .ok_or_else(|| anyhow!("language server download directory has not been assigned"))
 710            .log_err()?;
 711
 712        let this = self.clone();
 713        let adapter = language.adapter.clone()?;
 714        let lsp_binary_statuses = self.lsp_binary_statuses_tx.clone();
 715        let login_shell_env_loaded = self.login_shell_env_loaded.clone();
 716        Some(cx.spawn(|cx| async move {
 717            login_shell_env_loaded.await;
 718            let server_binary_path = this
 719                .lsp_binary_paths
 720                .lock()
 721                .entry(adapter.name.clone())
 722                .or_insert_with(|| {
 723                    get_server_binary_path(
 724                        adapter.clone(),
 725                        language.clone(),
 726                        http_client,
 727                        download_dir,
 728                        lsp_binary_statuses,
 729                    )
 730                    .map_err(Arc::new)
 731                    .boxed()
 732                    .shared()
 733                })
 734                .clone()
 735                .map_err(|e| anyhow!(e));
 736
 737            let server_binary_path = server_binary_path.await?;
 738            let server_args = &adapter.server_args;
 739            let server = lsp::LanguageServer::new(
 740                server_id,
 741                &server_binary_path,
 742                server_args,
 743                &root_path,
 744                cx,
 745            )?;
 746            Ok(server)
 747        }))
 748    }
 749
 750    pub fn language_server_binary_statuses(
 751        &self,
 752    ) -> async_broadcast::Receiver<(Arc<Language>, LanguageServerBinaryStatus)> {
 753        self.lsp_binary_statuses_rx.clone()
 754    }
 755}
 756
 757#[cfg(any(test, feature = "test-support"))]
 758impl Default for LanguageRegistry {
 759    fn default() -> Self {
 760        Self::test()
 761    }
 762}
 763
 764async fn get_server_binary_path(
 765    adapter: Arc<CachedLspAdapter>,
 766    language: Arc<Language>,
 767    http_client: Arc<dyn HttpClient>,
 768    download_dir: Arc<Path>,
 769    statuses: async_broadcast::Sender<(Arc<Language>, LanguageServerBinaryStatus)>,
 770) -> Result<PathBuf> {
 771    let container_dir = download_dir.join(adapter.name.0.as_ref());
 772    if !container_dir.exists() {
 773        smol::fs::create_dir_all(&container_dir)
 774            .await
 775            .context("failed to create container directory")?;
 776    }
 777
 778    let path = fetch_latest_server_binary_path(
 779        adapter.clone(),
 780        language.clone(),
 781        http_client,
 782        &container_dir,
 783        statuses.clone(),
 784    )
 785    .await;
 786    if let Err(error) = path.as_ref() {
 787        if let Some(cached_path) = adapter.cached_server_binary(container_dir).await {
 788            statuses
 789                .broadcast((language.clone(), LanguageServerBinaryStatus::Cached))
 790                .await?;
 791            return Ok(cached_path);
 792        } else {
 793            statuses
 794                .broadcast((
 795                    language.clone(),
 796                    LanguageServerBinaryStatus::Failed {
 797                        error: format!("{:?}", error),
 798                    },
 799                ))
 800                .await?;
 801        }
 802    }
 803    path
 804}
 805
 806async fn fetch_latest_server_binary_path(
 807    adapter: Arc<CachedLspAdapter>,
 808    language: Arc<Language>,
 809    http_client: Arc<dyn HttpClient>,
 810    container_dir: &Path,
 811    lsp_binary_statuses_tx: async_broadcast::Sender<(Arc<Language>, LanguageServerBinaryStatus)>,
 812) -> Result<PathBuf> {
 813    let container_dir: Arc<Path> = container_dir.into();
 814    lsp_binary_statuses_tx
 815        .broadcast((
 816            language.clone(),
 817            LanguageServerBinaryStatus::CheckingForUpdate,
 818        ))
 819        .await?;
 820    let version_info = adapter
 821        .fetch_latest_server_version(http_client.clone())
 822        .await?;
 823    lsp_binary_statuses_tx
 824        .broadcast((language.clone(), LanguageServerBinaryStatus::Downloading))
 825        .await?;
 826    let path = adapter
 827        .fetch_server_binary(version_info, http_client, container_dir.to_path_buf())
 828        .await?;
 829    lsp_binary_statuses_tx
 830        .broadcast((language.clone(), LanguageServerBinaryStatus::Downloaded))
 831        .await?;
 832    Ok(path)
 833}
 834
 835impl Language {
 836    pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
 837        Self {
 838            config,
 839            grammar: ts_language.map(|ts_language| {
 840                Arc::new(Grammar {
 841                    id: NEXT_GRAMMAR_ID.fetch_add(1, SeqCst),
 842                    highlights_query: None,
 843                    brackets_config: None,
 844                    outline_config: None,
 845                    indents_config: None,
 846                    injection_config: None,
 847                    override_config: None,
 848                    error_query: Query::new(ts_language, "(ERROR) @error").unwrap(),
 849                    ts_language,
 850                    highlight_map: Default::default(),
 851                })
 852            }),
 853            adapter: None,
 854
 855            #[cfg(any(test, feature = "test-support"))]
 856            fake_adapter: None,
 857        }
 858    }
 859
 860    pub fn lsp_adapter(&self) -> Option<Arc<CachedLspAdapter>> {
 861        self.adapter.clone()
 862    }
 863
 864    pub fn id(&self) -> Option<usize> {
 865        self.grammar.as_ref().map(|g| g.id)
 866    }
 867
 868    pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
 869        if let Some(query) = queries.highlights {
 870            self = self
 871                .with_highlights_query(query.as_ref())
 872                .expect("failed to evaluate highlights query");
 873        }
 874        if let Some(query) = queries.brackets {
 875            self = self
 876                .with_brackets_query(query.as_ref())
 877                .expect("failed to load brackets query");
 878        }
 879        if let Some(query) = queries.indents {
 880            self = self
 881                .with_indents_query(query.as_ref())
 882                .expect("failed to load indents query");
 883        }
 884        if let Some(query) = queries.outline {
 885            self = self
 886                .with_outline_query(query.as_ref())
 887                .expect("failed to load outline query");
 888        }
 889        if let Some(query) = queries.injections {
 890            self = self
 891                .with_injection_query(query.as_ref())
 892                .expect("failed to load injection query");
 893        }
 894        if let Some(query) = queries.overrides {
 895            self = self
 896                .with_override_query(query.as_ref())
 897                .expect("failed to load override query");
 898        }
 899        Ok(self)
 900    }
 901    pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
 902        let grammar = self.grammar_mut();
 903        grammar.highlights_query = Some(Query::new(grammar.ts_language, source)?);
 904        Ok(self)
 905    }
 906
 907    pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
 908        let grammar = self.grammar_mut();
 909        let query = Query::new(grammar.ts_language, source)?;
 910        let mut item_capture_ix = None;
 911        let mut name_capture_ix = None;
 912        let mut context_capture_ix = None;
 913        get_capture_indices(
 914            &query,
 915            &mut [
 916                ("item", &mut item_capture_ix),
 917                ("name", &mut name_capture_ix),
 918                ("context", &mut context_capture_ix),
 919            ],
 920        );
 921        if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
 922            grammar.outline_config = Some(OutlineConfig {
 923                query,
 924                item_capture_ix,
 925                name_capture_ix,
 926                context_capture_ix,
 927            });
 928        }
 929        Ok(self)
 930    }
 931
 932    pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
 933        let grammar = self.grammar_mut();
 934        let query = Query::new(grammar.ts_language, source)?;
 935        let mut open_capture_ix = None;
 936        let mut close_capture_ix = None;
 937        get_capture_indices(
 938            &query,
 939            &mut [
 940                ("open", &mut open_capture_ix),
 941                ("close", &mut close_capture_ix),
 942            ],
 943        );
 944        if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
 945            grammar.brackets_config = Some(BracketConfig {
 946                query,
 947                open_capture_ix,
 948                close_capture_ix,
 949            });
 950        }
 951        Ok(self)
 952    }
 953
 954    pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
 955        let grammar = self.grammar_mut();
 956        let query = Query::new(grammar.ts_language, source)?;
 957        let mut indent_capture_ix = None;
 958        let mut start_capture_ix = None;
 959        let mut end_capture_ix = None;
 960        let mut outdent_capture_ix = None;
 961        get_capture_indices(
 962            &query,
 963            &mut [
 964                ("indent", &mut indent_capture_ix),
 965                ("start", &mut start_capture_ix),
 966                ("end", &mut end_capture_ix),
 967                ("outdent", &mut outdent_capture_ix),
 968            ],
 969        );
 970        if let Some(indent_capture_ix) = indent_capture_ix {
 971            grammar.indents_config = Some(IndentConfig {
 972                query,
 973                indent_capture_ix,
 974                start_capture_ix,
 975                end_capture_ix,
 976                outdent_capture_ix,
 977            });
 978        }
 979        Ok(self)
 980    }
 981
 982    pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
 983        let grammar = self.grammar_mut();
 984        let query = Query::new(grammar.ts_language, source)?;
 985        let mut language_capture_ix = None;
 986        let mut content_capture_ix = None;
 987        get_capture_indices(
 988            &query,
 989            &mut [
 990                ("language", &mut language_capture_ix),
 991                ("content", &mut content_capture_ix),
 992            ],
 993        );
 994        let patterns = (0..query.pattern_count())
 995            .map(|ix| {
 996                let mut config = InjectionPatternConfig::default();
 997                for setting in query.property_settings(ix) {
 998                    match setting.key.as_ref() {
 999                        "language" => {
1000                            config.language = setting.value.clone();
1001                        }
1002                        "combined" => {
1003                            config.combined = true;
1004                        }
1005                        _ => {}
1006                    }
1007                }
1008                config
1009            })
1010            .collect();
1011        if let Some(content_capture_ix) = content_capture_ix {
1012            grammar.injection_config = Some(InjectionConfig {
1013                query,
1014                language_capture_ix,
1015                content_capture_ix,
1016                patterns,
1017            });
1018        }
1019        Ok(self)
1020    }
1021
1022    pub fn with_override_query(mut self, source: &str) -> Result<Self> {
1023        let query = Query::new(self.grammar_mut().ts_language, source)?;
1024
1025        let mut override_configs_by_id = HashMap::default();
1026        for (ix, name) in query.capture_names().iter().enumerate() {
1027            if !name.starts_with('_') {
1028                let value = self.config.overrides.remove(name).unwrap_or_default();
1029                override_configs_by_id.insert(ix as u32, (name.clone(), value));
1030            }
1031        }
1032
1033        if !self.config.overrides.is_empty() {
1034            let keys = self.config.overrides.keys().collect::<Vec<_>>();
1035            Err(anyhow!(
1036                "language {:?} has overrides in config not in query: {keys:?}",
1037                self.config.name
1038            ))?;
1039        }
1040
1041        for disabled_scope_name in self
1042            .config
1043            .brackets
1044            .disabled_scopes_by_bracket_ix
1045            .iter()
1046            .flatten()
1047        {
1048            if !override_configs_by_id
1049                .values()
1050                .any(|(scope_name, _)| scope_name == disabled_scope_name)
1051            {
1052                Err(anyhow!(
1053                    "language {:?} has overrides in config not in query: {disabled_scope_name:?}",
1054                    self.config.name
1055                ))?;
1056            }
1057        }
1058
1059        for (name, override_config) in override_configs_by_id.values_mut() {
1060            override_config.disabled_bracket_ixs = self
1061                .config
1062                .brackets
1063                .disabled_scopes_by_bracket_ix
1064                .iter()
1065                .enumerate()
1066                .filter_map(|(ix, disabled_scope_names)| {
1067                    if disabled_scope_names.contains(name) {
1068                        Some(ix as u16)
1069                    } else {
1070                        None
1071                    }
1072                })
1073                .collect();
1074        }
1075
1076        self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1077        self.grammar_mut().override_config = Some(OverrideConfig {
1078            query,
1079            values: override_configs_by_id,
1080        });
1081        Ok(self)
1082    }
1083
1084    fn grammar_mut(&mut self) -> &mut Grammar {
1085        Arc::get_mut(self.grammar.as_mut().unwrap()).unwrap()
1086    }
1087
1088    pub async fn with_lsp_adapter(mut self, lsp_adapter: Option<Box<dyn LspAdapter>>) -> Self {
1089        if let Some(adapter) = lsp_adapter {
1090            self.adapter = Some(CachedLspAdapter::new(adapter).await);
1091        }
1092        self
1093    }
1094
1095    #[cfg(any(test, feature = "test-support"))]
1096    pub async fn set_fake_lsp_adapter(
1097        &mut self,
1098        fake_lsp_adapter: Arc<FakeLspAdapter>,
1099    ) -> mpsc::UnboundedReceiver<lsp::FakeLanguageServer> {
1100        let (servers_tx, servers_rx) = mpsc::unbounded();
1101        self.fake_adapter = Some((servers_tx, fake_lsp_adapter.clone()));
1102        let adapter = CachedLspAdapter::new(Box::new(fake_lsp_adapter)).await;
1103        self.adapter = Some(adapter);
1104        servers_rx
1105    }
1106
1107    pub fn name(&self) -> Arc<str> {
1108        self.config.name.clone()
1109    }
1110
1111    pub async fn disk_based_diagnostic_sources(&self) -> &[String] {
1112        match self.adapter.as_ref() {
1113            Some(adapter) => &adapter.disk_based_diagnostic_sources,
1114            None => &[],
1115        }
1116    }
1117
1118    pub async fn disk_based_diagnostics_progress_token(&self) -> Option<&str> {
1119        if let Some(adapter) = self.adapter.as_ref() {
1120            adapter.disk_based_diagnostics_progress_token.as_deref()
1121        } else {
1122            None
1123        }
1124    }
1125
1126    pub async fn process_diagnostics(&self, diagnostics: &mut lsp::PublishDiagnosticsParams) {
1127        if let Some(processor) = self.adapter.as_ref() {
1128            processor.process_diagnostics(diagnostics).await;
1129        }
1130    }
1131
1132    pub async fn process_completion(self: &Arc<Self>, completion: &mut lsp::CompletionItem) {
1133        if let Some(adapter) = self.adapter.as_ref() {
1134            adapter.process_completion(completion).await;
1135        }
1136    }
1137
1138    pub async fn label_for_completion(
1139        self: &Arc<Self>,
1140        completion: &lsp::CompletionItem,
1141    ) -> Option<CodeLabel> {
1142        self.adapter
1143            .as_ref()?
1144            .label_for_completion(completion, self)
1145            .await
1146    }
1147
1148    pub async fn label_for_symbol(
1149        self: &Arc<Self>,
1150        name: &str,
1151        kind: lsp::SymbolKind,
1152    ) -> Option<CodeLabel> {
1153        self.adapter
1154            .as_ref()?
1155            .label_for_symbol(name, kind, self)
1156            .await
1157    }
1158
1159    pub fn highlight_text<'a>(
1160        self: &'a Arc<Self>,
1161        text: &'a Rope,
1162        range: Range<usize>,
1163    ) -> Vec<(Range<usize>, HighlightId)> {
1164        let mut result = Vec::new();
1165        if let Some(grammar) = &self.grammar {
1166            let tree = grammar.parse_text(text, None);
1167            let captures =
1168                SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1169                    grammar.highlights_query.as_ref()
1170                });
1171            let highlight_maps = vec![grammar.highlight_map()];
1172            let mut offset = 0;
1173            for chunk in BufferChunks::new(text, range, Some((captures, highlight_maps)), vec![]) {
1174                let end_offset = offset + chunk.text.len();
1175                if let Some(highlight_id) = chunk.syntax_highlight_id {
1176                    if !highlight_id.is_default() {
1177                        result.push((offset..end_offset, highlight_id));
1178                    }
1179                }
1180                offset = end_offset;
1181            }
1182        }
1183        result
1184    }
1185
1186    pub fn path_suffixes(&self) -> &[String] {
1187        &self.config.path_suffixes
1188    }
1189
1190    pub fn should_autoclose_before(&self, c: char) -> bool {
1191        c.is_whitespace() || self.config.autoclose_before.contains(c)
1192    }
1193
1194    pub fn set_theme(&self, theme: &SyntaxTheme) {
1195        if let Some(grammar) = self.grammar.as_ref() {
1196            if let Some(highlights_query) = &grammar.highlights_query {
1197                *grammar.highlight_map.lock() =
1198                    HighlightMap::new(highlights_query.capture_names(), theme);
1199            }
1200        }
1201    }
1202
1203    pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1204        self.grammar.as_ref()
1205    }
1206}
1207
1208impl LanguageScope {
1209    pub fn line_comment_prefix(&self) -> Option<&Arc<str>> {
1210        Override::as_option(
1211            self.config_override().map(|o| &o.line_comment),
1212            self.language.config.line_comment.as_ref(),
1213        )
1214    }
1215
1216    pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1217        Override::as_option(
1218            self.config_override().map(|o| &o.block_comment),
1219            self.language.config.block_comment.as_ref(),
1220        )
1221        .map(|e| (&e.0, &e.1))
1222    }
1223
1224    pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1225        let mut disabled_ids = self
1226            .config_override()
1227            .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1228        self.language
1229            .config
1230            .brackets
1231            .pairs
1232            .iter()
1233            .enumerate()
1234            .map(move |(ix, bracket)| {
1235                let mut is_enabled = true;
1236                if let Some(next_disabled_ix) = disabled_ids.first() {
1237                    if ix == *next_disabled_ix as usize {
1238                        disabled_ids = &disabled_ids[1..];
1239                        is_enabled = false;
1240                    }
1241                }
1242                (bracket, is_enabled)
1243            })
1244    }
1245
1246    pub fn should_autoclose_before(&self, c: char) -> bool {
1247        c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1248    }
1249
1250    fn config_override(&self) -> Option<&LanguageConfigOverride> {
1251        let id = self.override_id?;
1252        let grammar = self.language.grammar.as_ref()?;
1253        let override_config = grammar.override_config.as_ref()?;
1254        override_config.values.get(&id).map(|e| &e.1)
1255    }
1256}
1257
1258impl Hash for Language {
1259    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1260        self.id().hash(state)
1261    }
1262}
1263
1264impl PartialEq for Language {
1265    fn eq(&self, other: &Self) -> bool {
1266        self.id().eq(&other.id())
1267    }
1268}
1269
1270impl Eq for Language {}
1271
1272impl Debug for Language {
1273    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1274        f.debug_struct("Language")
1275            .field("name", &self.config.name)
1276            .finish()
1277    }
1278}
1279
1280impl Grammar {
1281    pub fn id(&self) -> usize {
1282        self.id
1283    }
1284
1285    fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1286        PARSER.with(|parser| {
1287            let mut parser = parser.borrow_mut();
1288            parser
1289                .set_language(self.ts_language)
1290                .expect("incompatible grammar");
1291            let mut chunks = text.chunks_in_range(0..text.len());
1292            parser
1293                .parse_with(
1294                    &mut move |offset, _| {
1295                        chunks.seek(offset);
1296                        chunks.next().unwrap_or("").as_bytes()
1297                    },
1298                    old_tree.as_ref(),
1299                )
1300                .unwrap()
1301        })
1302    }
1303
1304    pub fn highlight_map(&self) -> HighlightMap {
1305        self.highlight_map.lock().clone()
1306    }
1307
1308    pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1309        let capture_id = self
1310            .highlights_query
1311            .as_ref()?
1312            .capture_index_for_name(name)?;
1313        Some(self.highlight_map.lock().get(capture_id))
1314    }
1315}
1316
1317impl CodeLabel {
1318    pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1319        let mut result = Self {
1320            runs: Vec::new(),
1321            filter_range: 0..text.len(),
1322            text,
1323        };
1324        if let Some(filter_text) = filter_text {
1325            if let Some(ix) = result.text.find(filter_text) {
1326                result.filter_range = ix..ix + filter_text.len();
1327            }
1328        }
1329        result
1330    }
1331}
1332
1333#[cfg(any(test, feature = "test-support"))]
1334impl Default for FakeLspAdapter {
1335    fn default() -> Self {
1336        Self {
1337            name: "the-fake-language-server",
1338            capabilities: lsp::LanguageServer::full_capabilities(),
1339            initializer: None,
1340            disk_based_diagnostics_progress_token: None,
1341            disk_based_diagnostics_sources: Vec::new(),
1342        }
1343    }
1344}
1345
1346#[cfg(any(test, feature = "test-support"))]
1347#[async_trait]
1348impl LspAdapter for Arc<FakeLspAdapter> {
1349    async fn name(&self) -> LanguageServerName {
1350        LanguageServerName(self.name.into())
1351    }
1352
1353    async fn fetch_latest_server_version(
1354        &self,
1355        _: Arc<dyn HttpClient>,
1356    ) -> Result<Box<dyn 'static + Send + Any>> {
1357        unreachable!();
1358    }
1359
1360    async fn fetch_server_binary(
1361        &self,
1362        _: Box<dyn 'static + Send + Any>,
1363        _: Arc<dyn HttpClient>,
1364        _: PathBuf,
1365    ) -> Result<PathBuf> {
1366        unreachable!();
1367    }
1368
1369    async fn cached_server_binary(&self, _: PathBuf) -> Option<PathBuf> {
1370        unreachable!();
1371    }
1372
1373    async fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
1374
1375    async fn disk_based_diagnostic_sources(&self) -> Vec<String> {
1376        self.disk_based_diagnostics_sources.clone()
1377    }
1378
1379    async fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
1380        self.disk_based_diagnostics_progress_token.clone()
1381    }
1382}
1383
1384fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
1385    for (ix, name) in query.capture_names().iter().enumerate() {
1386        for (capture_name, index) in captures.iter_mut() {
1387            if capture_name == name {
1388                **index = Some(ix as u32);
1389                break;
1390            }
1391        }
1392    }
1393}
1394
1395pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
1396    lsp::Position::new(point.row, point.column)
1397}
1398
1399pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
1400    Unclipped(PointUtf16::new(point.line, point.character))
1401}
1402
1403pub fn range_to_lsp(range: Range<PointUtf16>) -> lsp::Range {
1404    lsp::Range {
1405        start: point_to_lsp(range.start),
1406        end: point_to_lsp(range.end),
1407    }
1408}
1409
1410pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
1411    let mut start = point_from_lsp(range.start);
1412    let mut end = point_from_lsp(range.end);
1413    if start > end {
1414        mem::swap(&mut start, &mut end);
1415    }
1416    start..end
1417}