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