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