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