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 channel::oneshot,
17 future::{BoxFuture, Shared},
18 FutureExt, TryFutureExt as _,
19};
20use gpui::{executor::Background, MutableAppContext, Task};
21use highlight_map::HighlightMap;
22use lazy_static::lazy_static;
23use lsp::CodeActionKind;
24use parking_lot::{Mutex, RwLock};
25use postage::watch;
26use regex::Regex;
27use serde::{de, Deserialize, Deserializer};
28use serde_json::Value;
29use std::{
30 any::Any,
31 borrow::Cow,
32 cell::RefCell,
33 ffi::OsString,
34 fmt::Debug,
35 hash::Hash,
36 mem,
37 ops::Range,
38 path::{Path, PathBuf},
39 str,
40 sync::{
41 atomic::{AtomicUsize, Ordering::SeqCst},
42 Arc,
43 },
44};
45use syntax_map::SyntaxSnapshot;
46use theme::{SyntaxTheme, Theme};
47use tree_sitter::{self, Query};
48use unicase::UniCase;
49use util::{merge_json_value_into, post_inc, ResultExt, TryFutureExt as _, UnwrapFuture};
50
51#[cfg(any(test, feature = "test-support"))]
52use futures::channel::mpsc;
53
54pub use buffer::Operation;
55pub use buffer::*;
56pub use diagnostic_set::DiagnosticEntry;
57pub use outline::{Outline, OutlineItem};
58pub use tree_sitter::{Parser, Tree};
59
60thread_local! {
61 static PARSER: RefCell<Parser> = RefCell::new(Parser::new());
62}
63
64lazy_static! {
65 pub static ref NEXT_GRAMMAR_ID: AtomicUsize = Default::default();
66 pub static ref PLAIN_TEXT: Arc<Language> = Arc::new(Language::new(
67 LanguageConfig {
68 name: "Plain Text".into(),
69 ..Default::default()
70 },
71 None,
72 ));
73}
74
75pub trait ToLspPosition {
76 fn to_lsp_position(self) -> lsp::Position;
77}
78
79#[derive(Clone, Debug, PartialEq, Eq, Hash)]
80pub struct LanguageServerName(pub Arc<str>);
81
82#[derive(Debug, Clone, Deserialize)]
83pub struct LanguageServerBinary {
84 pub path: PathBuf,
85 pub arguments: Vec<OsString>,
86}
87
88/// Represents a Language Server, with certain cached sync properties.
89/// Uses [`LspAdapter`] under the hood, but calls all 'static' methods
90/// once at startup, and caches the results.
91pub struct CachedLspAdapter {
92 pub name: LanguageServerName,
93 pub initialization_options: Option<Value>,
94 pub disk_based_diagnostic_sources: Vec<String>,
95 pub disk_based_diagnostics_progress_token: Option<String>,
96 pub language_ids: HashMap<String, String>,
97 pub adapter: Arc<dyn LspAdapter>,
98}
99
100impl CachedLspAdapter {
101 pub async fn new(adapter: Arc<dyn LspAdapter>) -> Arc<Self> {
102 let name = adapter.name().await;
103 let initialization_options = adapter.initialization_options().await;
104 let disk_based_diagnostic_sources = adapter.disk_based_diagnostic_sources().await;
105 let disk_based_diagnostics_progress_token =
106 adapter.disk_based_diagnostics_progress_token().await;
107 let language_ids = adapter.language_ids().await;
108
109 Arc::new(CachedLspAdapter {
110 name,
111 initialization_options,
112 disk_based_diagnostic_sources,
113 disk_based_diagnostics_progress_token,
114 language_ids,
115 adapter,
116 })
117 }
118
119 pub async fn fetch_latest_server_version(
120 &self,
121 http: Arc<dyn HttpClient>,
122 ) -> Result<Box<dyn 'static + Send + Any>> {
123 self.adapter.fetch_latest_server_version(http).await
124 }
125
126 pub async fn fetch_server_binary(
127 &self,
128 version: Box<dyn 'static + Send + Any>,
129 http: Arc<dyn HttpClient>,
130 container_dir: PathBuf,
131 ) -> Result<LanguageServerBinary> {
132 self.adapter
133 .fetch_server_binary(version, http, container_dir)
134 .await
135 }
136
137 pub async fn cached_server_binary(
138 &self,
139 container_dir: PathBuf,
140 ) -> Option<LanguageServerBinary> {
141 self.adapter.cached_server_binary(container_dir).await
142 }
143
144 pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
145 self.adapter.code_action_kinds()
146 }
147
148 pub fn workspace_configuration(
149 &self,
150 cx: &mut MutableAppContext,
151 ) -> Option<BoxFuture<'static, Value>> {
152 self.adapter.workspace_configuration(cx)
153 }
154
155 pub async fn process_diagnostics(&self, params: &mut lsp::PublishDiagnosticsParams) {
156 self.adapter.process_diagnostics(params).await
157 }
158
159 pub async fn process_completion(&self, completion_item: &mut lsp::CompletionItem) {
160 self.adapter.process_completion(completion_item).await
161 }
162
163 pub async fn label_for_completion(
164 &self,
165 completion_item: &lsp::CompletionItem,
166 language: &Arc<Language>,
167 ) -> Option<CodeLabel> {
168 self.adapter
169 .label_for_completion(completion_item, language)
170 .await
171 }
172
173 pub async fn label_for_symbol(
174 &self,
175 name: &str,
176 kind: lsp::SymbolKind,
177 language: &Arc<Language>,
178 ) -> Option<CodeLabel> {
179 self.adapter.label_for_symbol(name, kind, language).await
180 }
181}
182
183#[async_trait]
184pub trait LspAdapter: 'static + Send + Sync {
185 async fn name(&self) -> LanguageServerName;
186
187 async fn fetch_latest_server_version(
188 &self,
189 http: Arc<dyn HttpClient>,
190 ) -> Result<Box<dyn 'static + Send + Any>>;
191
192 async fn fetch_server_binary(
193 &self,
194 version: Box<dyn 'static + Send + Any>,
195 http: Arc<dyn HttpClient>,
196 container_dir: PathBuf,
197 ) -> Result<LanguageServerBinary>;
198
199 async fn cached_server_binary(&self, container_dir: PathBuf) -> Option<LanguageServerBinary>;
200
201 async fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
202
203 async fn process_completion(&self, _: &mut lsp::CompletionItem) {}
204
205 async fn label_for_completion(
206 &self,
207 _: &lsp::CompletionItem,
208 _: &Arc<Language>,
209 ) -> Option<CodeLabel> {
210 None
211 }
212
213 async fn label_for_symbol(
214 &self,
215 _: &str,
216 _: lsp::SymbolKind,
217 _: &Arc<Language>,
218 ) -> Option<CodeLabel> {
219 None
220 }
221
222 async fn initialization_options(&self) -> Option<Value> {
223 None
224 }
225
226 fn workspace_configuration(
227 &self,
228 _: &mut MutableAppContext,
229 ) -> Option<BoxFuture<'static, Value>> {
230 None
231 }
232
233 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
234 Some(vec![
235 CodeActionKind::EMPTY,
236 CodeActionKind::QUICKFIX,
237 CodeActionKind::REFACTOR,
238 CodeActionKind::REFACTOR_EXTRACT,
239 CodeActionKind::SOURCE,
240 ])
241 }
242
243 async fn disk_based_diagnostic_sources(&self) -> Vec<String> {
244 Default::default()
245 }
246
247 async fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
248 None
249 }
250
251 async fn language_ids(&self) -> HashMap<String, String> {
252 Default::default()
253 }
254}
255
256#[derive(Clone, Debug, PartialEq, Eq)]
257pub struct CodeLabel {
258 pub text: String,
259 pub runs: Vec<(Range<usize>, HighlightId)>,
260 pub filter_range: Range<usize>,
261}
262
263#[derive(Clone, Deserialize)]
264pub struct LanguageConfig {
265 pub name: Arc<str>,
266 pub path_suffixes: Vec<String>,
267 pub brackets: BracketPairConfig,
268 #[serde(default = "auto_indent_using_last_non_empty_line_default")]
269 pub auto_indent_using_last_non_empty_line: bool,
270 #[serde(default, deserialize_with = "deserialize_regex")]
271 pub increase_indent_pattern: Option<Regex>,
272 #[serde(default, deserialize_with = "deserialize_regex")]
273 pub decrease_indent_pattern: Option<Regex>,
274 #[serde(default)]
275 pub autoclose_before: String,
276 #[serde(default)]
277 pub line_comment: Option<Arc<str>>,
278 #[serde(default)]
279 pub block_comment: Option<(Arc<str>, Arc<str>)>,
280 #[serde(default)]
281 pub overrides: HashMap<String, LanguageConfigOverride>,
282}
283
284#[derive(Debug, Default)]
285pub struct LanguageQueries {
286 pub highlights: Option<Cow<'static, str>>,
287 pub brackets: Option<Cow<'static, str>>,
288 pub indents: Option<Cow<'static, str>>,
289 pub outline: Option<Cow<'static, str>>,
290 pub injections: Option<Cow<'static, str>>,
291 pub overrides: Option<Cow<'static, str>>,
292}
293
294#[derive(Clone, Debug)]
295pub struct LanguageScope {
296 language: Arc<Language>,
297 override_id: Option<u32>,
298}
299
300#[derive(Clone, Deserialize, Default, Debug)]
301pub struct LanguageConfigOverride {
302 #[serde(default)]
303 pub line_comment: Override<Arc<str>>,
304 #[serde(default)]
305 pub block_comment: Override<(Arc<str>, Arc<str>)>,
306 #[serde(skip_deserializing)]
307 pub disabled_bracket_ixs: Vec<u16>,
308}
309
310#[derive(Clone, Deserialize, Debug)]
311#[serde(untagged)]
312pub enum Override<T> {
313 Remove { remove: bool },
314 Set(T),
315}
316
317impl<T> Default for Override<T> {
318 fn default() -> Self {
319 Override::Remove { remove: false }
320 }
321}
322
323impl<T> Override<T> {
324 fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
325 match this {
326 Some(Self::Set(value)) => Some(value),
327 Some(Self::Remove { remove: true }) => None,
328 Some(Self::Remove { remove: false }) | None => original,
329 }
330 }
331}
332
333impl Default for LanguageConfig {
334 fn default() -> Self {
335 Self {
336 name: "".into(),
337 path_suffixes: Default::default(),
338 brackets: Default::default(),
339 auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
340 increase_indent_pattern: Default::default(),
341 decrease_indent_pattern: Default::default(),
342 autoclose_before: Default::default(),
343 line_comment: Default::default(),
344 block_comment: Default::default(),
345 overrides: Default::default(),
346 }
347 }
348}
349
350fn auto_indent_using_last_non_empty_line_default() -> bool {
351 true
352}
353
354fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
355 let source = Option::<String>::deserialize(d)?;
356 if let Some(source) = source {
357 Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
358 } else {
359 Ok(None)
360 }
361}
362
363#[cfg(any(test, feature = "test-support"))]
364pub struct FakeLspAdapter {
365 pub name: &'static str,
366 pub capabilities: lsp::ServerCapabilities,
367 pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
368 pub disk_based_diagnostics_progress_token: Option<String>,
369 pub disk_based_diagnostics_sources: Vec<String>,
370}
371
372#[derive(Clone, Debug, Default)]
373pub struct BracketPairConfig {
374 pub pairs: Vec<BracketPair>,
375 pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
376}
377
378impl<'de> Deserialize<'de> for BracketPairConfig {
379 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
380 where
381 D: Deserializer<'de>,
382 {
383 #[derive(Deserialize)]
384 pub struct Entry {
385 #[serde(flatten)]
386 pub bracket_pair: BracketPair,
387 #[serde(default)]
388 pub not_in: Vec<String>,
389 }
390
391 let result = Vec::<Entry>::deserialize(deserializer)?;
392 let mut brackets = Vec::with_capacity(result.len());
393 let mut disabled_scopes_by_bracket_ix = Vec::with_capacity(result.len());
394 for entry in result {
395 brackets.push(entry.bracket_pair);
396 disabled_scopes_by_bracket_ix.push(entry.not_in);
397 }
398
399 Ok(BracketPairConfig {
400 pairs: brackets,
401 disabled_scopes_by_bracket_ix,
402 })
403 }
404}
405
406#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
407pub struct BracketPair {
408 pub start: String,
409 pub end: String,
410 pub close: bool,
411 pub newline: bool,
412}
413
414pub struct Language {
415 pub(crate) config: LanguageConfig,
416 pub(crate) grammar: Option<Arc<Grammar>>,
417 pub(crate) adapter: Option<Arc<CachedLspAdapter>>,
418
419 #[cfg(any(test, feature = "test-support"))]
420 fake_adapter: Option<(
421 mpsc::UnboundedSender<lsp::FakeLanguageServer>,
422 Arc<FakeLspAdapter>,
423 )>,
424}
425
426pub struct Grammar {
427 id: usize,
428 pub(crate) ts_language: tree_sitter::Language,
429 pub(crate) error_query: Query,
430 pub(crate) highlights_query: Option<Query>,
431 pub(crate) brackets_config: Option<BracketConfig>,
432 pub(crate) indents_config: Option<IndentConfig>,
433 pub(crate) outline_config: Option<OutlineConfig>,
434 pub(crate) injection_config: Option<InjectionConfig>,
435 pub(crate) override_config: Option<OverrideConfig>,
436 pub(crate) highlight_map: Mutex<HighlightMap>,
437}
438
439struct IndentConfig {
440 query: Query,
441 indent_capture_ix: u32,
442 start_capture_ix: Option<u32>,
443 end_capture_ix: Option<u32>,
444 outdent_capture_ix: Option<u32>,
445}
446
447struct OutlineConfig {
448 query: Query,
449 item_capture_ix: u32,
450 name_capture_ix: u32,
451 context_capture_ix: Option<u32>,
452}
453
454struct InjectionConfig {
455 query: Query,
456 content_capture_ix: u32,
457 language_capture_ix: Option<u32>,
458 patterns: Vec<InjectionPatternConfig>,
459}
460
461struct OverrideConfig {
462 query: Query,
463 values: HashMap<u32, (String, LanguageConfigOverride)>,
464}
465
466#[derive(Default, Clone)]
467struct InjectionPatternConfig {
468 language: Option<Box<str>>,
469 combined: bool,
470}
471
472struct BracketConfig {
473 query: Query,
474 open_capture_ix: u32,
475 close_capture_ix: u32,
476}
477
478#[derive(Clone)]
479pub enum LanguageServerBinaryStatus {
480 CheckingForUpdate,
481 Downloading,
482 Downloaded,
483 Cached,
484 Failed { error: String },
485}
486
487type AvailableLanguageId = usize;
488
489#[derive(Clone)]
490struct AvailableLanguage {
491 id: AvailableLanguageId,
492 path: &'static str,
493 config: LanguageConfig,
494 grammar: tree_sitter::Language,
495 lsp_adapter: Option<Arc<dyn LspAdapter>>,
496 get_queries: fn(&str) -> LanguageQueries,
497}
498
499pub struct LanguageRegistry {
500 state: RwLock<LanguageRegistryState>,
501 language_server_download_dir: Option<Arc<Path>>,
502 lsp_binary_statuses_tx: async_broadcast::Sender<(Arc<Language>, LanguageServerBinaryStatus)>,
503 lsp_binary_statuses_rx: async_broadcast::Receiver<(Arc<Language>, LanguageServerBinaryStatus)>,
504 login_shell_env_loaded: Shared<Task<()>>,
505 #[allow(clippy::type_complexity)]
506 lsp_binary_paths: Mutex<
507 HashMap<
508 LanguageServerName,
509 Shared<BoxFuture<'static, Result<LanguageServerBinary, Arc<anyhow::Error>>>>,
510 >,
511 >,
512 executor: Option<Arc<Background>>,
513}
514
515struct LanguageRegistryState {
516 languages: Vec<Arc<Language>>,
517 available_languages: Vec<AvailableLanguage>,
518 next_available_language_id: AvailableLanguageId,
519 loading_languages: HashMap<AvailableLanguageId, Vec<oneshot::Sender<Result<Arc<Language>>>>>,
520 subscription: (watch::Sender<()>, watch::Receiver<()>),
521 theme: Option<Arc<Theme>>,
522 version: usize,
523}
524
525impl LanguageRegistry {
526 pub fn new(login_shell_env_loaded: Task<()>) -> Self {
527 let (lsp_binary_statuses_tx, lsp_binary_statuses_rx) = async_broadcast::broadcast(16);
528 Self {
529 state: RwLock::new(LanguageRegistryState {
530 languages: vec![PLAIN_TEXT.clone()],
531 available_languages: Default::default(),
532 next_available_language_id: 0,
533 loading_languages: Default::default(),
534 subscription: watch::channel(),
535 theme: Default::default(),
536 version: 0,
537 }),
538 language_server_download_dir: None,
539 lsp_binary_statuses_tx,
540 lsp_binary_statuses_rx,
541 login_shell_env_loaded: login_shell_env_loaded.shared(),
542 lsp_binary_paths: Default::default(),
543 executor: None,
544 }
545 }
546
547 #[cfg(any(test, feature = "test-support"))]
548 pub fn test() -> Self {
549 Self::new(Task::ready(()))
550 }
551
552 pub fn set_executor(&mut self, executor: Arc<Background>) {
553 self.executor = Some(executor);
554 }
555
556 pub fn register(
557 &self,
558 path: &'static str,
559 config: LanguageConfig,
560 grammar: tree_sitter::Language,
561 lsp_adapter: Option<Arc<dyn LspAdapter>>,
562 get_queries: fn(&str) -> LanguageQueries,
563 ) {
564 let state = &mut *self.state.write();
565 state.available_languages.push(AvailableLanguage {
566 id: post_inc(&mut state.next_available_language_id),
567 path,
568 config,
569 grammar,
570 lsp_adapter,
571 get_queries,
572 });
573 }
574
575 pub fn language_names(&self) -> Vec<String> {
576 let state = self.state.read();
577 let mut result = state
578 .available_languages
579 .iter()
580 .map(|l| l.config.name.to_string())
581 .chain(state.languages.iter().map(|l| l.config.name.to_string()))
582 .collect::<Vec<_>>();
583 result.sort_unstable_by_key(|language_name| language_name.to_lowercase());
584 result
585 }
586
587 pub fn workspace_configuration(&self, cx: &mut MutableAppContext) -> Task<serde_json::Value> {
588 let lsp_adapters = {
589 let state = self.state.read();
590 state
591 .available_languages
592 .iter()
593 .filter_map(|l| l.lsp_adapter.clone())
594 .chain(
595 state
596 .languages
597 .iter()
598 .filter_map(|l| l.adapter.as_ref().map(|a| a.adapter.clone())),
599 )
600 .collect::<Vec<_>>()
601 };
602
603 let mut language_configs = Vec::new();
604 for adapter in &lsp_adapters {
605 if let Some(language_config) = adapter.workspace_configuration(cx) {
606 language_configs.push(language_config);
607 }
608 }
609
610 cx.background().spawn(async move {
611 let mut config = serde_json::json!({});
612 let language_configs = futures::future::join_all(language_configs).await;
613 for language_config in language_configs {
614 merge_json_value_into(language_config, &mut config);
615 }
616 config
617 })
618 }
619
620 pub fn add(&self, language: Arc<Language>) {
621 self.state.write().add(language);
622 }
623
624 pub fn subscribe(&self) -> watch::Receiver<()> {
625 self.state.read().subscription.1.clone()
626 }
627
628 pub fn version(&self) -> usize {
629 self.state.read().version
630 }
631
632 pub fn set_theme(&self, theme: Arc<Theme>) {
633 let mut state = self.state.write();
634 state.theme = Some(theme.clone());
635 for language in &state.languages {
636 language.set_theme(&theme.editor.syntax);
637 }
638 }
639
640 pub fn set_language_server_download_dir(&mut self, path: impl Into<Arc<Path>>) {
641 self.language_server_download_dir = Some(path.into());
642 }
643
644 pub fn language_for_name(
645 self: &Arc<Self>,
646 name: &str,
647 ) -> UnwrapFuture<oneshot::Receiver<Result<Arc<Language>>>> {
648 let name = UniCase::new(name);
649 self.get_or_load_language(|config| UniCase::new(config.name.as_ref()) == name)
650 }
651
652 pub fn language_for_name_or_extension(
653 self: &Arc<Self>,
654 string: &str,
655 ) -> UnwrapFuture<oneshot::Receiver<Result<Arc<Language>>>> {
656 let string = UniCase::new(string);
657 self.get_or_load_language(|config| {
658 UniCase::new(config.name.as_ref()) == string
659 || config
660 .path_suffixes
661 .iter()
662 .any(|suffix| UniCase::new(suffix) == string)
663 })
664 }
665
666 pub fn language_for_path(
667 self: &Arc<Self>,
668 path: impl AsRef<Path>,
669 ) -> UnwrapFuture<oneshot::Receiver<Result<Arc<Language>>>> {
670 let path = path.as_ref();
671 let filename = path.file_name().and_then(|name| name.to_str());
672 let extension = path.extension().and_then(|name| name.to_str());
673 let path_suffixes = [extension, filename];
674 self.get_or_load_language(|config| {
675 config
676 .path_suffixes
677 .iter()
678 .any(|suffix| path_suffixes.contains(&Some(suffix.as_str())))
679 })
680 }
681
682 fn get_or_load_language(
683 self: &Arc<Self>,
684 callback: impl Fn(&LanguageConfig) -> bool,
685 ) -> UnwrapFuture<oneshot::Receiver<Result<Arc<Language>>>> {
686 let (tx, rx) = oneshot::channel();
687
688 let mut state = self.state.write();
689 if let Some(language) = state
690 .languages
691 .iter()
692 .find(|language| callback(&language.config))
693 {
694 let _ = tx.send(Ok(language.clone()));
695 } else if let Some(executor) = self.executor.clone() {
696 if let Some(language) = state
697 .available_languages
698 .iter()
699 .find(|l| callback(&l.config))
700 .cloned()
701 {
702 let txs = state
703 .loading_languages
704 .entry(language.id)
705 .or_insert_with(|| {
706 let this = self.clone();
707 executor
708 .spawn(async move {
709 let id = language.id;
710 let queries = (language.get_queries)(&language.path);
711 let language =
712 Language::new(language.config, Some(language.grammar))
713 .with_lsp_adapter(language.lsp_adapter)
714 .await;
715 let name = language.name();
716 match language.with_queries(queries) {
717 Ok(language) => {
718 let language = Arc::new(language);
719 let mut state = this.state.write();
720 state.add(language.clone());
721 state
722 .available_languages
723 .retain(|language| language.id != id);
724 if let Some(mut txs) = state.loading_languages.remove(&id) {
725 for tx in txs.drain(..) {
726 let _ = tx.send(Ok(language.clone()));
727 }
728 }
729 }
730 Err(err) => {
731 let mut state = this.state.write();
732 state
733 .available_languages
734 .retain(|language| language.id != id);
735 if let Some(mut txs) = state.loading_languages.remove(&id) {
736 for tx in txs.drain(..) {
737 let _ = tx.send(Err(anyhow!(
738 "failed to load language {}: {}",
739 name,
740 err
741 )));
742 }
743 }
744 }
745 };
746 })
747 .detach();
748
749 Vec::new()
750 });
751 txs.push(tx);
752 } else {
753 let _ = tx.send(Err(anyhow!("language not found")));
754 }
755 } else {
756 let _ = tx.send(Err(anyhow!("executor does not exist")));
757 }
758
759 rx.unwrap()
760 }
761
762 pub fn to_vec(&self) -> Vec<Arc<Language>> {
763 self.state.read().languages.iter().cloned().collect()
764 }
765
766 pub fn start_language_server(
767 self: &Arc<Self>,
768 server_id: usize,
769 language: Arc<Language>,
770 root_path: Arc<Path>,
771 http_client: Arc<dyn HttpClient>,
772 cx: &mut MutableAppContext,
773 ) -> Option<Task<Result<lsp::LanguageServer>>> {
774 #[cfg(any(test, feature = "test-support"))]
775 if language.fake_adapter.is_some() {
776 let language = language;
777 return Some(cx.spawn(|cx| async move {
778 let (servers_tx, fake_adapter) = language.fake_adapter.as_ref().unwrap();
779 let (server, mut fake_server) = lsp::LanguageServer::fake(
780 fake_adapter.name.to_string(),
781 fake_adapter.capabilities.clone(),
782 cx.clone(),
783 );
784
785 if let Some(initializer) = &fake_adapter.initializer {
786 initializer(&mut fake_server);
787 }
788
789 let servers_tx = servers_tx.clone();
790 cx.background()
791 .spawn(async move {
792 if fake_server
793 .try_receive_notification::<lsp::notification::Initialized>()
794 .await
795 .is_some()
796 {
797 servers_tx.unbounded_send(fake_server).ok();
798 }
799 })
800 .detach();
801 Ok(server)
802 }));
803 }
804
805 let download_dir = self
806 .language_server_download_dir
807 .clone()
808 .ok_or_else(|| anyhow!("language server download directory has not been assigned"))
809 .log_err()?;
810
811 let this = self.clone();
812 let adapter = language.adapter.clone()?;
813 let lsp_binary_statuses = self.lsp_binary_statuses_tx.clone();
814 let login_shell_env_loaded = self.login_shell_env_loaded.clone();
815
816 Some(cx.spawn(|cx| async move {
817 login_shell_env_loaded.await;
818
819 let mut lock = this.lsp_binary_paths.lock();
820 let entry = lock
821 .entry(adapter.name.clone())
822 .or_insert_with(|| {
823 get_binary(
824 adapter.clone(),
825 language.clone(),
826 http_client,
827 download_dir,
828 lsp_binary_statuses,
829 )
830 .map_err(Arc::new)
831 .boxed()
832 .shared()
833 })
834 .clone();
835 drop(lock);
836 let binary = entry.clone().map_err(|e| anyhow!(e)).await?;
837
838 let server = lsp::LanguageServer::new(
839 server_id,
840 &binary.path,
841 &binary.arguments,
842 &root_path,
843 adapter.code_action_kinds(),
844 cx,
845 )?;
846
847 Ok(server)
848 }))
849 }
850
851 pub fn language_server_binary_statuses(
852 &self,
853 ) -> async_broadcast::Receiver<(Arc<Language>, LanguageServerBinaryStatus)> {
854 self.lsp_binary_statuses_rx.clone()
855 }
856}
857
858impl LanguageRegistryState {
859 fn add(&mut self, language: Arc<Language>) {
860 if let Some(theme) = self.theme.as_ref() {
861 language.set_theme(&theme.editor.syntax);
862 }
863 self.languages.push(language);
864 self.version += 1;
865 *self.subscription.0.borrow_mut() = ();
866 }
867}
868
869#[cfg(any(test, feature = "test-support"))]
870impl Default for LanguageRegistry {
871 fn default() -> Self {
872 Self::test()
873 }
874}
875
876async fn get_binary(
877 adapter: Arc<CachedLspAdapter>,
878 language: Arc<Language>,
879 http_client: Arc<dyn HttpClient>,
880 download_dir: Arc<Path>,
881 statuses: async_broadcast::Sender<(Arc<Language>, LanguageServerBinaryStatus)>,
882) -> Result<LanguageServerBinary> {
883 let container_dir = download_dir.join(adapter.name.0.as_ref());
884 if !container_dir.exists() {
885 smol::fs::create_dir_all(&container_dir)
886 .await
887 .context("failed to create container directory")?;
888 }
889
890 let binary = fetch_latest_binary(
891 adapter.clone(),
892 language.clone(),
893 http_client,
894 &container_dir,
895 statuses.clone(),
896 )
897 .await;
898
899 if let Err(error) = binary.as_ref() {
900 if let Some(cached) = adapter.cached_server_binary(container_dir).await {
901 statuses
902 .broadcast((language.clone(), LanguageServerBinaryStatus::Cached))
903 .await?;
904 return Ok(cached);
905 } else {
906 statuses
907 .broadcast((
908 language.clone(),
909 LanguageServerBinaryStatus::Failed {
910 error: format!("{:?}", error),
911 },
912 ))
913 .await?;
914 }
915 }
916 binary
917}
918
919async fn fetch_latest_binary(
920 adapter: Arc<CachedLspAdapter>,
921 language: Arc<Language>,
922 http_client: Arc<dyn HttpClient>,
923 container_dir: &Path,
924 lsp_binary_statuses_tx: async_broadcast::Sender<(Arc<Language>, LanguageServerBinaryStatus)>,
925) -> Result<LanguageServerBinary> {
926 let container_dir: Arc<Path> = container_dir.into();
927 lsp_binary_statuses_tx
928 .broadcast((
929 language.clone(),
930 LanguageServerBinaryStatus::CheckingForUpdate,
931 ))
932 .await?;
933 let version_info = adapter
934 .fetch_latest_server_version(http_client.clone())
935 .await?;
936 lsp_binary_statuses_tx
937 .broadcast((language.clone(), LanguageServerBinaryStatus::Downloading))
938 .await?;
939 let binary = adapter
940 .fetch_server_binary(version_info, http_client, container_dir.to_path_buf())
941 .await?;
942 lsp_binary_statuses_tx
943 .broadcast((language.clone(), LanguageServerBinaryStatus::Downloaded))
944 .await?;
945 Ok(binary)
946}
947
948impl Language {
949 pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
950 Self {
951 config,
952 grammar: ts_language.map(|ts_language| {
953 Arc::new(Grammar {
954 id: NEXT_GRAMMAR_ID.fetch_add(1, SeqCst),
955 highlights_query: None,
956 brackets_config: None,
957 outline_config: None,
958 indents_config: None,
959 injection_config: None,
960 override_config: None,
961 error_query: Query::new(ts_language, "(ERROR) @error").unwrap(),
962 ts_language,
963 highlight_map: Default::default(),
964 })
965 }),
966 adapter: None,
967
968 #[cfg(any(test, feature = "test-support"))]
969 fake_adapter: None,
970 }
971 }
972
973 pub fn lsp_adapter(&self) -> Option<Arc<CachedLspAdapter>> {
974 self.adapter.clone()
975 }
976
977 pub fn id(&self) -> Option<usize> {
978 self.grammar.as_ref().map(|g| g.id)
979 }
980
981 pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
982 if let Some(query) = queries.highlights {
983 self = self
984 .with_highlights_query(query.as_ref())
985 .expect("failed to evaluate highlights query");
986 }
987 if let Some(query) = queries.brackets {
988 self = self
989 .with_brackets_query(query.as_ref())
990 .expect("failed to load brackets query");
991 }
992 if let Some(query) = queries.indents {
993 self = self
994 .with_indents_query(query.as_ref())
995 .expect("failed to load indents query");
996 }
997 if let Some(query) = queries.outline {
998 self = self
999 .with_outline_query(query.as_ref())
1000 .expect("failed to load outline query");
1001 }
1002 if let Some(query) = queries.injections {
1003 self = self
1004 .with_injection_query(query.as_ref())
1005 .expect("failed to load injection query");
1006 }
1007 if let Some(query) = queries.overrides {
1008 self = self
1009 .with_override_query(query.as_ref())
1010 .expect("failed to load override query");
1011 }
1012 Ok(self)
1013 }
1014 pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1015 let grammar = self.grammar_mut();
1016 grammar.highlights_query = Some(Query::new(grammar.ts_language, source)?);
1017 Ok(self)
1018 }
1019
1020 pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1021 let grammar = self.grammar_mut();
1022 let query = Query::new(grammar.ts_language, source)?;
1023 let mut item_capture_ix = None;
1024 let mut name_capture_ix = None;
1025 let mut context_capture_ix = None;
1026 get_capture_indices(
1027 &query,
1028 &mut [
1029 ("item", &mut item_capture_ix),
1030 ("name", &mut name_capture_ix),
1031 ("context", &mut context_capture_ix),
1032 ],
1033 );
1034 if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
1035 grammar.outline_config = Some(OutlineConfig {
1036 query,
1037 item_capture_ix,
1038 name_capture_ix,
1039 context_capture_ix,
1040 });
1041 }
1042 Ok(self)
1043 }
1044
1045 pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1046 let grammar = self.grammar_mut();
1047 let query = Query::new(grammar.ts_language, source)?;
1048 let mut open_capture_ix = None;
1049 let mut close_capture_ix = None;
1050 get_capture_indices(
1051 &query,
1052 &mut [
1053 ("open", &mut open_capture_ix),
1054 ("close", &mut close_capture_ix),
1055 ],
1056 );
1057 if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1058 grammar.brackets_config = Some(BracketConfig {
1059 query,
1060 open_capture_ix,
1061 close_capture_ix,
1062 });
1063 }
1064 Ok(self)
1065 }
1066
1067 pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1068 let grammar = self.grammar_mut();
1069 let query = Query::new(grammar.ts_language, source)?;
1070 let mut indent_capture_ix = None;
1071 let mut start_capture_ix = None;
1072 let mut end_capture_ix = None;
1073 let mut outdent_capture_ix = None;
1074 get_capture_indices(
1075 &query,
1076 &mut [
1077 ("indent", &mut indent_capture_ix),
1078 ("start", &mut start_capture_ix),
1079 ("end", &mut end_capture_ix),
1080 ("outdent", &mut outdent_capture_ix),
1081 ],
1082 );
1083 if let Some(indent_capture_ix) = indent_capture_ix {
1084 grammar.indents_config = Some(IndentConfig {
1085 query,
1086 indent_capture_ix,
1087 start_capture_ix,
1088 end_capture_ix,
1089 outdent_capture_ix,
1090 });
1091 }
1092 Ok(self)
1093 }
1094
1095 pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1096 let grammar = self.grammar_mut();
1097 let query = Query::new(grammar.ts_language, source)?;
1098 let mut language_capture_ix = None;
1099 let mut content_capture_ix = None;
1100 get_capture_indices(
1101 &query,
1102 &mut [
1103 ("language", &mut language_capture_ix),
1104 ("content", &mut content_capture_ix),
1105 ],
1106 );
1107 let patterns = (0..query.pattern_count())
1108 .map(|ix| {
1109 let mut config = InjectionPatternConfig::default();
1110 for setting in query.property_settings(ix) {
1111 match setting.key.as_ref() {
1112 "language" => {
1113 config.language = setting.value.clone();
1114 }
1115 "combined" => {
1116 config.combined = true;
1117 }
1118 _ => {}
1119 }
1120 }
1121 config
1122 })
1123 .collect();
1124 if let Some(content_capture_ix) = content_capture_ix {
1125 grammar.injection_config = Some(InjectionConfig {
1126 query,
1127 language_capture_ix,
1128 content_capture_ix,
1129 patterns,
1130 });
1131 }
1132 Ok(self)
1133 }
1134
1135 pub fn with_override_query(mut self, source: &str) -> Result<Self> {
1136 let query = Query::new(self.grammar_mut().ts_language, source)?;
1137
1138 let mut override_configs_by_id = HashMap::default();
1139 for (ix, name) in query.capture_names().iter().enumerate() {
1140 if !name.starts_with('_') {
1141 let value = self.config.overrides.remove(name).unwrap_or_default();
1142 override_configs_by_id.insert(ix as u32, (name.clone(), value));
1143 }
1144 }
1145
1146 if !self.config.overrides.is_empty() {
1147 let keys = self.config.overrides.keys().collect::<Vec<_>>();
1148 Err(anyhow!(
1149 "language {:?} has overrides in config not in query: {keys:?}",
1150 self.config.name
1151 ))?;
1152 }
1153
1154 for disabled_scope_name in self
1155 .config
1156 .brackets
1157 .disabled_scopes_by_bracket_ix
1158 .iter()
1159 .flatten()
1160 {
1161 if !override_configs_by_id
1162 .values()
1163 .any(|(scope_name, _)| scope_name == disabled_scope_name)
1164 {
1165 Err(anyhow!(
1166 "language {:?} has overrides in config not in query: {disabled_scope_name:?}",
1167 self.config.name
1168 ))?;
1169 }
1170 }
1171
1172 for (name, override_config) in override_configs_by_id.values_mut() {
1173 override_config.disabled_bracket_ixs = self
1174 .config
1175 .brackets
1176 .disabled_scopes_by_bracket_ix
1177 .iter()
1178 .enumerate()
1179 .filter_map(|(ix, disabled_scope_names)| {
1180 if disabled_scope_names.contains(name) {
1181 Some(ix as u16)
1182 } else {
1183 None
1184 }
1185 })
1186 .collect();
1187 }
1188
1189 self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1190 self.grammar_mut().override_config = Some(OverrideConfig {
1191 query,
1192 values: override_configs_by_id,
1193 });
1194 Ok(self)
1195 }
1196
1197 fn grammar_mut(&mut self) -> &mut Grammar {
1198 Arc::get_mut(self.grammar.as_mut().unwrap()).unwrap()
1199 }
1200
1201 pub async fn with_lsp_adapter(mut self, lsp_adapter: Option<Arc<dyn LspAdapter>>) -> Self {
1202 if let Some(adapter) = lsp_adapter {
1203 self.adapter = Some(CachedLspAdapter::new(adapter).await);
1204 }
1205 self
1206 }
1207
1208 #[cfg(any(test, feature = "test-support"))]
1209 pub async fn set_fake_lsp_adapter(
1210 &mut self,
1211 fake_lsp_adapter: Arc<FakeLspAdapter>,
1212 ) -> mpsc::UnboundedReceiver<lsp::FakeLanguageServer> {
1213 let (servers_tx, servers_rx) = mpsc::unbounded();
1214 self.fake_adapter = Some((servers_tx, fake_lsp_adapter.clone()));
1215 let adapter = CachedLspAdapter::new(Arc::new(fake_lsp_adapter)).await;
1216 self.adapter = Some(adapter);
1217 servers_rx
1218 }
1219
1220 pub fn name(&self) -> Arc<str> {
1221 self.config.name.clone()
1222 }
1223
1224 pub async fn disk_based_diagnostic_sources(&self) -> &[String] {
1225 match self.adapter.as_ref() {
1226 Some(adapter) => &adapter.disk_based_diagnostic_sources,
1227 None => &[],
1228 }
1229 }
1230
1231 pub async fn disk_based_diagnostics_progress_token(&self) -> Option<&str> {
1232 if let Some(adapter) = self.adapter.as_ref() {
1233 adapter.disk_based_diagnostics_progress_token.as_deref()
1234 } else {
1235 None
1236 }
1237 }
1238
1239 pub async fn process_diagnostics(&self, diagnostics: &mut lsp::PublishDiagnosticsParams) {
1240 if let Some(processor) = self.adapter.as_ref() {
1241 processor.process_diagnostics(diagnostics).await;
1242 }
1243 }
1244
1245 pub async fn process_completion(self: &Arc<Self>, completion: &mut lsp::CompletionItem) {
1246 if let Some(adapter) = self.adapter.as_ref() {
1247 adapter.process_completion(completion).await;
1248 }
1249 }
1250
1251 pub async fn label_for_completion(
1252 self: &Arc<Self>,
1253 completion: &lsp::CompletionItem,
1254 ) -> Option<CodeLabel> {
1255 self.adapter
1256 .as_ref()?
1257 .label_for_completion(completion, self)
1258 .await
1259 }
1260
1261 pub async fn label_for_symbol(
1262 self: &Arc<Self>,
1263 name: &str,
1264 kind: lsp::SymbolKind,
1265 ) -> Option<CodeLabel> {
1266 self.adapter
1267 .as_ref()?
1268 .label_for_symbol(name, kind, self)
1269 .await
1270 }
1271
1272 pub fn highlight_text<'a>(
1273 self: &'a Arc<Self>,
1274 text: &'a Rope,
1275 range: Range<usize>,
1276 ) -> Vec<(Range<usize>, HighlightId)> {
1277 let mut result = Vec::new();
1278 if let Some(grammar) = &self.grammar {
1279 let tree = grammar.parse_text(text, None);
1280 let captures =
1281 SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1282 grammar.highlights_query.as_ref()
1283 });
1284 let highlight_maps = vec![grammar.highlight_map()];
1285 let mut offset = 0;
1286 for chunk in BufferChunks::new(text, range, Some((captures, highlight_maps)), vec![]) {
1287 let end_offset = offset + chunk.text.len();
1288 if let Some(highlight_id) = chunk.syntax_highlight_id {
1289 if !highlight_id.is_default() {
1290 result.push((offset..end_offset, highlight_id));
1291 }
1292 }
1293 offset = end_offset;
1294 }
1295 }
1296 result
1297 }
1298
1299 pub fn path_suffixes(&self) -> &[String] {
1300 &self.config.path_suffixes
1301 }
1302
1303 pub fn should_autoclose_before(&self, c: char) -> bool {
1304 c.is_whitespace() || self.config.autoclose_before.contains(c)
1305 }
1306
1307 pub fn set_theme(&self, theme: &SyntaxTheme) {
1308 if let Some(grammar) = self.grammar.as_ref() {
1309 if let Some(highlights_query) = &grammar.highlights_query {
1310 *grammar.highlight_map.lock() =
1311 HighlightMap::new(highlights_query.capture_names(), theme);
1312 }
1313 }
1314 }
1315
1316 pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1317 self.grammar.as_ref()
1318 }
1319}
1320
1321impl LanguageScope {
1322 pub fn line_comment_prefix(&self) -> Option<&Arc<str>> {
1323 Override::as_option(
1324 self.config_override().map(|o| &o.line_comment),
1325 self.language.config.line_comment.as_ref(),
1326 )
1327 }
1328
1329 pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1330 Override::as_option(
1331 self.config_override().map(|o| &o.block_comment),
1332 self.language.config.block_comment.as_ref(),
1333 )
1334 .map(|e| (&e.0, &e.1))
1335 }
1336
1337 pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1338 let mut disabled_ids = self
1339 .config_override()
1340 .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1341 self.language
1342 .config
1343 .brackets
1344 .pairs
1345 .iter()
1346 .enumerate()
1347 .map(move |(ix, bracket)| {
1348 let mut is_enabled = true;
1349 if let Some(next_disabled_ix) = disabled_ids.first() {
1350 if ix == *next_disabled_ix as usize {
1351 disabled_ids = &disabled_ids[1..];
1352 is_enabled = false;
1353 }
1354 }
1355 (bracket, is_enabled)
1356 })
1357 }
1358
1359 pub fn should_autoclose_before(&self, c: char) -> bool {
1360 c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1361 }
1362
1363 fn config_override(&self) -> Option<&LanguageConfigOverride> {
1364 let id = self.override_id?;
1365 let grammar = self.language.grammar.as_ref()?;
1366 let override_config = grammar.override_config.as_ref()?;
1367 override_config.values.get(&id).map(|e| &e.1)
1368 }
1369}
1370
1371impl Hash for Language {
1372 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1373 self.id().hash(state)
1374 }
1375}
1376
1377impl PartialEq for Language {
1378 fn eq(&self, other: &Self) -> bool {
1379 self.id().eq(&other.id())
1380 }
1381}
1382
1383impl Eq for Language {}
1384
1385impl Debug for Language {
1386 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1387 f.debug_struct("Language")
1388 .field("name", &self.config.name)
1389 .finish()
1390 }
1391}
1392
1393impl Grammar {
1394 pub fn id(&self) -> usize {
1395 self.id
1396 }
1397
1398 fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1399 PARSER.with(|parser| {
1400 let mut parser = parser.borrow_mut();
1401 parser
1402 .set_language(self.ts_language)
1403 .expect("incompatible grammar");
1404 let mut chunks = text.chunks_in_range(0..text.len());
1405 parser
1406 .parse_with(
1407 &mut move |offset, _| {
1408 chunks.seek(offset);
1409 chunks.next().unwrap_or("").as_bytes()
1410 },
1411 old_tree.as_ref(),
1412 )
1413 .unwrap()
1414 })
1415 }
1416
1417 pub fn highlight_map(&self) -> HighlightMap {
1418 self.highlight_map.lock().clone()
1419 }
1420
1421 pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1422 let capture_id = self
1423 .highlights_query
1424 .as_ref()?
1425 .capture_index_for_name(name)?;
1426 Some(self.highlight_map.lock().get(capture_id))
1427 }
1428}
1429
1430impl CodeLabel {
1431 pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1432 let mut result = Self {
1433 runs: Vec::new(),
1434 filter_range: 0..text.len(),
1435 text,
1436 };
1437 if let Some(filter_text) = filter_text {
1438 if let Some(ix) = result.text.find(filter_text) {
1439 result.filter_range = ix..ix + filter_text.len();
1440 }
1441 }
1442 result
1443 }
1444}
1445
1446#[cfg(any(test, feature = "test-support"))]
1447impl Default for FakeLspAdapter {
1448 fn default() -> Self {
1449 Self {
1450 name: "the-fake-language-server",
1451 capabilities: lsp::LanguageServer::full_capabilities(),
1452 initializer: None,
1453 disk_based_diagnostics_progress_token: None,
1454 disk_based_diagnostics_sources: Vec::new(),
1455 }
1456 }
1457}
1458
1459#[cfg(any(test, feature = "test-support"))]
1460#[async_trait]
1461impl LspAdapter for Arc<FakeLspAdapter> {
1462 async fn name(&self) -> LanguageServerName {
1463 LanguageServerName(self.name.into())
1464 }
1465
1466 async fn fetch_latest_server_version(
1467 &self,
1468 _: Arc<dyn HttpClient>,
1469 ) -> Result<Box<dyn 'static + Send + Any>> {
1470 unreachable!();
1471 }
1472
1473 async fn fetch_server_binary(
1474 &self,
1475 _: Box<dyn 'static + Send + Any>,
1476 _: Arc<dyn HttpClient>,
1477 _: PathBuf,
1478 ) -> Result<LanguageServerBinary> {
1479 unreachable!();
1480 }
1481
1482 async fn cached_server_binary(&self, _: PathBuf) -> Option<LanguageServerBinary> {
1483 unreachable!();
1484 }
1485
1486 async fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
1487
1488 async fn disk_based_diagnostic_sources(&self) -> Vec<String> {
1489 self.disk_based_diagnostics_sources.clone()
1490 }
1491
1492 async fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
1493 self.disk_based_diagnostics_progress_token.clone()
1494 }
1495}
1496
1497fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
1498 for (ix, name) in query.capture_names().iter().enumerate() {
1499 for (capture_name, index) in captures.iter_mut() {
1500 if capture_name == name {
1501 **index = Some(ix as u32);
1502 break;
1503 }
1504 }
1505 }
1506}
1507
1508pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
1509 lsp::Position::new(point.row, point.column)
1510}
1511
1512pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
1513 Unclipped(PointUtf16::new(point.line, point.character))
1514}
1515
1516pub fn range_to_lsp(range: Range<PointUtf16>) -> lsp::Range {
1517 lsp::Range {
1518 start: point_to_lsp(range.start),
1519 end: point_to_lsp(range.end),
1520 }
1521}
1522
1523pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
1524 let mut start = point_from_lsp(range.start);
1525 let mut end = point_from_lsp(range.end);
1526 if start > end {
1527 mem::swap(&mut start, &mut end);
1528 }
1529 start..end
1530}
1531
1532#[cfg(test)]
1533mod tests {
1534 use gpui::TestAppContext;
1535
1536 use super::*;
1537
1538 #[gpui::test(iterations = 10)]
1539 async fn test_language_loading(cx: &mut TestAppContext) {
1540 let mut languages = LanguageRegistry::test();
1541 languages.set_executor(cx.background());
1542 let languages = Arc::new(languages);
1543 languages.register(
1544 "/JSON",
1545 LanguageConfig {
1546 name: "JSON".into(),
1547 path_suffixes: vec!["json".into()],
1548 ..Default::default()
1549 },
1550 tree_sitter_json::language(),
1551 None,
1552 |_| Default::default(),
1553 );
1554 languages.register(
1555 "/rust",
1556 LanguageConfig {
1557 name: "Rust".into(),
1558 path_suffixes: vec!["rs".into()],
1559 ..Default::default()
1560 },
1561 tree_sitter_rust::language(),
1562 None,
1563 |_| Default::default(),
1564 );
1565 assert_eq!(
1566 languages.language_names(),
1567 &[
1568 "JSON".to_string(),
1569 "Plain Text".to_string(),
1570 "Rust".to_string(),
1571 ]
1572 );
1573
1574 let rust1 = languages.language_for_name("Rust");
1575 let rust2 = languages.language_for_name("Rust");
1576
1577 // Ensure language is still listed even if it's being loaded.
1578 assert_eq!(
1579 languages.language_names(),
1580 &[
1581 "JSON".to_string(),
1582 "Plain Text".to_string(),
1583 "Rust".to_string(),
1584 ]
1585 );
1586
1587 let (rust1, rust2) = futures::join!(rust1, rust2);
1588 assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
1589
1590 // Ensure language is still listed even after loading it.
1591 assert_eq!(
1592 languages.language_names(),
1593 &[
1594 "JSON".to_string(),
1595 "Plain Text".to_string(),
1596 "Rust".to_string(),
1597 ]
1598 );
1599
1600 // Loading an unknown language returns an error.
1601 assert!(languages.language_for_name("Unknown").await.is_err());
1602 }
1603}