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}
316
317struct OutlineConfig {
318 query: Query,
319 item_capture_ix: u32,
320 name_capture_ix: u32,
321 context_capture_ix: Option<u32>,
322}
323
324struct InjectionConfig {
325 query: Query,
326 content_capture_ix: u32,
327 language_capture_ix: Option<u32>,
328 languages_by_pattern_ix: Vec<Option<Box<str>>>,
329}
330
331struct BracketConfig {
332 query: Query,
333 open_capture_ix: u32,
334 close_capture_ix: u32,
335}
336
337#[derive(Clone)]
338pub enum LanguageServerBinaryStatus {
339 CheckingForUpdate,
340 Downloading,
341 Downloaded,
342 Cached,
343 Failed { error: String },
344}
345
346pub struct LanguageRegistry {
347 languages: RwLock<Vec<Arc<Language>>>,
348 language_server_download_dir: Option<Arc<Path>>,
349 lsp_binary_statuses_tx: async_broadcast::Sender<(Arc<Language>, LanguageServerBinaryStatus)>,
350 lsp_binary_statuses_rx: async_broadcast::Receiver<(Arc<Language>, LanguageServerBinaryStatus)>,
351 login_shell_env_loaded: Shared<Task<()>>,
352 #[allow(clippy::type_complexity)]
353 lsp_binary_paths: Mutex<
354 HashMap<
355 LanguageServerName,
356 Shared<BoxFuture<'static, Result<PathBuf, Arc<anyhow::Error>>>>,
357 >,
358 >,
359 subscription: RwLock<(watch::Sender<()>, watch::Receiver<()>)>,
360 theme: RwLock<Option<Arc<Theme>>>,
361}
362
363impl LanguageRegistry {
364 pub fn new(login_shell_env_loaded: Task<()>) -> Self {
365 let (lsp_binary_statuses_tx, lsp_binary_statuses_rx) = async_broadcast::broadcast(16);
366 Self {
367 language_server_download_dir: None,
368 languages: Default::default(),
369 lsp_binary_statuses_tx,
370 lsp_binary_statuses_rx,
371 login_shell_env_loaded: login_shell_env_loaded.shared(),
372 lsp_binary_paths: Default::default(),
373 subscription: RwLock::new(watch::channel()),
374 theme: Default::default(),
375 }
376 }
377
378 #[cfg(any(test, feature = "test-support"))]
379 pub fn test() -> Self {
380 Self::new(Task::ready(()))
381 }
382
383 pub fn add(&self, language: Arc<Language>) {
384 if let Some(theme) = self.theme.read().clone() {
385 language.set_theme(&theme.editor.syntax);
386 }
387 self.languages.write().push(language);
388 *self.subscription.write().0.borrow_mut() = ();
389 }
390
391 pub fn subscribe(&self) -> watch::Receiver<()> {
392 self.subscription.read().1.clone()
393 }
394
395 pub fn set_theme(&self, theme: Arc<Theme>) {
396 *self.theme.write() = Some(theme.clone());
397 for language in self.languages.read().iter() {
398 language.set_theme(&theme.editor.syntax);
399 }
400 }
401
402 pub fn set_language_server_download_dir(&mut self, path: impl Into<Arc<Path>>) {
403 self.language_server_download_dir = Some(path.into());
404 }
405
406 pub fn get_language(&self, name: &str) -> Option<Arc<Language>> {
407 self.languages
408 .read()
409 .iter()
410 .find(|language| language.name().to_lowercase() == name.to_lowercase())
411 .cloned()
412 }
413
414 pub fn to_vec(&self) -> Vec<Arc<Language>> {
415 self.languages.read().iter().cloned().collect()
416 }
417
418 pub fn language_names(&self) -> Vec<String> {
419 self.languages
420 .read()
421 .iter()
422 .map(|language| language.name().to_string())
423 .collect()
424 }
425
426 pub fn select_language(&self, path: impl AsRef<Path>) -> Option<Arc<Language>> {
427 let path = path.as_ref();
428 let filename = path.file_name().and_then(|name| name.to_str());
429 let extension = path.extension().and_then(|name| name.to_str());
430 let path_suffixes = [extension, filename];
431 self.languages
432 .read()
433 .iter()
434 .find(|language| {
435 language
436 .config
437 .path_suffixes
438 .iter()
439 .any(|suffix| path_suffixes.contains(&Some(suffix.as_str())))
440 })
441 .cloned()
442 }
443
444 pub fn start_language_server(
445 self: &Arc<Self>,
446 server_id: usize,
447 language: Arc<Language>,
448 root_path: Arc<Path>,
449 http_client: Arc<dyn HttpClient>,
450 cx: &mut MutableAppContext,
451 ) -> Option<Task<Result<lsp::LanguageServer>>> {
452 #[cfg(any(test, feature = "test-support"))]
453 if language.fake_adapter.is_some() {
454 let language = language;
455 return Some(cx.spawn(|cx| async move {
456 let (servers_tx, fake_adapter) = language.fake_adapter.as_ref().unwrap();
457 let (server, mut fake_server) = lsp::LanguageServer::fake(
458 fake_adapter.name.to_string(),
459 fake_adapter.capabilities.clone(),
460 cx.clone(),
461 );
462
463 if let Some(initializer) = &fake_adapter.initializer {
464 initializer(&mut fake_server);
465 }
466
467 let servers_tx = servers_tx.clone();
468 cx.background()
469 .spawn(async move {
470 if fake_server
471 .try_receive_notification::<lsp::notification::Initialized>()
472 .await
473 .is_some()
474 {
475 servers_tx.unbounded_send(fake_server).ok();
476 }
477 })
478 .detach();
479 Ok(server)
480 }));
481 }
482
483 let download_dir = self
484 .language_server_download_dir
485 .clone()
486 .ok_or_else(|| anyhow!("language server download directory has not been assigned"))
487 .log_err()?;
488
489 let this = self.clone();
490 let adapter = language.adapter.clone()?;
491 let lsp_binary_statuses = self.lsp_binary_statuses_tx.clone();
492 let login_shell_env_loaded = self.login_shell_env_loaded.clone();
493 Some(cx.spawn(|cx| async move {
494 login_shell_env_loaded.await;
495 let server_binary_path = this
496 .lsp_binary_paths
497 .lock()
498 .entry(adapter.name.clone())
499 .or_insert_with(|| {
500 get_server_binary_path(
501 adapter.clone(),
502 language.clone(),
503 http_client,
504 download_dir,
505 lsp_binary_statuses,
506 )
507 .map_err(Arc::new)
508 .boxed()
509 .shared()
510 })
511 .clone()
512 .map_err(|e| anyhow!(e));
513
514 let server_binary_path = server_binary_path.await?;
515 let server_args = &adapter.server_args;
516 let server = lsp::LanguageServer::new(
517 server_id,
518 &server_binary_path,
519 server_args,
520 &root_path,
521 cx,
522 )?;
523 Ok(server)
524 }))
525 }
526
527 pub fn language_server_binary_statuses(
528 &self,
529 ) -> async_broadcast::Receiver<(Arc<Language>, LanguageServerBinaryStatus)> {
530 self.lsp_binary_statuses_rx.clone()
531 }
532}
533
534#[cfg(any(test, feature = "test-support"))]
535impl Default for LanguageRegistry {
536 fn default() -> Self {
537 Self::test()
538 }
539}
540
541async fn get_server_binary_path(
542 adapter: Arc<CachedLspAdapter>,
543 language: Arc<Language>,
544 http_client: Arc<dyn HttpClient>,
545 download_dir: Arc<Path>,
546 statuses: async_broadcast::Sender<(Arc<Language>, LanguageServerBinaryStatus)>,
547) -> Result<PathBuf> {
548 let container_dir = download_dir.join(adapter.name.0.as_ref());
549 if !container_dir.exists() {
550 smol::fs::create_dir_all(&container_dir)
551 .await
552 .context("failed to create container directory")?;
553 }
554
555 let path = fetch_latest_server_binary_path(
556 adapter.clone(),
557 language.clone(),
558 http_client,
559 &container_dir,
560 statuses.clone(),
561 )
562 .await;
563 if let Err(error) = path.as_ref() {
564 if let Some(cached_path) = adapter.cached_server_binary(container_dir).await {
565 statuses
566 .broadcast((language.clone(), LanguageServerBinaryStatus::Cached))
567 .await?;
568 return Ok(cached_path);
569 } else {
570 statuses
571 .broadcast((
572 language.clone(),
573 LanguageServerBinaryStatus::Failed {
574 error: format!("{:?}", error),
575 },
576 ))
577 .await?;
578 }
579 }
580 path
581}
582
583async fn fetch_latest_server_binary_path(
584 adapter: Arc<CachedLspAdapter>,
585 language: Arc<Language>,
586 http_client: Arc<dyn HttpClient>,
587 container_dir: &Path,
588 lsp_binary_statuses_tx: async_broadcast::Sender<(Arc<Language>, LanguageServerBinaryStatus)>,
589) -> Result<PathBuf> {
590 let container_dir: Arc<Path> = container_dir.into();
591 lsp_binary_statuses_tx
592 .broadcast((
593 language.clone(),
594 LanguageServerBinaryStatus::CheckingForUpdate,
595 ))
596 .await?;
597 let version_info = adapter
598 .fetch_latest_server_version(http_client.clone())
599 .await?;
600 lsp_binary_statuses_tx
601 .broadcast((language.clone(), LanguageServerBinaryStatus::Downloading))
602 .await?;
603 let path = adapter
604 .fetch_server_binary(version_info, http_client, container_dir.to_path_buf())
605 .await?;
606 lsp_binary_statuses_tx
607 .broadcast((language.clone(), LanguageServerBinaryStatus::Downloaded))
608 .await?;
609 Ok(path)
610}
611
612impl Language {
613 pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
614 Self {
615 config,
616 grammar: ts_language.map(|ts_language| {
617 Arc::new(Grammar {
618 id: NEXT_GRAMMAR_ID.fetch_add(1, SeqCst),
619 highlights_query: None,
620 brackets_config: None,
621 outline_config: None,
622 indents_config: None,
623 injection_config: None,
624 ts_language,
625 highlight_map: Default::default(),
626 })
627 }),
628 adapter: None,
629
630 #[cfg(any(test, feature = "test-support"))]
631 fake_adapter: None,
632 }
633 }
634
635 pub fn lsp_adapter(&self) -> Option<Arc<CachedLspAdapter>> {
636 self.adapter.clone()
637 }
638
639 pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
640 let grammar = self.grammar_mut();
641 grammar.highlights_query = Some(Query::new(grammar.ts_language, source)?);
642 Ok(self)
643 }
644
645 pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
646 let grammar = self.grammar_mut();
647 let query = Query::new(grammar.ts_language, source)?;
648 let mut open_capture_ix = None;
649 let mut close_capture_ix = None;
650 get_capture_indices(
651 &query,
652 &mut [
653 ("open", &mut open_capture_ix),
654 ("close", &mut close_capture_ix),
655 ],
656 );
657 if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
658 grammar.brackets_config = Some(BracketConfig {
659 query,
660 open_capture_ix,
661 close_capture_ix,
662 });
663 }
664 Ok(self)
665 }
666
667 pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
668 let grammar = self.grammar_mut();
669 let query = Query::new(grammar.ts_language, source)?;
670 let mut indent_capture_ix = None;
671 let mut start_capture_ix = None;
672 let mut end_capture_ix = None;
673 get_capture_indices(
674 &query,
675 &mut [
676 ("indent", &mut indent_capture_ix),
677 ("start", &mut start_capture_ix),
678 ("end", &mut end_capture_ix),
679 ],
680 );
681 if let Some(indent_capture_ix) = indent_capture_ix {
682 grammar.indents_config = Some(IndentConfig {
683 query,
684 indent_capture_ix,
685 start_capture_ix,
686 end_capture_ix,
687 });
688 }
689 Ok(self)
690 }
691
692 pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
693 let grammar = self.grammar_mut();
694 let query = Query::new(grammar.ts_language, source)?;
695 let mut item_capture_ix = None;
696 let mut name_capture_ix = None;
697 let mut context_capture_ix = None;
698 get_capture_indices(
699 &query,
700 &mut [
701 ("item", &mut item_capture_ix),
702 ("name", &mut name_capture_ix),
703 ("context", &mut context_capture_ix),
704 ],
705 );
706 if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
707 grammar.outline_config = Some(OutlineConfig {
708 query,
709 item_capture_ix,
710 name_capture_ix,
711 context_capture_ix,
712 });
713 }
714 Ok(self)
715 }
716
717 pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
718 let grammar = self.grammar_mut();
719 let query = Query::new(grammar.ts_language, source)?;
720 let mut language_capture_ix = None;
721 let mut content_capture_ix = None;
722 get_capture_indices(
723 &query,
724 &mut [
725 ("language", &mut language_capture_ix),
726 ("content", &mut content_capture_ix),
727 ],
728 );
729 let languages_by_pattern_ix = (0..query.pattern_count())
730 .map(|ix| {
731 query.property_settings(ix).iter().find_map(|setting| {
732 if setting.key.as_ref() == "language" {
733 return setting.value.clone();
734 } else {
735 None
736 }
737 })
738 })
739 .collect();
740 if let Some(content_capture_ix) = content_capture_ix {
741 grammar.injection_config = Some(InjectionConfig {
742 query,
743 language_capture_ix,
744 content_capture_ix,
745 languages_by_pattern_ix,
746 });
747 }
748 Ok(self)
749 }
750
751 fn grammar_mut(&mut self) -> &mut Grammar {
752 Arc::get_mut(self.grammar.as_mut().unwrap()).unwrap()
753 }
754
755 pub fn with_lsp_adapter(mut self, lsp_adapter: Arc<CachedLspAdapter>) -> Self {
756 self.adapter = Some(lsp_adapter);
757 self
758 }
759
760 #[cfg(any(test, feature = "test-support"))]
761 pub async fn set_fake_lsp_adapter(
762 &mut self,
763 fake_lsp_adapter: Arc<FakeLspAdapter>,
764 ) -> mpsc::UnboundedReceiver<lsp::FakeLanguageServer> {
765 let (servers_tx, servers_rx) = mpsc::unbounded();
766 self.fake_adapter = Some((servers_tx, fake_lsp_adapter.clone()));
767 let adapter = CachedLspAdapter::new(fake_lsp_adapter).await;
768 self.adapter = Some(adapter);
769 servers_rx
770 }
771
772 pub fn name(&self) -> Arc<str> {
773 self.config.name.clone()
774 }
775
776 pub fn line_comment_prefix(&self) -> Option<&Arc<str>> {
777 self.config.line_comment.as_ref()
778 }
779
780 pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
781 self.config
782 .block_comment
783 .as_ref()
784 .map(|(start, end)| (start, end))
785 }
786
787 pub async fn disk_based_diagnostic_sources(&self) -> &[String] {
788 match self.adapter.as_ref() {
789 Some(adapter) => &adapter.disk_based_diagnostic_sources,
790 None => &[],
791 }
792 }
793
794 pub async fn disk_based_diagnostics_progress_token(&self) -> Option<&str> {
795 if let Some(adapter) = self.adapter.as_ref() {
796 adapter.disk_based_diagnostics_progress_token.as_deref()
797 } else {
798 None
799 }
800 }
801
802 pub async fn process_diagnostics(&self, diagnostics: &mut lsp::PublishDiagnosticsParams) {
803 if let Some(processor) = self.adapter.as_ref() {
804 processor.process_diagnostics(diagnostics).await;
805 }
806 }
807
808 pub async fn label_for_completion(
809 self: &Arc<Self>,
810 completion: &lsp::CompletionItem,
811 ) -> Option<CodeLabel> {
812 self.adapter
813 .as_ref()?
814 .label_for_completion(completion, self)
815 .await
816 }
817
818 pub async fn label_for_symbol(
819 self: &Arc<Self>,
820 name: &str,
821 kind: lsp::SymbolKind,
822 ) -> Option<CodeLabel> {
823 self.adapter
824 .as_ref()?
825 .label_for_symbol(name, kind, self)
826 .await
827 }
828
829 pub fn highlight_text<'a>(
830 self: &'a Arc<Self>,
831 text: &'a Rope,
832 range: Range<usize>,
833 ) -> Vec<(Range<usize>, HighlightId)> {
834 let mut result = Vec::new();
835 if let Some(grammar) = &self.grammar {
836 let tree = grammar.parse_text(text, None);
837 let captures =
838 SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
839 grammar.highlights_query.as_ref()
840 });
841 let highlight_maps = vec![grammar.highlight_map()];
842 let mut offset = 0;
843 for chunk in BufferChunks::new(text, range, Some((captures, highlight_maps)), vec![]) {
844 let end_offset = offset + chunk.text.len();
845 if let Some(highlight_id) = chunk.syntax_highlight_id {
846 if !highlight_id.is_default() {
847 result.push((offset..end_offset, highlight_id));
848 }
849 }
850 offset = end_offset;
851 }
852 }
853 result
854 }
855
856 pub fn brackets(&self) -> &[BracketPair] {
857 &self.config.brackets
858 }
859
860 pub fn path_suffixes(&self) -> &[String] {
861 &self.config.path_suffixes
862 }
863
864 pub fn should_autoclose_before(&self, c: char) -> bool {
865 c.is_whitespace() || self.config.autoclose_before.contains(c)
866 }
867
868 pub fn set_theme(&self, theme: &SyntaxTheme) {
869 if let Some(grammar) = self.grammar.as_ref() {
870 if let Some(highlights_query) = &grammar.highlights_query {
871 *grammar.highlight_map.lock() =
872 HighlightMap::new(highlights_query.capture_names(), theme);
873 }
874 }
875 }
876
877 pub fn grammar(&self) -> Option<&Arc<Grammar>> {
878 self.grammar.as_ref()
879 }
880}
881
882impl Debug for Language {
883 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
884 f.debug_struct("Language")
885 .field("name", &self.config.name)
886 .finish()
887 }
888}
889
890impl Grammar {
891 pub fn id(&self) -> usize {
892 self.id
893 }
894
895 fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
896 PARSER.with(|parser| {
897 let mut parser = parser.borrow_mut();
898 parser
899 .set_language(self.ts_language)
900 .expect("incompatible grammar");
901 let mut chunks = text.chunks_in_range(0..text.len());
902 parser
903 .parse_with(
904 &mut move |offset, _| {
905 chunks.seek(offset);
906 chunks.next().unwrap_or("").as_bytes()
907 },
908 old_tree.as_ref(),
909 )
910 .unwrap()
911 })
912 }
913
914 pub fn highlight_map(&self) -> HighlightMap {
915 self.highlight_map.lock().clone()
916 }
917
918 pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
919 let capture_id = self
920 .highlights_query
921 .as_ref()?
922 .capture_index_for_name(name)?;
923 Some(self.highlight_map.lock().get(capture_id))
924 }
925}
926
927impl CodeLabel {
928 pub fn plain(text: String, filter_text: Option<&str>) -> Self {
929 let mut result = Self {
930 runs: Vec::new(),
931 filter_range: 0..text.len(),
932 text,
933 };
934 if let Some(filter_text) = filter_text {
935 if let Some(ix) = result.text.find(filter_text) {
936 result.filter_range = ix..ix + filter_text.len();
937 }
938 }
939 result
940 }
941}
942
943#[cfg(any(test, feature = "test-support"))]
944impl Default for FakeLspAdapter {
945 fn default() -> Self {
946 Self {
947 name: "the-fake-language-server",
948 capabilities: lsp::LanguageServer::full_capabilities(),
949 initializer: None,
950 disk_based_diagnostics_progress_token: None,
951 disk_based_diagnostics_sources: Vec::new(),
952 }
953 }
954}
955
956#[cfg(any(test, feature = "test-support"))]
957#[async_trait]
958impl LspAdapter for Arc<FakeLspAdapter> {
959 async fn name(&self) -> LanguageServerName {
960 LanguageServerName(self.name.into())
961 }
962
963 async fn fetch_latest_server_version(
964 &self,
965 _: Arc<dyn HttpClient>,
966 ) -> Result<Box<dyn 'static + Send + Any>> {
967 unreachable!();
968 }
969
970 async fn fetch_server_binary(
971 &self,
972 _: Box<dyn 'static + Send + Any>,
973 _: Arc<dyn HttpClient>,
974 _: PathBuf,
975 ) -> Result<PathBuf> {
976 unreachable!();
977 }
978
979 async fn cached_server_binary(&self, _: PathBuf) -> Option<PathBuf> {
980 unreachable!();
981 }
982
983 async fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
984
985 async fn disk_based_diagnostic_sources(&self) -> Vec<String> {
986 self.disk_based_diagnostics_sources.clone()
987 }
988
989 async fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
990 self.disk_based_diagnostics_progress_token.clone()
991 }
992}
993
994fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
995 for (ix, name) in query.capture_names().iter().enumerate() {
996 for (capture_name, index) in captures.iter_mut() {
997 if capture_name == name {
998 **index = Some(ix as u32);
999 break;
1000 }
1001 }
1002 }
1003}
1004
1005pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
1006 lsp::Position::new(point.row, point.column)
1007}
1008
1009pub fn point_from_lsp(point: lsp::Position) -> PointUtf16 {
1010 PointUtf16::new(point.line, point.character)
1011}
1012
1013pub fn range_to_lsp(range: Range<PointUtf16>) -> lsp::Range {
1014 lsp::Range {
1015 start: point_to_lsp(range.start),
1016 end: point_to_lsp(range.end),
1017 }
1018}
1019
1020pub fn range_from_lsp(range: lsp::Range) -> Range<PointUtf16> {
1021 let mut start = point_from_lsp(range.start);
1022 let mut end = point_from_lsp(range.end);
1023 if start > end {
1024 mem::swap(&mut start, &mut end);
1025 }
1026 start..end
1027}