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