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