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