language.rs

  1mod buffer;
  2mod diagnostic_set;
  3mod highlight_map;
  4mod outline;
  5pub mod proto;
  6#[cfg(test)]
  7mod tests;
  8
  9use anyhow::{anyhow, Context, Result};
 10use client::http::HttpClient;
 11use collections::HashMap;
 12use futures::{
 13    future::{BoxFuture, Shared},
 14    FutureExt, TryFutureExt,
 15};
 16use gpui::{MutableAppContext, Task};
 17use highlight_map::HighlightMap;
 18use lazy_static::lazy_static;
 19use parking_lot::{Mutex, RwLock};
 20use regex::Regex;
 21use serde::{de, Deserialize, Deserializer};
 22use serde_json::Value;
 23use std::{
 24    any::Any,
 25    cell::RefCell,
 26    mem,
 27    ops::Range,
 28    path::{Path, PathBuf},
 29    str,
 30    sync::Arc,
 31};
 32use theme::SyntaxTheme;
 33use tree_sitter::{self, Query};
 34use util::ResultExt;
 35
 36#[cfg(any(test, feature = "test-support"))]
 37use futures::channel::mpsc;
 38
 39pub use buffer::Operation;
 40pub use buffer::*;
 41pub use diagnostic_set::DiagnosticEntry;
 42pub use outline::{Outline, OutlineItem};
 43pub use tree_sitter::{Parser, Tree};
 44
 45thread_local! {
 46    static PARSER: RefCell<Parser>  = RefCell::new(Parser::new());
 47}
 48
 49lazy_static! {
 50    pub static ref PLAIN_TEXT: Arc<Language> = Arc::new(Language::new(
 51        LanguageConfig {
 52            name: "Plain Text".into(),
 53            ..Default::default()
 54        },
 55        None,
 56    ));
 57}
 58
 59pub trait ToLspPosition {
 60    fn to_lsp_position(self) -> lsp::Position;
 61}
 62
 63#[derive(Clone, Debug, PartialEq, Eq, Hash)]
 64pub struct LanguageServerName(pub Arc<str>);
 65
 66use async_trait::async_trait;
 67
 68// pub struct LspAdapter {
 69//     name: LanguageServerName,
 70//     adapter: Arc<dyn LspAdapter>,
 71// }
 72
 73// impl LspAdapter {
 74//     async fn new(adapter: Arc<dyn LspAdapter>) -> Self {
 75//         let name = adapter.name().await;
 76
 77//         LspAdapter { name, adapter }
 78//     }
 79
 80//     fn name(&self) -> LanguageServerName {
 81//         self.name
 82//     }
 83// }
 84
 85#[async_trait]
 86pub trait LspAdapter: 'static + Send + Sync {
 87    async fn name(&self) -> LanguageServerName;
 88    async fn fetch_latest_server_version(
 89        &self,
 90        http: Arc<dyn HttpClient>,
 91    ) -> Result<Box<dyn 'static + Send + Any>>;
 92    async fn fetch_server_binary(
 93        &self,
 94        version: Box<dyn 'static + Send + Any>,
 95        http: Arc<dyn HttpClient>,
 96        container_dir: PathBuf,
 97    ) -> Result<PathBuf>;
 98    async fn cached_server_binary(&self, container_dir: PathBuf) -> Option<PathBuf>;
 99
100    async fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
101
102    async fn label_for_completion(
103        &self,
104        _: &lsp::CompletionItem,
105        _: &Language,
106    ) -> Option<CodeLabel> {
107        None
108    }
109
110    async fn label_for_symbol(
111        &self,
112        _: &str,
113        _: lsp::SymbolKind,
114        _: &Language,
115    ) -> Option<CodeLabel> {
116        None
117    }
118
119    async fn server_args(&self) -> Vec<String> {
120        Vec::new()
121    }
122
123    async fn initialization_options(&self) -> Option<Value> {
124        None
125    }
126
127    async fn disk_based_diagnostic_sources(&self) -> Vec<String> {
128        Default::default()
129    }
130
131    async fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
132        None
133    }
134
135    async fn id_for_language(&self, _name: &str) -> Option<String> {
136        None
137    }
138}
139
140#[derive(Clone, Debug, PartialEq, Eq)]
141pub struct CodeLabel {
142    pub text: String,
143    pub runs: Vec<(Range<usize>, HighlightId)>,
144    pub filter_range: Range<usize>,
145}
146
147#[derive(Deserialize)]
148pub struct LanguageConfig {
149    pub name: Arc<str>,
150    pub path_suffixes: Vec<String>,
151    pub brackets: Vec<BracketPair>,
152    #[serde(default = "auto_indent_using_last_non_empty_line_default")]
153    pub auto_indent_using_last_non_empty_line: bool,
154    #[serde(default, deserialize_with = "deserialize_regex")]
155    pub increase_indent_pattern: Option<Regex>,
156    #[serde(default, deserialize_with = "deserialize_regex")]
157    pub decrease_indent_pattern: Option<Regex>,
158    #[serde(default)]
159    pub autoclose_before: String,
160    pub line_comment: Option<String>,
161}
162
163impl Default for LanguageConfig {
164    fn default() -> Self {
165        Self {
166            name: "".into(),
167            path_suffixes: Default::default(),
168            brackets: Default::default(),
169            auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
170            increase_indent_pattern: Default::default(),
171            decrease_indent_pattern: Default::default(),
172            autoclose_before: Default::default(),
173            line_comment: Default::default(),
174        }
175    }
176}
177
178fn auto_indent_using_last_non_empty_line_default() -> bool {
179    true
180}
181
182fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
183    let source = Option::<String>::deserialize(d)?;
184    if let Some(source) = source {
185        Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
186    } else {
187        Ok(None)
188    }
189}
190
191#[cfg(any(test, feature = "test-support"))]
192pub struct FakeLspAdapter {
193    pub name: &'static str,
194    pub capabilities: lsp::ServerCapabilities,
195    pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
196    pub disk_based_diagnostics_progress_token: Option<String>,
197    pub disk_based_diagnostics_sources: Vec<String>,
198}
199
200#[derive(Clone, Debug, Deserialize)]
201pub struct BracketPair {
202    pub start: String,
203    pub end: String,
204    pub close: bool,
205    pub newline: bool,
206}
207
208pub struct Language {
209    pub(crate) config: LanguageConfig,
210    pub(crate) grammar: Option<Arc<Grammar>>,
211    pub(crate) adapter: Option<Arc<dyn LspAdapter>>,
212
213    #[cfg(any(test, feature = "test-support"))]
214    fake_adapter: Option<(
215        mpsc::UnboundedSender<lsp::FakeLanguageServer>,
216        Arc<FakeLspAdapter>,
217    )>,
218}
219
220pub struct Grammar {
221    pub(crate) ts_language: tree_sitter::Language,
222    pub(crate) highlights_query: Option<Query>,
223    pub(crate) brackets_query: Option<Query>,
224    pub(crate) indents_query: Option<Query>,
225    pub(crate) outline_query: Option<Query>,
226    pub(crate) highlight_map: Mutex<HighlightMap>,
227}
228
229#[derive(Clone)]
230pub enum LanguageServerBinaryStatus {
231    CheckingForUpdate,
232    Downloading,
233    Downloaded,
234    Cached,
235    Failed { error: String },
236}
237
238pub struct LanguageRegistry {
239    languages: RwLock<Vec<Arc<Language>>>,
240    language_server_download_dir: Option<Arc<Path>>,
241    lsp_binary_statuses_tx: async_broadcast::Sender<(Arc<Language>, LanguageServerBinaryStatus)>,
242    lsp_binary_statuses_rx: async_broadcast::Receiver<(Arc<Language>, LanguageServerBinaryStatus)>,
243    login_shell_env_loaded: Shared<Task<()>>,
244    lsp_binary_paths: Mutex<
245        HashMap<
246            LanguageServerName,
247            Shared<BoxFuture<'static, Result<PathBuf, Arc<anyhow::Error>>>>,
248        >,
249    >,
250}
251
252impl LanguageRegistry {
253    pub fn new(login_shell_env_loaded: Task<()>) -> Self {
254        let (lsp_binary_statuses_tx, lsp_binary_statuses_rx) = async_broadcast::broadcast(16);
255        Self {
256            language_server_download_dir: None,
257            languages: Default::default(),
258            lsp_binary_statuses_tx,
259            lsp_binary_statuses_rx,
260            login_shell_env_loaded: login_shell_env_loaded.shared(),
261            lsp_binary_paths: Default::default(),
262        }
263    }
264
265    #[cfg(any(test, feature = "test-support"))]
266    pub fn test() -> Self {
267        Self::new(Task::ready(()))
268    }
269
270    pub fn add(&self, language: Arc<Language>) {
271        self.languages.write().push(language.clone());
272    }
273
274    pub fn set_theme(&self, theme: &SyntaxTheme) {
275        for language in self.languages.read().iter() {
276            language.set_theme(theme);
277        }
278    }
279
280    pub fn set_language_server_download_dir(&mut self, path: impl Into<Arc<Path>>) {
281        self.language_server_download_dir = Some(path.into());
282    }
283
284    pub fn get_language(&self, name: &str) -> Option<Arc<Language>> {
285        self.languages
286            .read()
287            .iter()
288            .find(|language| language.name().to_lowercase() == name.to_lowercase())
289            .cloned()
290    }
291
292    pub fn to_vec(&self) -> Vec<Arc<Language>> {
293        self.languages.read().iter().cloned().collect()
294    }
295
296    pub fn language_names(&self) -> Vec<String> {
297        self.languages
298            .read()
299            .iter()
300            .map(|language| language.name().to_string())
301            .collect()
302    }
303
304    pub fn select_language(&self, path: impl AsRef<Path>) -> Option<Arc<Language>> {
305        let path = path.as_ref();
306        let filename = path.file_name().and_then(|name| name.to_str());
307        let extension = path.extension().and_then(|name| name.to_str());
308        let path_suffixes = [extension, filename];
309        self.languages
310            .read()
311            .iter()
312            .find(|language| {
313                language
314                    .config
315                    .path_suffixes
316                    .iter()
317                    .any(|suffix| dbg!(path_suffixes.contains(&Some(dbg!(suffix.as_str())))))
318            })
319            .cloned()
320    }
321
322    pub fn start_language_server(
323        self: &Arc<Self>,
324        server_id: usize,
325        language: Arc<Language>,
326        root_path: Arc<Path>,
327        http_client: Arc<dyn HttpClient>,
328        cx: &mut MutableAppContext,
329    ) -> Option<Task<Result<lsp::LanguageServer>>> {
330        #[cfg(any(test, feature = "test-support"))]
331        if language.fake_adapter.is_some() {
332            let language = language.clone();
333            return Some(cx.spawn(|cx| async move {
334                let (servers_tx, fake_adapter) = language.fake_adapter.as_ref().unwrap();
335                let (server, mut fake_server) = lsp::LanguageServer::fake(
336                    fake_adapter.name.to_string(),
337                    fake_adapter.capabilities.clone(),
338                    cx.clone(),
339                );
340
341                if let Some(initializer) = &fake_adapter.initializer {
342                    initializer(&mut fake_server);
343                }
344
345                let servers_tx = servers_tx.clone();
346                cx.background()
347                    .spawn(async move {
348                        if fake_server
349                            .try_receive_notification::<lsp::notification::Initialized>()
350                            .await
351                            .is_some()
352                        {
353                            servers_tx.unbounded_send(fake_server).ok();
354                        }
355                    })
356                    .detach();
357                Ok(server)
358            }));
359        }
360
361        let download_dir = self
362            .language_server_download_dir
363            .clone()
364            .ok_or_else(|| anyhow!("language server download directory has not been assigned"))
365            .log_err()?;
366
367        let this = self.clone();
368        let adapter = language.adapter.clone()?;
369        let lsp_binary_statuses = self.lsp_binary_statuses_tx.clone();
370        let login_shell_env_loaded = self.login_shell_env_loaded.clone();
371        Some(cx.spawn(|cx| async move {
372            login_shell_env_loaded.await;
373            let server_binary_path = this
374                .lsp_binary_paths
375                .lock()
376                .entry(adapter.name().await)
377                .or_insert_with(|| {
378                    get_server_binary_path(
379                        adapter.clone(),
380                        language.clone(),
381                        http_client,
382                        download_dir,
383                        lsp_binary_statuses,
384                    )
385                    .map_err(Arc::new)
386                    .boxed()
387                    .shared()
388                })
389                .clone()
390                .map_err(|e| anyhow!(e));
391
392            let server_binary_path = server_binary_path.await?;
393            let server_args = adapter.server_args().await;
394            let server = lsp::LanguageServer::new(
395                server_id,
396                &server_binary_path,
397                &server_args,
398                &root_path,
399                cx,
400            )?;
401            Ok(server)
402        }))
403    }
404
405    pub fn language_server_binary_statuses(
406        &self,
407    ) -> async_broadcast::Receiver<(Arc<Language>, LanguageServerBinaryStatus)> {
408        self.lsp_binary_statuses_rx.clone()
409    }
410}
411
412async fn get_server_binary_path(
413    adapter: Arc<dyn LspAdapter>,
414    language: Arc<Language>,
415    http_client: Arc<dyn HttpClient>,
416    download_dir: Arc<Path>,
417    statuses: async_broadcast::Sender<(Arc<Language>, LanguageServerBinaryStatus)>,
418) -> Result<PathBuf> {
419    let container_dir = download_dir.join(adapter.name().await.0.as_ref());
420    if !container_dir.exists() {
421        smol::fs::create_dir_all(&container_dir)
422            .await
423            .context("failed to create container directory")?;
424    }
425
426    let path = fetch_latest_server_binary_path(
427        adapter.clone(),
428        language.clone(),
429        http_client,
430        &container_dir,
431        statuses.clone(),
432    )
433    .await;
434    if let Err(error) = path.as_ref() {
435        if let Some(cached_path) = adapter.cached_server_binary(container_dir).await {
436            statuses
437                .broadcast((language.clone(), LanguageServerBinaryStatus::Cached))
438                .await?;
439            return Ok(cached_path);
440        } else {
441            statuses
442                .broadcast((
443                    language.clone(),
444                    LanguageServerBinaryStatus::Failed {
445                        error: format!("{:?}", error),
446                    },
447                ))
448                .await?;
449        }
450    }
451    path
452}
453
454async fn fetch_latest_server_binary_path(
455    adapter: Arc<dyn LspAdapter>,
456    language: Arc<Language>,
457    http_client: Arc<dyn HttpClient>,
458    container_dir: &Path,
459    lsp_binary_statuses_tx: async_broadcast::Sender<(Arc<Language>, LanguageServerBinaryStatus)>,
460) -> Result<PathBuf> {
461    let container_dir: Arc<Path> = container_dir.into();
462    lsp_binary_statuses_tx
463        .broadcast((
464            language.clone(),
465            LanguageServerBinaryStatus::CheckingForUpdate,
466        ))
467        .await?;
468    let version_info = adapter
469        .fetch_latest_server_version(http_client.clone())
470        .await?;
471    lsp_binary_statuses_tx
472        .broadcast((language.clone(), LanguageServerBinaryStatus::Downloading))
473        .await?;
474    let path = adapter
475        .fetch_server_binary(version_info, http_client, container_dir.clone())
476        .await?;
477    lsp_binary_statuses_tx
478        .broadcast((language.clone(), LanguageServerBinaryStatus::Downloaded))
479        .await?;
480    Ok(path)
481}
482
483impl Language {
484    pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
485        Self {
486            config,
487            grammar: ts_language.map(|ts_language| {
488                Arc::new(Grammar {
489                    highlights_query: None,
490                    brackets_query: None,
491                    indents_query: None,
492                    outline_query: None,
493                    ts_language,
494                    highlight_map: Default::default(),
495                })
496            }),
497            adapter: None,
498
499            #[cfg(any(test, feature = "test-support"))]
500            fake_adapter: None,
501        }
502    }
503
504    pub fn lsp_adapter(&self) -> Option<Arc<dyn LspAdapter>> {
505        self.adapter.clone()
506    }
507
508    pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
509        let grammar = self.grammar_mut();
510        grammar.highlights_query = Some(Query::new(grammar.ts_language, source)?);
511        Ok(self)
512    }
513
514    pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
515        let grammar = self.grammar_mut();
516        grammar.brackets_query = Some(Query::new(grammar.ts_language, source)?);
517        Ok(self)
518    }
519
520    pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
521        let grammar = self.grammar_mut();
522        grammar.indents_query = Some(Query::new(grammar.ts_language, source)?);
523        Ok(self)
524    }
525
526    pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
527        let grammar = self.grammar_mut();
528        grammar.outline_query = Some(Query::new(grammar.ts_language, source)?);
529        Ok(self)
530    }
531
532    fn grammar_mut(&mut self) -> &mut Grammar {
533        Arc::get_mut(self.grammar.as_mut().unwrap()).unwrap()
534    }
535
536    pub fn with_lsp_adapter(mut self, lsp_adapter: Arc<dyn LspAdapter>) -> Self {
537        self.adapter = Some(lsp_adapter);
538        self
539    }
540
541    #[cfg(any(test, feature = "test-support"))]
542    pub fn set_fake_lsp_adapter(
543        &mut self,
544        fake_lsp_adapter: FakeLspAdapter,
545    ) -> mpsc::UnboundedReceiver<lsp::FakeLanguageServer> {
546        let (servers_tx, servers_rx) = mpsc::unbounded();
547        let adapter = Arc::new(fake_lsp_adapter);
548        self.fake_adapter = Some((servers_tx, adapter.clone()));
549        self.adapter = Some(adapter);
550        servers_rx
551    }
552
553    pub fn name(&self) -> Arc<str> {
554        self.config.name.clone()
555    }
556
557    pub fn line_comment_prefix(&self) -> Option<&str> {
558        self.config.line_comment.as_deref()
559    }
560
561    pub async fn disk_based_diagnostic_sources(&self) -> Vec<String> {
562        match self.adapter.as_ref() {
563            Some(adapter) => adapter.disk_based_diagnostic_sources().await,
564            None => Vec::new(),
565        }
566    }
567
568    pub async fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
569        if let Some(adapter) = self.adapter.as_ref() {
570            adapter.disk_based_diagnostics_progress_token().await
571        } else {
572            None
573        }
574    }
575
576    pub async fn process_diagnostics(&self, diagnostics: &mut lsp::PublishDiagnosticsParams) {
577        if let Some(processor) = self.adapter.as_ref() {
578            processor.process_diagnostics(diagnostics).await;
579        }
580    }
581
582    pub async fn label_for_completion(
583        &self,
584        completion: &lsp::CompletionItem,
585    ) -> Option<CodeLabel> {
586        self.adapter
587            .as_ref()?
588            .label_for_completion(completion, self)
589            .await
590    }
591
592    pub async fn label_for_symbol(&self, name: &str, kind: lsp::SymbolKind) -> Option<CodeLabel> {
593        self.adapter
594            .as_ref()?
595            .label_for_symbol(name, kind, self)
596            .await
597    }
598
599    pub fn highlight_text<'a>(
600        &'a self,
601        text: &'a Rope,
602        range: Range<usize>,
603    ) -> Vec<(Range<usize>, HighlightId)> {
604        let mut result = Vec::new();
605        if let Some(grammar) = &self.grammar {
606            let tree = grammar.parse_text(text, None);
607            let mut offset = 0;
608            for chunk in BufferChunks::new(text, range, Some(&tree), self.grammar.as_ref(), vec![])
609            {
610                let end_offset = offset + chunk.text.len();
611                if let Some(highlight_id) = chunk.syntax_highlight_id {
612                    if !highlight_id.is_default() {
613                        result.push((offset..end_offset, highlight_id));
614                    }
615                }
616                offset = end_offset;
617            }
618        }
619        result
620    }
621
622    pub fn brackets(&self) -> &[BracketPair] {
623        &self.config.brackets
624    }
625
626    pub fn path_suffixes(&self) -> &[String] {
627        &self.config.path_suffixes
628    }
629
630    pub fn should_autoclose_before(&self, c: char) -> bool {
631        c.is_whitespace() || self.config.autoclose_before.contains(c)
632    }
633
634    pub fn set_theme(&self, theme: &SyntaxTheme) {
635        if let Some(grammar) = self.grammar.as_ref() {
636            if let Some(highlights_query) = &grammar.highlights_query {
637                *grammar.highlight_map.lock() =
638                    HighlightMap::new(highlights_query.capture_names(), theme);
639            }
640        }
641    }
642
643    pub fn grammar(&self) -> Option<&Arc<Grammar>> {
644        self.grammar.as_ref()
645    }
646}
647
648impl Grammar {
649    fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
650        PARSER.with(|parser| {
651            let mut parser = parser.borrow_mut();
652            parser
653                .set_language(self.ts_language)
654                .expect("incompatible grammar");
655            let mut chunks = text.chunks_in_range(0..text.len());
656            parser
657                .parse_with(
658                    &mut move |offset, _| {
659                        chunks.seek(offset);
660                        chunks.next().unwrap_or("").as_bytes()
661                    },
662                    old_tree.as_ref(),
663                )
664                .unwrap()
665        })
666    }
667
668    pub fn highlight_map(&self) -> HighlightMap {
669        self.highlight_map.lock().clone()
670    }
671
672    pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
673        let capture_id = self
674            .highlights_query
675            .as_ref()?
676            .capture_index_for_name(name)?;
677        Some(self.highlight_map.lock().get(capture_id))
678    }
679}
680
681impl CodeLabel {
682    pub fn plain(text: String, filter_text: Option<&str>) -> Self {
683        let mut result = Self {
684            runs: Vec::new(),
685            filter_range: 0..text.len(),
686            text,
687        };
688        if let Some(filter_text) = filter_text {
689            if let Some(ix) = result.text.find(filter_text) {
690                result.filter_range = ix..ix + filter_text.len();
691            }
692        }
693        result
694    }
695}
696
697#[cfg(any(test, feature = "test-support"))]
698impl Default for FakeLspAdapter {
699    fn default() -> Self {
700        Self {
701            name: "the-fake-language-server",
702            capabilities: lsp::LanguageServer::full_capabilities(),
703            initializer: None,
704            disk_based_diagnostics_progress_token: None,
705            disk_based_diagnostics_sources: Vec::new(),
706        }
707    }
708}
709
710#[cfg(any(test, feature = "test-support"))]
711#[async_trait]
712impl LspAdapter for FakeLspAdapter {
713    async fn name(&self) -> LanguageServerName {
714        LanguageServerName(self.name.into())
715    }
716
717    async fn fetch_latest_server_version(
718        &self,
719        _: Arc<dyn HttpClient>,
720    ) -> Result<Box<dyn 'static + Send + Any>> {
721        unreachable!();
722    }
723
724    async fn fetch_server_binary(
725        &self,
726        _: Box<dyn 'static + Send + Any>,
727        _: Arc<dyn HttpClient>,
728        _: PathBuf,
729    ) -> Result<PathBuf> {
730        unreachable!();
731    }
732
733    async fn cached_server_binary(&self, _: PathBuf) -> Option<PathBuf> {
734        unreachable!();
735    }
736
737    async fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
738
739    async fn disk_based_diagnostic_sources(&self) -> Vec<String> {
740        self.disk_based_diagnostics_sources.clone()
741    }
742
743    async fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
744        self.disk_based_diagnostics_progress_token.clone()
745    }
746}
747
748pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
749    lsp::Position::new(point.row, point.column)
750}
751
752pub fn point_from_lsp(point: lsp::Position) -> PointUtf16 {
753    PointUtf16::new(point.line, point.character)
754}
755
756pub fn range_to_lsp(range: Range<PointUtf16>) -> lsp::Range {
757    lsp::Range {
758        start: point_to_lsp(range.start),
759        end: point_to_lsp(range.end),
760    }
761}
762
763pub fn range_from_lsp(range: lsp::Range) -> Range<PointUtf16> {
764    let mut start = point_from_lsp(range.start);
765    let mut end = point_from_lsp(range.end);
766    if start > end {
767        mem::swap(&mut start, &mut end);
768    }
769    start..end
770}