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