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