language.rs

  1mod buffer;
  2mod diagnostic_set;
  3mod highlight_map;
  4mod outline;
  5pub mod proto;
  6#[cfg(test)]
  7mod tests;
  8
  9use anyhow::{anyhow, Result};
 10use collections::HashSet;
 11use gpui::AppContext;
 12use highlight_map::HighlightMap;
 13use lazy_static::lazy_static;
 14use parking_lot::Mutex;
 15use postage::prelude::Stream;
 16use serde::Deserialize;
 17use std::{cell::RefCell, ops::Range, path::Path, str, sync::Arc};
 18use theme::SyntaxTheme;
 19use tree_sitter::{self, Query};
 20
 21#[cfg(any(test, feature = "test-support"))]
 22use futures::channel::mpsc;
 23
 24pub use buffer::Operation;
 25pub use buffer::*;
 26pub use diagnostic_set::DiagnosticEntry;
 27pub use outline::{Outline, OutlineItem};
 28pub use tree_sitter::{Parser, Tree};
 29
 30thread_local! {
 31    static PARSER: RefCell<Parser>  = RefCell::new(Parser::new());
 32}
 33
 34lazy_static! {
 35    pub static ref PLAIN_TEXT: Arc<Language> = Arc::new(Language::new(
 36        LanguageConfig {
 37            name: "Plain Text".to_string(),
 38            path_suffixes: Default::default(),
 39            brackets: Default::default(),
 40            line_comment: None,
 41            language_server: None,
 42        },
 43        None,
 44    ));
 45}
 46
 47pub trait ToLspPosition {
 48    fn to_lsp_position(self) -> lsp::Position;
 49}
 50
 51pub trait LspPostProcessor: 'static + Send + Sync {
 52    fn process_diagnostics(&self, diagnostics: &mut lsp::PublishDiagnosticsParams);
 53    fn label_for_completion(
 54        &self,
 55        _: &lsp::CompletionItem,
 56        _: &Language,
 57    ) -> Option<CompletionLabel> {
 58        None
 59    }
 60}
 61
 62#[derive(Clone, Debug, PartialEq, Eq)]
 63pub struct CompletionLabel {
 64    pub text: String,
 65    pub runs: Vec<(Range<usize>, HighlightId)>,
 66    pub filter_range: Range<usize>,
 67    pub left_aligned_len: usize,
 68}
 69
 70#[derive(Default, Deserialize)]
 71pub struct LanguageConfig {
 72    pub name: String,
 73    pub path_suffixes: Vec<String>,
 74    pub brackets: Vec<BracketPair>,
 75    pub line_comment: Option<String>,
 76    pub language_server: Option<LanguageServerConfig>,
 77}
 78
 79#[derive(Default, Deserialize)]
 80pub struct LanguageServerConfig {
 81    pub binary: String,
 82    pub disk_based_diagnostic_sources: HashSet<String>,
 83    pub disk_based_diagnostics_progress_token: Option<String>,
 84    #[cfg(any(test, feature = "test-support"))]
 85    #[serde(skip)]
 86    fake_config: Option<FakeLanguageServerConfig>,
 87}
 88
 89#[cfg(any(test, feature = "test-support"))]
 90struct FakeLanguageServerConfig {
 91    servers_tx: mpsc::UnboundedSender<lsp::FakeLanguageServer>,
 92    capabilities: lsp::ServerCapabilities,
 93}
 94
 95#[derive(Clone, Debug, Deserialize)]
 96pub struct BracketPair {
 97    pub start: String,
 98    pub end: String,
 99    pub close: bool,
100    pub newline: bool,
101}
102
103pub struct Language {
104    pub(crate) config: LanguageConfig,
105    pub(crate) grammar: Option<Arc<Grammar>>,
106    pub(crate) lsp_post_processor: Option<Box<dyn LspPostProcessor>>,
107}
108
109pub struct Grammar {
110    pub(crate) ts_language: tree_sitter::Language,
111    pub(crate) highlights_query: Query,
112    pub(crate) brackets_query: Query,
113    pub(crate) indents_query: Query,
114    pub(crate) outline_query: Query,
115    pub(crate) highlight_map: Mutex<HighlightMap>,
116}
117
118#[derive(Default)]
119pub struct LanguageRegistry {
120    languages: Vec<Arc<Language>>,
121}
122
123impl LanguageRegistry {
124    pub fn new() -> Self {
125        Self::default()
126    }
127
128    pub fn add(&mut self, language: Arc<Language>) {
129        self.languages.push(language);
130    }
131
132    pub fn set_theme(&self, theme: &SyntaxTheme) {
133        for language in &self.languages {
134            language.set_theme(theme);
135        }
136    }
137
138    pub fn get_language(&self, name: &str) -> Option<&Arc<Language>> {
139        self.languages
140            .iter()
141            .find(|language| language.name() == name)
142    }
143
144    pub fn select_language(&self, path: impl AsRef<Path>) -> Option<&Arc<Language>> {
145        let path = path.as_ref();
146        let filename = path.file_name().and_then(|name| name.to_str());
147        let extension = path.extension().and_then(|name| name.to_str());
148        let path_suffixes = [extension, filename];
149        self.languages.iter().find(|language| {
150            language
151                .config
152                .path_suffixes
153                .iter()
154                .any(|suffix| path_suffixes.contains(&Some(suffix.as_str())))
155        })
156    }
157}
158
159impl Language {
160    pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
161        Self {
162            config,
163            grammar: ts_language.map(|ts_language| {
164                Arc::new(Grammar {
165                    brackets_query: Query::new(ts_language, "").unwrap(),
166                    highlights_query: Query::new(ts_language, "").unwrap(),
167                    indents_query: Query::new(ts_language, "").unwrap(),
168                    outline_query: Query::new(ts_language, "").unwrap(),
169                    ts_language,
170                    highlight_map: Default::default(),
171                })
172            }),
173            lsp_post_processor: None,
174        }
175    }
176
177    pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
178        let grammar = self
179            .grammar
180            .as_mut()
181            .and_then(Arc::get_mut)
182            .ok_or_else(|| anyhow!("grammar does not exist or is already being used"))?;
183        grammar.highlights_query = Query::new(grammar.ts_language, source)?;
184        Ok(self)
185    }
186
187    pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
188        let grammar = self
189            .grammar
190            .as_mut()
191            .and_then(Arc::get_mut)
192            .ok_or_else(|| anyhow!("grammar does not exist or is already being used"))?;
193        grammar.brackets_query = Query::new(grammar.ts_language, source)?;
194        Ok(self)
195    }
196
197    pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
198        let grammar = self
199            .grammar
200            .as_mut()
201            .and_then(Arc::get_mut)
202            .ok_or_else(|| anyhow!("grammar does not exist or is already being used"))?;
203        grammar.indents_query = Query::new(grammar.ts_language, source)?;
204        Ok(self)
205    }
206
207    pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
208        let grammar = self
209            .grammar
210            .as_mut()
211            .and_then(Arc::get_mut)
212            .ok_or_else(|| anyhow!("grammar does not exist or is already being used"))?;
213        grammar.outline_query = Query::new(grammar.ts_language, source)?;
214        Ok(self)
215    }
216
217    pub fn with_lsp_post_processor(mut self, processor: impl LspPostProcessor) -> Self {
218        self.lsp_post_processor = Some(Box::new(processor));
219        self
220    }
221
222    pub fn name(&self) -> &str {
223        self.config.name.as_str()
224    }
225
226    pub fn line_comment_prefix(&self) -> Option<&str> {
227        self.config.line_comment.as_deref()
228    }
229
230    pub fn start_server(
231        &self,
232        root_path: &Path,
233        cx: &AppContext,
234    ) -> Result<Option<Arc<lsp::LanguageServer>>> {
235        if let Some(config) = &self.config.language_server {
236            #[cfg(any(test, feature = "test-support"))]
237            if let Some(fake_config) = &config.fake_config {
238                let (server, fake_server) = lsp::LanguageServer::fake_with_capabilities(
239                    fake_config.capabilities.clone(),
240                    cx.background().clone(),
241                );
242
243                let servers_tx = fake_config.servers_tx.clone();
244                let mut initialized = server.capabilities();
245                cx.background()
246                    .spawn(async move {
247                        while initialized.recv().await.is_none() {}
248                        servers_tx.unbounded_send(fake_server).ok();
249                    })
250                    .detach();
251
252                return Ok(Some(server.clone()));
253            }
254
255            const ZED_BUNDLE: Option<&'static str> = option_env!("ZED_BUNDLE");
256            let binary_path = if ZED_BUNDLE.map_or(Ok(false), |b| b.parse())? {
257                cx.platform()
258                    .path_for_resource(Some(&config.binary), None)?
259            } else {
260                Path::new(&config.binary).to_path_buf()
261            };
262            lsp::LanguageServer::new(&binary_path, root_path, cx.background().clone()).map(Some)
263        } else {
264            Ok(None)
265        }
266    }
267
268    pub fn disk_based_diagnostic_sources(&self) -> Option<&HashSet<String>> {
269        self.config
270            .language_server
271            .as_ref()
272            .map(|config| &config.disk_based_diagnostic_sources)
273    }
274
275    pub fn disk_based_diagnostics_progress_token(&self) -> Option<&String> {
276        self.config
277            .language_server
278            .as_ref()
279            .and_then(|config| config.disk_based_diagnostics_progress_token.as_ref())
280    }
281
282    pub fn process_diagnostics(&self, diagnostics: &mut lsp::PublishDiagnosticsParams) {
283        if let Some(processor) = self.lsp_post_processor.as_ref() {
284            processor.process_diagnostics(diagnostics);
285        }
286    }
287
288    pub fn label_for_completion(
289        &self,
290        completion: &lsp::CompletionItem,
291    ) -> Option<CompletionLabel> {
292        self.lsp_post_processor
293            .as_ref()?
294            .label_for_completion(completion, self)
295    }
296
297    pub fn highlight_text<'a>(
298        &'a self,
299        text: &'a Rope,
300        range: Range<usize>,
301    ) -> Vec<(Range<usize>, HighlightId)> {
302        let mut result = Vec::new();
303        if let Some(grammar) = &self.grammar {
304            let tree = grammar.parse_text(text, None);
305            let mut offset = 0;
306            for chunk in BufferChunks::new(text, range, Some(&tree), self.grammar.as_ref(), vec![])
307            {
308                let end_offset = offset + chunk.text.len();
309                if let Some(highlight_id) = chunk.highlight_id {
310                    result.push((offset..end_offset, highlight_id));
311                }
312                offset = end_offset;
313            }
314        }
315        result
316    }
317
318    pub fn brackets(&self) -> &[BracketPair] {
319        &self.config.brackets
320    }
321
322    pub fn set_theme(&self, theme: &SyntaxTheme) {
323        if let Some(grammar) = self.grammar.as_ref() {
324            *grammar.highlight_map.lock() =
325                HighlightMap::new(grammar.highlights_query.capture_names(), theme);
326        }
327    }
328
329    pub fn grammar(&self) -> Option<&Arc<Grammar>> {
330        self.grammar.as_ref()
331    }
332}
333
334impl Grammar {
335    fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
336        PARSER.with(|parser| {
337            let mut parser = parser.borrow_mut();
338            parser
339                .set_language(self.ts_language)
340                .expect("incompatible grammar");
341            let mut chunks = text.chunks_in_range(0..text.len());
342            parser
343                .parse_with(
344                    &mut move |offset, _| {
345                        chunks.seek(offset);
346                        chunks.next().unwrap_or("").as_bytes()
347                    },
348                    old_tree.as_ref(),
349                )
350                .unwrap()
351        })
352    }
353
354    pub fn highlight_map(&self) -> HighlightMap {
355        self.highlight_map.lock().clone()
356    }
357
358    pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
359        let capture_id = self.highlights_query.capture_index_for_name(name)?;
360        Some(self.highlight_map.lock().get(capture_id))
361    }
362}
363
364impl CompletionLabel {
365    pub fn plain(completion: &lsp::CompletionItem) -> Self {
366        let mut result = Self {
367            text: completion.label.clone(),
368            runs: Vec::new(),
369            left_aligned_len: completion.label.len(),
370            filter_range: 0..completion.label.len(),
371        };
372        if let Some(filter_text) = &completion.filter_text {
373            if let Some(ix) = completion.label.find(filter_text) {
374                result.filter_range = ix..ix + filter_text.len();
375            }
376        }
377        result
378    }
379}
380
381#[cfg(any(test, feature = "test-support"))]
382impl LanguageServerConfig {
383    pub fn fake() -> (Self, mpsc::UnboundedReceiver<lsp::FakeLanguageServer>) {
384        Self::fake_with_capabilities(Default::default())
385    }
386
387    pub fn fake_with_capabilities(
388        capabilities: lsp::ServerCapabilities,
389    ) -> (Self, mpsc::UnboundedReceiver<lsp::FakeLanguageServer>) {
390        let (servers_tx, servers_rx) = mpsc::unbounded();
391        (
392            Self {
393                fake_config: Some(FakeLanguageServerConfig {
394                    servers_tx,
395                    capabilities,
396                }),
397                disk_based_diagnostics_progress_token: Some("fakeServer/check".to_string()),
398                ..Default::default()
399            },
400            servers_rx,
401        )
402    }
403}
404
405impl ToLspPosition for PointUtf16 {
406    fn to_lsp_position(self) -> lsp::Position {
407        lsp::Position::new(self.row, self.column)
408    }
409}
410
411pub fn point_from_lsp(point: lsp::Position) -> PointUtf16 {
412    PointUtf16::new(point.line, point.character)
413}
414
415pub fn range_from_lsp(range: lsp::Range) -> Range<PointUtf16> {
416    let start = PointUtf16::new(range.start.line, range.start.character);
417    let end = PointUtf16::new(range.end.line, range.end.character);
418    start..end
419}