1//! The `language` crate provides a large chunk of Zed's language-related
2//! features (the other big contributors being project and lsp crates that revolve around LSP features).
3//! Namely, this crate:
4//! - Provides [`Language`], [`Grammar`] and [`LanguageRegistry`] types that
5//! use Tree-sitter to provide syntax highlighting to the editor; note though that `language` doesn't perform the highlighting by itself. It only maps ranges in a buffer to colors. Treesitter is also used for buffer outlines (lists of symbols in a buffer)
6//! - Exposes [`LanguageConfig`] that describes how constructs (like brackets or line comments) should be handled by the editor for a source file of a particular language.
7//!
8//! Notably we do *not* assign a single language to a single file; in real world a single file can consist of multiple programming languages - HTML is a good example of that - and `language` crate tends to reflect that status quo in it's API.
9mod buffer;
10mod diagnostic_set;
11mod highlight_map;
12mod language_registry;
13pub mod language_settings;
14mod outline;
15pub mod proto;
16mod syntax_map;
17
18#[cfg(test)]
19mod buffer_tests;
20pub mod markdown;
21
22use anyhow::{anyhow, Context, Result};
23use async_trait::async_trait;
24use collections::{HashMap, HashSet};
25use gpui::{AppContext, AsyncAppContext, Model, Task};
26pub use highlight_map::HighlightMap;
27use lazy_static::lazy_static;
28use lsp::{CodeActionKind, LanguageServerBinary};
29use parking_lot::Mutex;
30use regex::Regex;
31use schemars::{
32 gen::SchemaGenerator,
33 schema::{InstanceType, Schema, SchemaObject},
34 JsonSchema,
35};
36use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
37use serde_json::Value;
38use std::{
39 any::Any,
40 cell::RefCell,
41 ffi::OsString,
42 fmt::Debug,
43 hash::Hash,
44 mem,
45 ops::Range,
46 path::{Path, PathBuf},
47 str,
48 sync::{
49 atomic::{AtomicU64, AtomicUsize, Ordering::SeqCst},
50 Arc,
51 },
52};
53use syntax_map::SyntaxSnapshot;
54use theme::SyntaxTheme;
55use tree_sitter::{self, wasmtime, Query, WasmStore};
56use util::http::HttpClient;
57
58pub use buffer::Operation;
59pub use buffer::*;
60pub use diagnostic_set::DiagnosticEntry;
61pub use language_registry::{
62 LanguageQueries, LanguageRegistry, LanguageServerBinaryStatus, PendingLanguageServer,
63 QUERY_FILENAME_PREFIXES,
64};
65pub use lsp::LanguageServerId;
66pub use outline::{Outline, OutlineItem};
67pub use syntax_map::{OwnedSyntaxLayer, SyntaxLayer};
68pub use text::LineEnding;
69pub use tree_sitter::{Parser, Tree};
70
71/// Initializes the `language` crate.
72///
73/// This should be called before making use of items from the create.
74pub fn init(cx: &mut AppContext) {
75 language_settings::init(cx);
76}
77
78thread_local! {
79 static PARSER: RefCell<Parser> = {
80 let mut parser = Parser::new();
81 parser.set_wasm_store(WasmStore::new(WASM_ENGINE.clone()).unwrap()).unwrap();
82 RefCell::new(parser)
83 };
84}
85
86lazy_static! {
87 static ref NEXT_LANGUAGE_ID: AtomicUsize = Default::default();
88 static ref NEXT_GRAMMAR_ID: AtomicUsize = Default::default();
89 static ref WASM_ENGINE: wasmtime::Engine = wasmtime::Engine::default();
90
91 /// A shared grammar for plain text, exposed for reuse by downstream crates.
92 pub static ref PLAIN_TEXT: Arc<Language> = Arc::new(Language::new(
93 LanguageConfig {
94 name: "Plain Text".into(),
95 ..Default::default()
96 },
97 None,
98 ));
99}
100
101/// Types that represent a position in a buffer, and can be converted into
102/// an LSP position, to send to a language server.
103pub trait ToLspPosition {
104 /// Converts the value into an LSP position.
105 fn to_lsp_position(self) -> lsp::Position;
106}
107
108/// A name of a language server.
109#[derive(Clone, Debug, PartialEq, Eq, Hash)]
110pub struct LanguageServerName(pub Arc<str>);
111#[derive(Debug, Clone, PartialEq, Eq, Hash)]
112
113pub struct Location {
114 pub buffer: Model<Buffer>,
115 pub range: Range<Anchor>,
116}
117
118/// Represents a Language Server, with certain cached sync properties.
119/// Uses [`LspAdapter`] under the hood, but calls all 'static' methods
120/// once at startup, and caches the results.
121pub struct CachedLspAdapter {
122 pub name: LanguageServerName,
123 pub short_name: &'static str,
124 pub disk_based_diagnostic_sources: Vec<String>,
125 pub disk_based_diagnostics_progress_token: Option<String>,
126 pub language_ids: HashMap<String, String>,
127 pub adapter: Arc<dyn LspAdapter>,
128 pub reinstall_attempt_count: AtomicU64,
129}
130
131impl CachedLspAdapter {
132 pub async fn new(adapter: Arc<dyn LspAdapter>) -> Arc<Self> {
133 let name = adapter.name();
134 let short_name = adapter.short_name();
135 let disk_based_diagnostic_sources = adapter.disk_based_diagnostic_sources();
136 let disk_based_diagnostics_progress_token = adapter.disk_based_diagnostics_progress_token();
137 let language_ids = adapter.language_ids();
138
139 Arc::new(CachedLspAdapter {
140 name,
141 short_name,
142 disk_based_diagnostic_sources,
143 disk_based_diagnostics_progress_token,
144 language_ids,
145 adapter,
146 reinstall_attempt_count: AtomicU64::new(0),
147 })
148 }
149
150 pub fn check_if_user_installed(
151 &self,
152 delegate: &Arc<dyn LspAdapterDelegate>,
153 cx: &mut AsyncAppContext,
154 ) -> Option<Task<Option<LanguageServerBinary>>> {
155 self.adapter.check_if_user_installed(delegate, cx)
156 }
157
158 pub async fn fetch_latest_server_version(
159 &self,
160 delegate: &dyn LspAdapterDelegate,
161 ) -> Result<Box<dyn 'static + Send + Any>> {
162 self.adapter.fetch_latest_server_version(delegate).await
163 }
164
165 pub fn will_fetch_server(
166 &self,
167 delegate: &Arc<dyn LspAdapterDelegate>,
168 cx: &mut AsyncAppContext,
169 ) -> Option<Task<Result<()>>> {
170 self.adapter.will_fetch_server(delegate, cx)
171 }
172
173 pub fn will_start_server(
174 &self,
175 delegate: &Arc<dyn LspAdapterDelegate>,
176 cx: &mut AsyncAppContext,
177 ) -> Option<Task<Result<()>>> {
178 self.adapter.will_start_server(delegate, cx)
179 }
180
181 pub async fn fetch_server_binary(
182 &self,
183 version: Box<dyn 'static + Send + Any>,
184 container_dir: PathBuf,
185 delegate: &dyn LspAdapterDelegate,
186 ) -> Result<LanguageServerBinary> {
187 self.adapter
188 .fetch_server_binary(version, container_dir, delegate)
189 .await
190 }
191
192 pub async fn cached_server_binary(
193 &self,
194 container_dir: PathBuf,
195 delegate: &dyn LspAdapterDelegate,
196 ) -> Option<LanguageServerBinary> {
197 self.adapter
198 .cached_server_binary(container_dir, delegate)
199 .await
200 }
201
202 pub fn can_be_reinstalled(&self) -> bool {
203 self.adapter.can_be_reinstalled()
204 }
205
206 pub async fn installation_test_binary(
207 &self,
208 container_dir: PathBuf,
209 ) -> Option<LanguageServerBinary> {
210 self.adapter.installation_test_binary(container_dir).await
211 }
212
213 pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
214 self.adapter.code_action_kinds()
215 }
216
217 pub fn workspace_configuration(&self, workspace_root: &Path, cx: &mut AppContext) -> Value {
218 self.adapter.workspace_configuration(workspace_root, cx)
219 }
220
221 pub fn process_diagnostics(&self, params: &mut lsp::PublishDiagnosticsParams) {
222 self.adapter.process_diagnostics(params)
223 }
224
225 pub async fn process_completion(&self, completion_item: &mut lsp::CompletionItem) {
226 self.adapter.process_completion(completion_item).await
227 }
228
229 pub async fn label_for_completion(
230 &self,
231 completion_item: &lsp::CompletionItem,
232 language: &Arc<Language>,
233 ) -> Option<CodeLabel> {
234 self.adapter
235 .label_for_completion(completion_item, language)
236 .await
237 }
238
239 pub async fn label_for_symbol(
240 &self,
241 name: &str,
242 kind: lsp::SymbolKind,
243 language: &Arc<Language>,
244 ) -> Option<CodeLabel> {
245 self.adapter.label_for_symbol(name, kind, language).await
246 }
247
248 pub fn prettier_plugins(&self) -> &[&'static str] {
249 self.adapter.prettier_plugins()
250 }
251}
252
253/// [`LspAdapterDelegate`] allows [`LspAdapter]` implementations to interface with the application
254// e.g. to display a notification or fetch data from the web.
255pub trait LspAdapterDelegate: Send + Sync {
256 fn show_notification(&self, message: &str, cx: &mut AppContext);
257 fn http_client(&self) -> Arc<dyn HttpClient>;
258 fn which_command(
259 &self,
260 command: OsString,
261 cx: &AppContext,
262 ) -> Task<Option<(PathBuf, HashMap<String, String>)>>;
263}
264
265#[async_trait]
266pub trait LspAdapter: 'static + Send + Sync {
267 fn name(&self) -> LanguageServerName;
268
269 fn short_name(&self) -> &'static str;
270
271 fn check_if_user_installed(
272 &self,
273 _: &Arc<dyn LspAdapterDelegate>,
274 _: &mut AsyncAppContext,
275 ) -> Option<Task<Option<LanguageServerBinary>>> {
276 None
277 }
278
279 async fn fetch_latest_server_version(
280 &self,
281 delegate: &dyn LspAdapterDelegate,
282 ) -> Result<Box<dyn 'static + Send + Any>>;
283
284 fn will_fetch_server(
285 &self,
286 _: &Arc<dyn LspAdapterDelegate>,
287 _: &mut AsyncAppContext,
288 ) -> Option<Task<Result<()>>> {
289 None
290 }
291
292 fn will_start_server(
293 &self,
294 _: &Arc<dyn LspAdapterDelegate>,
295 _: &mut AsyncAppContext,
296 ) -> Option<Task<Result<()>>> {
297 None
298 }
299
300 async fn fetch_server_binary(
301 &self,
302 version: Box<dyn 'static + Send + Any>,
303 container_dir: PathBuf,
304 delegate: &dyn LspAdapterDelegate,
305 ) -> Result<LanguageServerBinary>;
306
307 async fn cached_server_binary(
308 &self,
309 container_dir: PathBuf,
310 delegate: &dyn LspAdapterDelegate,
311 ) -> Option<LanguageServerBinary>;
312
313 /// Returns `true` if a language server can be reinstalled.
314 ///
315 /// If language server initialization fails, a reinstallation will be attempted unless the value returned from this method is `false`.
316 ///
317 /// Implementations that rely on software already installed on user's system
318 /// should have [`can_be_reinstalled`](Self::can_be_reinstalled) return `false`.
319 fn can_be_reinstalled(&self) -> bool {
320 true
321 }
322
323 async fn installation_test_binary(
324 &self,
325 container_dir: PathBuf,
326 ) -> Option<LanguageServerBinary>;
327
328 fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
329
330 /// A callback called for each [`lsp::CompletionItem`] obtained from LSP server.
331 /// Some LspAdapter implementations might want to modify the obtained item to
332 /// change how it's displayed.
333 async fn process_completion(&self, _: &mut lsp::CompletionItem) {}
334
335 async fn label_for_completion(
336 &self,
337 _: &lsp::CompletionItem,
338 _: &Arc<Language>,
339 ) -> Option<CodeLabel> {
340 None
341 }
342
343 async fn label_for_symbol(
344 &self,
345 _: &str,
346 _: lsp::SymbolKind,
347 _: &Arc<Language>,
348 ) -> Option<CodeLabel> {
349 None
350 }
351
352 /// Returns initialization options that are going to be sent to a LSP server as a part of [`lsp::InitializeParams`]
353 fn initialization_options(&self) -> Option<Value> {
354 None
355 }
356
357 fn workspace_configuration(&self, _workspace_root: &Path, _cx: &mut AppContext) -> Value {
358 serde_json::json!({})
359 }
360
361 /// Returns a list of code actions supported by a given LspAdapter
362 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
363 Some(vec![
364 CodeActionKind::EMPTY,
365 CodeActionKind::QUICKFIX,
366 CodeActionKind::REFACTOR,
367 CodeActionKind::REFACTOR_EXTRACT,
368 CodeActionKind::SOURCE,
369 ])
370 }
371
372 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
373 Default::default()
374 }
375
376 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
377 None
378 }
379
380 fn language_ids(&self) -> HashMap<String, String> {
381 Default::default()
382 }
383
384 fn prettier_plugins(&self) -> &[&'static str] {
385 &[]
386 }
387}
388
389#[derive(Clone, Debug, PartialEq, Eq)]
390pub struct CodeLabel {
391 /// The text to display.
392 pub text: String,
393 /// Syntax highlighting runs.
394 pub runs: Vec<(Range<usize>, HighlightId)>,
395 /// The portion of the text that should be used in fuzzy filtering.
396 pub filter_range: Range<usize>,
397}
398
399#[derive(Clone, Deserialize, JsonSchema)]
400pub struct LanguageConfig {
401 /// Human-readable name of the language.
402 pub name: Arc<str>,
403 // The name of the grammar in a WASM bundle (experimental).
404 pub grammar: Option<Arc<str>>,
405 /// The criteria for matching this language to a given file.
406 #[serde(flatten)]
407 pub matcher: LanguageMatcher,
408 /// List of bracket types in a language.
409 #[serde(default)]
410 #[schemars(schema_with = "bracket_pair_config_json_schema")]
411 pub brackets: BracketPairConfig,
412 /// If set to true, auto indentation uses last non empty line to determine
413 /// the indentation level for a new line.
414 #[serde(default = "auto_indent_using_last_non_empty_line_default")]
415 pub auto_indent_using_last_non_empty_line: bool,
416 /// A regex that is used to determine whether the indentation level should be
417 /// increased in the following line.
418 #[serde(default, deserialize_with = "deserialize_regex")]
419 #[schemars(schema_with = "regex_json_schema")]
420 pub increase_indent_pattern: Option<Regex>,
421 /// A regex that is used to determine whether the indentation level should be
422 /// decreased in the following line.
423 #[serde(default, deserialize_with = "deserialize_regex")]
424 #[schemars(schema_with = "regex_json_schema")]
425 pub decrease_indent_pattern: Option<Regex>,
426 /// A list of characters that trigger the automatic insertion of a closing
427 /// bracket when they immediately precede the point where an opening
428 /// bracket is inserted.
429 #[serde(default)]
430 pub autoclose_before: String,
431 /// A placeholder used internally by Semantic Index.
432 #[serde(default)]
433 pub collapsed_placeholder: String,
434 /// A line comment string that is inserted in e.g. `toggle comments` action.
435 /// A language can have multiple flavours of line comments. All of the provided line comments are
436 /// used for comment continuations on the next line, but only the first one is used for Editor::ToggleComments.
437 #[serde(default)]
438 pub line_comments: Vec<Arc<str>>,
439 /// Starting and closing characters of a block comment.
440 #[serde(default)]
441 pub block_comment: Option<(Arc<str>, Arc<str>)>,
442 /// A list of language servers that are allowed to run on subranges of a given language.
443 #[serde(default)]
444 pub scope_opt_in_language_servers: Vec<String>,
445 #[serde(default)]
446 pub overrides: HashMap<String, LanguageConfigOverride>,
447 /// A list of characters that Zed should treat as word characters for the
448 /// purpose of features that operate on word boundaries, like 'move to next word end'
449 /// or a whole-word search in buffer search.
450 #[serde(default)]
451 pub word_characters: HashSet<char>,
452 /// The name of a Prettier parser that should be used for this language.
453 #[serde(default)]
454 pub prettier_parser_name: Option<String>,
455}
456
457#[derive(Clone, Debug, Serialize, Deserialize, Default, JsonSchema)]
458pub struct LanguageMatcher {
459 /// Given a list of `LanguageConfig`'s, the language of a file can be determined based on the path extension matching any of the `path_suffixes`.
460 #[serde(default)]
461 pub path_suffixes: Vec<String>,
462 /// A regex pattern that determines whether the language should be assigned to a file or not.
463 #[serde(
464 default,
465 serialize_with = "serialize_regex",
466 deserialize_with = "deserialize_regex"
467 )]
468 #[schemars(schema_with = "regex_json_schema")]
469 pub first_line_pattern: Option<Regex>,
470}
471
472/// Represents a language for the given range. Some languages (e.g. HTML)
473/// interleave several languages together, thus a single buffer might actually contain
474/// several nested scopes.
475#[derive(Clone, Debug)]
476pub struct LanguageScope {
477 language: Arc<Language>,
478 override_id: Option<u32>,
479}
480
481#[derive(Clone, Deserialize, Default, Debug, JsonSchema)]
482pub struct LanguageConfigOverride {
483 #[serde(default)]
484 pub line_comments: Override<Vec<Arc<str>>>,
485 #[serde(default)]
486 pub block_comment: Override<(Arc<str>, Arc<str>)>,
487 #[serde(skip_deserializing)]
488 #[schemars(skip)]
489 pub disabled_bracket_ixs: Vec<u16>,
490 #[serde(default)]
491 pub word_characters: Override<HashSet<char>>,
492 #[serde(default)]
493 pub opt_into_language_servers: Vec<String>,
494}
495
496#[derive(Clone, Deserialize, Debug, Serialize, JsonSchema)]
497#[serde(untagged)]
498pub enum Override<T> {
499 Remove { remove: bool },
500 Set(T),
501}
502
503impl<T> Default for Override<T> {
504 fn default() -> Self {
505 Override::Remove { remove: false }
506 }
507}
508
509impl<T> Override<T> {
510 fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
511 match this {
512 Some(Self::Set(value)) => Some(value),
513 Some(Self::Remove { remove: true }) => None,
514 Some(Self::Remove { remove: false }) | None => original,
515 }
516 }
517}
518
519impl Default for LanguageConfig {
520 fn default() -> Self {
521 Self {
522 name: "".into(),
523 grammar: None,
524 matcher: LanguageMatcher::default(),
525 brackets: Default::default(),
526 auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
527 increase_indent_pattern: Default::default(),
528 decrease_indent_pattern: Default::default(),
529 autoclose_before: Default::default(),
530 line_comments: Default::default(),
531 block_comment: Default::default(),
532 scope_opt_in_language_servers: Default::default(),
533 overrides: Default::default(),
534 word_characters: Default::default(),
535 prettier_parser_name: None,
536 collapsed_placeholder: Default::default(),
537 }
538 }
539}
540
541fn auto_indent_using_last_non_empty_line_default() -> bool {
542 true
543}
544
545fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
546 let source = Option::<String>::deserialize(d)?;
547 if let Some(source) = source {
548 Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
549 } else {
550 Ok(None)
551 }
552}
553
554fn regex_json_schema(_: &mut SchemaGenerator) -> Schema {
555 Schema::Object(SchemaObject {
556 instance_type: Some(InstanceType::String.into()),
557 ..Default::default()
558 })
559}
560
561fn serialize_regex<S>(regex: &Option<Regex>, serializer: S) -> Result<S::Ok, S::Error>
562where
563 S: Serializer,
564{
565 match regex {
566 Some(regex) => serializer.serialize_str(regex.as_str()),
567 None => serializer.serialize_none(),
568 }
569}
570
571#[doc(hidden)]
572#[cfg(any(test, feature = "test-support"))]
573pub struct FakeLspAdapter {
574 pub name: &'static str,
575 pub initialization_options: Option<Value>,
576 pub capabilities: lsp::ServerCapabilities,
577 pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
578 pub disk_based_diagnostics_progress_token: Option<String>,
579 pub disk_based_diagnostics_sources: Vec<String>,
580 pub prettier_plugins: Vec<&'static str>,
581}
582
583/// Configuration of handling bracket pairs for a given language.
584///
585/// This struct includes settings for defining which pairs of characters are considered brackets and
586/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
587#[derive(Clone, Debug, Default, JsonSchema)]
588pub struct BracketPairConfig {
589 /// A list of character pairs that should be treated as brackets in the context of a given language.
590 pub pairs: Vec<BracketPair>,
591 /// A list of tree-sitter scopes for which a given bracket should not be active.
592 /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
593 #[schemars(skip)]
594 pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
595}
596
597fn bracket_pair_config_json_schema(gen: &mut SchemaGenerator) -> Schema {
598 Option::<Vec<BracketPairContent>>::json_schema(gen)
599}
600
601#[derive(Deserialize, JsonSchema)]
602pub struct BracketPairContent {
603 #[serde(flatten)]
604 pub bracket_pair: BracketPair,
605 #[serde(default)]
606 pub not_in: Vec<String>,
607}
608
609impl<'de> Deserialize<'de> for BracketPairConfig {
610 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
611 where
612 D: Deserializer<'de>,
613 {
614 let result = Vec::<BracketPairContent>::deserialize(deserializer)?;
615 let mut brackets = Vec::with_capacity(result.len());
616 let mut disabled_scopes_by_bracket_ix = Vec::with_capacity(result.len());
617 for entry in result {
618 brackets.push(entry.bracket_pair);
619 disabled_scopes_by_bracket_ix.push(entry.not_in);
620 }
621
622 Ok(BracketPairConfig {
623 pairs: brackets,
624 disabled_scopes_by_bracket_ix,
625 })
626 }
627}
628
629/// Describes a single bracket pair and how an editor should react to e.g. inserting
630/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
631#[derive(Clone, Debug, Default, Deserialize, PartialEq, JsonSchema)]
632pub struct BracketPair {
633 /// Starting substring for a bracket.
634 pub start: String,
635 /// Ending substring for a bracket.
636 pub end: String,
637 /// True if `end` should be automatically inserted right after `start` characters.
638 pub close: bool,
639 /// True if an extra newline should be inserted while the cursor is in the middle
640 /// of that bracket pair.
641 pub newline: bool,
642}
643
644#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
645pub(crate) struct LanguageId(usize);
646
647impl LanguageId {
648 pub(crate) fn new() -> Self {
649 Self(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst))
650 }
651}
652
653pub struct Language {
654 pub(crate) id: LanguageId,
655 pub(crate) config: LanguageConfig,
656 pub(crate) grammar: Option<Arc<Grammar>>,
657 pub(crate) adapters: Vec<Arc<CachedLspAdapter>>,
658
659 #[cfg(any(test, feature = "test-support"))]
660 fake_adapter: Option<(
661 futures::channel::mpsc::UnboundedSender<lsp::FakeLanguageServer>,
662 Arc<FakeLspAdapter>,
663 )>,
664}
665
666#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
667pub struct GrammarId(pub usize);
668
669impl GrammarId {
670 pub(crate) fn new() -> Self {
671 Self(NEXT_GRAMMAR_ID.fetch_add(1, SeqCst))
672 }
673}
674
675pub struct Grammar {
676 id: GrammarId,
677 pub ts_language: tree_sitter::Language,
678 pub(crate) error_query: Query,
679 pub(crate) highlights_query: Option<Query>,
680 pub(crate) brackets_config: Option<BracketConfig>,
681 pub(crate) redactions_config: Option<RedactionConfig>,
682 pub(crate) indents_config: Option<IndentConfig>,
683 pub outline_config: Option<OutlineConfig>,
684 pub embedding_config: Option<EmbeddingConfig>,
685 pub(crate) injection_config: Option<InjectionConfig>,
686 pub(crate) override_config: Option<OverrideConfig>,
687 pub(crate) highlight_map: Mutex<HighlightMap>,
688}
689
690struct IndentConfig {
691 query: Query,
692 indent_capture_ix: u32,
693 start_capture_ix: Option<u32>,
694 end_capture_ix: Option<u32>,
695 outdent_capture_ix: Option<u32>,
696}
697
698pub struct OutlineConfig {
699 pub query: Query,
700 pub item_capture_ix: u32,
701 pub name_capture_ix: u32,
702 pub context_capture_ix: Option<u32>,
703 pub extra_context_capture_ix: Option<u32>,
704}
705
706#[derive(Debug)]
707pub struct EmbeddingConfig {
708 pub query: Query,
709 pub item_capture_ix: u32,
710 pub name_capture_ix: Option<u32>,
711 pub context_capture_ix: Option<u32>,
712 pub collapse_capture_ix: Option<u32>,
713 pub keep_capture_ix: Option<u32>,
714}
715
716struct InjectionConfig {
717 query: Query,
718 content_capture_ix: u32,
719 language_capture_ix: Option<u32>,
720 patterns: Vec<InjectionPatternConfig>,
721}
722
723struct RedactionConfig {
724 pub query: Query,
725 pub redaction_capture_ix: u32,
726}
727
728struct OverrideConfig {
729 query: Query,
730 values: HashMap<u32, (String, LanguageConfigOverride)>,
731}
732
733#[derive(Default, Clone)]
734struct InjectionPatternConfig {
735 language: Option<Box<str>>,
736 combined: bool,
737}
738
739struct BracketConfig {
740 query: Query,
741 open_capture_ix: u32,
742 close_capture_ix: u32,
743}
744
745impl Language {
746 pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
747 Self::new_with_id(
748 LanguageId(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst)),
749 config,
750 ts_language,
751 )
752 }
753
754 fn new_with_id(
755 id: LanguageId,
756 config: LanguageConfig,
757 ts_language: Option<tree_sitter::Language>,
758 ) -> Self {
759 Self {
760 id,
761 config,
762 grammar: ts_language.map(|ts_language| {
763 Arc::new(Grammar {
764 id: GrammarId::new(),
765 highlights_query: None,
766 brackets_config: None,
767 outline_config: None,
768 embedding_config: None,
769 indents_config: None,
770 injection_config: None,
771 override_config: None,
772 redactions_config: None,
773 error_query: Query::new(&ts_language, "(ERROR) @error").unwrap(),
774 ts_language,
775 highlight_map: Default::default(),
776 })
777 }),
778 adapters: Vec::new(),
779
780 #[cfg(any(test, feature = "test-support"))]
781 fake_adapter: None,
782 }
783 }
784
785 pub fn lsp_adapters(&self) -> &[Arc<CachedLspAdapter>] {
786 &self.adapters
787 }
788
789 pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
790 if let Some(query) = queries.highlights {
791 self = self
792 .with_highlights_query(query.as_ref())
793 .context("Error loading highlights query")?;
794 }
795 if let Some(query) = queries.brackets {
796 self = self
797 .with_brackets_query(query.as_ref())
798 .context("Error loading brackets query")?;
799 }
800 if let Some(query) = queries.indents {
801 self = self
802 .with_indents_query(query.as_ref())
803 .context("Error loading indents query")?;
804 }
805 if let Some(query) = queries.outline {
806 self = self
807 .with_outline_query(query.as_ref())
808 .context("Error loading outline query")?;
809 }
810 if let Some(query) = queries.embedding {
811 self = self
812 .with_embedding_query(query.as_ref())
813 .context("Error loading embedding query")?;
814 }
815 if let Some(query) = queries.injections {
816 self = self
817 .with_injection_query(query.as_ref())
818 .context("Error loading injection query")?;
819 }
820 if let Some(query) = queries.overrides {
821 self = self
822 .with_override_query(query.as_ref())
823 .context("Error loading override query")?;
824 }
825 if let Some(query) = queries.redactions {
826 self = self
827 .with_redaction_query(query.as_ref())
828 .context("Error loading redaction query")?;
829 }
830 Ok(self)
831 }
832
833 pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
834 let grammar = self.grammar_mut();
835 grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
836 Ok(self)
837 }
838
839 pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
840 let grammar = self.grammar_mut();
841 let query = Query::new(&grammar.ts_language, source)?;
842 let mut item_capture_ix = None;
843 let mut name_capture_ix = None;
844 let mut context_capture_ix = None;
845 let mut extra_context_capture_ix = None;
846 get_capture_indices(
847 &query,
848 &mut [
849 ("item", &mut item_capture_ix),
850 ("name", &mut name_capture_ix),
851 ("context", &mut context_capture_ix),
852 ("context.extra", &mut extra_context_capture_ix),
853 ],
854 );
855 if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
856 grammar.outline_config = Some(OutlineConfig {
857 query,
858 item_capture_ix,
859 name_capture_ix,
860 context_capture_ix,
861 extra_context_capture_ix,
862 });
863 }
864 Ok(self)
865 }
866
867 pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
868 let grammar = self.grammar_mut();
869 let query = Query::new(&grammar.ts_language, source)?;
870 let mut item_capture_ix = None;
871 let mut name_capture_ix = None;
872 let mut context_capture_ix = None;
873 let mut collapse_capture_ix = None;
874 let mut keep_capture_ix = None;
875 get_capture_indices(
876 &query,
877 &mut [
878 ("item", &mut item_capture_ix),
879 ("name", &mut name_capture_ix),
880 ("context", &mut context_capture_ix),
881 ("keep", &mut keep_capture_ix),
882 ("collapse", &mut collapse_capture_ix),
883 ],
884 );
885 if let Some(item_capture_ix) = item_capture_ix {
886 grammar.embedding_config = Some(EmbeddingConfig {
887 query,
888 item_capture_ix,
889 name_capture_ix,
890 context_capture_ix,
891 collapse_capture_ix,
892 keep_capture_ix,
893 });
894 }
895 Ok(self)
896 }
897
898 pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
899 let grammar = self.grammar_mut();
900 let query = Query::new(&grammar.ts_language, source)?;
901 let mut open_capture_ix = None;
902 let mut close_capture_ix = None;
903 get_capture_indices(
904 &query,
905 &mut [
906 ("open", &mut open_capture_ix),
907 ("close", &mut close_capture_ix),
908 ],
909 );
910 if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
911 grammar.brackets_config = Some(BracketConfig {
912 query,
913 open_capture_ix,
914 close_capture_ix,
915 });
916 }
917 Ok(self)
918 }
919
920 pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
921 let grammar = self.grammar_mut();
922 let query = Query::new(&grammar.ts_language, source)?;
923 let mut indent_capture_ix = None;
924 let mut start_capture_ix = None;
925 let mut end_capture_ix = None;
926 let mut outdent_capture_ix = None;
927 get_capture_indices(
928 &query,
929 &mut [
930 ("indent", &mut indent_capture_ix),
931 ("start", &mut start_capture_ix),
932 ("end", &mut end_capture_ix),
933 ("outdent", &mut outdent_capture_ix),
934 ],
935 );
936 if let Some(indent_capture_ix) = indent_capture_ix {
937 grammar.indents_config = Some(IndentConfig {
938 query,
939 indent_capture_ix,
940 start_capture_ix,
941 end_capture_ix,
942 outdent_capture_ix,
943 });
944 }
945 Ok(self)
946 }
947
948 pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
949 let grammar = self.grammar_mut();
950 let query = Query::new(&grammar.ts_language, source)?;
951 let mut language_capture_ix = None;
952 let mut content_capture_ix = None;
953 get_capture_indices(
954 &query,
955 &mut [
956 ("language", &mut language_capture_ix),
957 ("content", &mut content_capture_ix),
958 ],
959 );
960 let patterns = (0..query.pattern_count())
961 .map(|ix| {
962 let mut config = InjectionPatternConfig::default();
963 for setting in query.property_settings(ix) {
964 match setting.key.as_ref() {
965 "language" => {
966 config.language = setting.value.clone();
967 }
968 "combined" => {
969 config.combined = true;
970 }
971 _ => {}
972 }
973 }
974 config
975 })
976 .collect();
977 if let Some(content_capture_ix) = content_capture_ix {
978 grammar.injection_config = Some(InjectionConfig {
979 query,
980 language_capture_ix,
981 content_capture_ix,
982 patterns,
983 });
984 }
985 Ok(self)
986 }
987
988 pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
989 let query = Query::new(&self.grammar_mut().ts_language, source)?;
990
991 let mut override_configs_by_id = HashMap::default();
992 for (ix, name) in query.capture_names().iter().enumerate() {
993 if !name.starts_with('_') {
994 let value = self.config.overrides.remove(*name).unwrap_or_default();
995 for server_name in &value.opt_into_language_servers {
996 if !self
997 .config
998 .scope_opt_in_language_servers
999 .contains(server_name)
1000 {
1001 util::debug_panic!("Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server");
1002 }
1003 }
1004
1005 override_configs_by_id.insert(ix as u32, (name.to_string(), value));
1006 }
1007 }
1008
1009 if !self.config.overrides.is_empty() {
1010 let keys = self.config.overrides.keys().collect::<Vec<_>>();
1011 Err(anyhow!(
1012 "language {:?} has overrides in config not in query: {keys:?}",
1013 self.config.name
1014 ))?;
1015 }
1016
1017 for disabled_scope_name in self
1018 .config
1019 .brackets
1020 .disabled_scopes_by_bracket_ix
1021 .iter()
1022 .flatten()
1023 {
1024 if !override_configs_by_id
1025 .values()
1026 .any(|(scope_name, _)| scope_name == disabled_scope_name)
1027 {
1028 Err(anyhow!(
1029 "language {:?} has overrides in config not in query: {disabled_scope_name:?}",
1030 self.config.name
1031 ))?;
1032 }
1033 }
1034
1035 for (name, override_config) in override_configs_by_id.values_mut() {
1036 override_config.disabled_bracket_ixs = self
1037 .config
1038 .brackets
1039 .disabled_scopes_by_bracket_ix
1040 .iter()
1041 .enumerate()
1042 .filter_map(|(ix, disabled_scope_names)| {
1043 if disabled_scope_names.contains(name) {
1044 Some(ix as u16)
1045 } else {
1046 None
1047 }
1048 })
1049 .collect();
1050 }
1051
1052 self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1053 self.grammar_mut().override_config = Some(OverrideConfig {
1054 query,
1055 values: override_configs_by_id,
1056 });
1057 Ok(self)
1058 }
1059
1060 pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1061 let grammar = self.grammar_mut();
1062 let query = Query::new(&grammar.ts_language, source)?;
1063 let mut redaction_capture_ix = None;
1064 get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1065
1066 if let Some(redaction_capture_ix) = redaction_capture_ix {
1067 grammar.redactions_config = Some(RedactionConfig {
1068 query,
1069 redaction_capture_ix,
1070 });
1071 }
1072
1073 Ok(self)
1074 }
1075
1076 fn grammar_mut(&mut self) -> &mut Grammar {
1077 Arc::get_mut(self.grammar.as_mut().unwrap()).unwrap()
1078 }
1079
1080 pub async fn with_lsp_adapters(mut self, lsp_adapters: Vec<Arc<dyn LspAdapter>>) -> Self {
1081 for adapter in lsp_adapters {
1082 self.adapters.push(CachedLspAdapter::new(adapter).await);
1083 }
1084 self
1085 }
1086
1087 #[cfg(any(test, feature = "test-support"))]
1088 pub async fn set_fake_lsp_adapter(
1089 &mut self,
1090 fake_lsp_adapter: Arc<FakeLspAdapter>,
1091 ) -> futures::channel::mpsc::UnboundedReceiver<lsp::FakeLanguageServer> {
1092 let (servers_tx, servers_rx) = futures::channel::mpsc::unbounded();
1093 self.fake_adapter = Some((servers_tx, fake_lsp_adapter.clone()));
1094 let adapter = CachedLspAdapter::new(Arc::new(fake_lsp_adapter)).await;
1095 self.adapters = vec![adapter];
1096 servers_rx
1097 }
1098
1099 pub fn name(&self) -> Arc<str> {
1100 self.config.name.clone()
1101 }
1102
1103 pub async fn disk_based_diagnostic_sources(&self) -> &[String] {
1104 match self.adapters.first().as_ref() {
1105 Some(adapter) => &adapter.disk_based_diagnostic_sources,
1106 None => &[],
1107 }
1108 }
1109
1110 pub async fn disk_based_diagnostics_progress_token(&self) -> Option<&str> {
1111 for adapter in &self.adapters {
1112 let token = adapter.disk_based_diagnostics_progress_token.as_deref();
1113 if token.is_some() {
1114 return token;
1115 }
1116 }
1117
1118 None
1119 }
1120
1121 pub async fn process_completion(self: &Arc<Self>, completion: &mut lsp::CompletionItem) {
1122 for adapter in &self.adapters {
1123 adapter.process_completion(completion).await;
1124 }
1125 }
1126
1127 pub async fn label_for_completion(
1128 self: &Arc<Self>,
1129 completion: &lsp::CompletionItem,
1130 ) -> Option<CodeLabel> {
1131 self.adapters
1132 .first()
1133 .as_ref()?
1134 .label_for_completion(completion, self)
1135 .await
1136 }
1137
1138 pub async fn label_for_symbol(
1139 self: &Arc<Self>,
1140 name: &str,
1141 kind: lsp::SymbolKind,
1142 ) -> Option<CodeLabel> {
1143 self.adapters
1144 .first()
1145 .as_ref()?
1146 .label_for_symbol(name, kind, self)
1147 .await
1148 }
1149
1150 pub fn highlight_text<'a>(
1151 self: &'a Arc<Self>,
1152 text: &'a Rope,
1153 range: Range<usize>,
1154 ) -> Vec<(Range<usize>, HighlightId)> {
1155 let mut result = Vec::new();
1156 if let Some(grammar) = &self.grammar {
1157 let tree = grammar.parse_text(text, None);
1158 let captures =
1159 SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1160 grammar.highlights_query.as_ref()
1161 });
1162 let highlight_maps = vec![grammar.highlight_map()];
1163 let mut offset = 0;
1164 for chunk in BufferChunks::new(text, range, Some((captures, highlight_maps)), vec![]) {
1165 let end_offset = offset + chunk.text.len();
1166 if let Some(highlight_id) = chunk.syntax_highlight_id {
1167 if !highlight_id.is_default() {
1168 result.push((offset..end_offset, highlight_id));
1169 }
1170 }
1171 offset = end_offset;
1172 }
1173 }
1174 result
1175 }
1176
1177 pub fn path_suffixes(&self) -> &[String] {
1178 &self.config.matcher.path_suffixes
1179 }
1180
1181 pub fn should_autoclose_before(&self, c: char) -> bool {
1182 c.is_whitespace() || self.config.autoclose_before.contains(c)
1183 }
1184
1185 pub fn set_theme(&self, theme: &SyntaxTheme) {
1186 if let Some(grammar) = self.grammar.as_ref() {
1187 if let Some(highlights_query) = &grammar.highlights_query {
1188 *grammar.highlight_map.lock() =
1189 HighlightMap::new(highlights_query.capture_names(), theme);
1190 }
1191 }
1192 }
1193
1194 pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1195 self.grammar.as_ref()
1196 }
1197
1198 pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1199 LanguageScope {
1200 language: self.clone(),
1201 override_id: None,
1202 }
1203 }
1204
1205 pub fn prettier_parser_name(&self) -> Option<&str> {
1206 self.config.prettier_parser_name.as_deref()
1207 }
1208}
1209
1210impl LanguageScope {
1211 pub fn collapsed_placeholder(&self) -> &str {
1212 self.language.config.collapsed_placeholder.as_ref()
1213 }
1214
1215 /// Returns line prefix that is inserted in e.g. line continuations or
1216 /// in `toggle comments` action.
1217 pub fn line_comment_prefixes(&self) -> Option<&Vec<Arc<str>>> {
1218 Override::as_option(
1219 self.config_override().map(|o| &o.line_comments),
1220 Some(&self.language.config.line_comments),
1221 )
1222 }
1223
1224 pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1225 Override::as_option(
1226 self.config_override().map(|o| &o.block_comment),
1227 self.language.config.block_comment.as_ref(),
1228 )
1229 .map(|e| (&e.0, &e.1))
1230 }
1231
1232 /// Returns a list of language-specific word characters.
1233 ///
1234 /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1235 /// the purpose of actions like 'move to next word end` or whole-word search.
1236 /// It additionally accounts for language's additional word characters.
1237 pub fn word_characters(&self) -> Option<&HashSet<char>> {
1238 Override::as_option(
1239 self.config_override().map(|o| &o.word_characters),
1240 Some(&self.language.config.word_characters),
1241 )
1242 }
1243
1244 /// Returns a list of bracket pairs for a given language with an additional
1245 /// piece of information about whether the particular bracket pair is currently active for a given language.
1246 pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1247 let mut disabled_ids = self
1248 .config_override()
1249 .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1250 self.language
1251 .config
1252 .brackets
1253 .pairs
1254 .iter()
1255 .enumerate()
1256 .map(move |(ix, bracket)| {
1257 let mut is_enabled = true;
1258 if let Some(next_disabled_ix) = disabled_ids.first() {
1259 if ix == *next_disabled_ix as usize {
1260 disabled_ids = &disabled_ids[1..];
1261 is_enabled = false;
1262 }
1263 }
1264 (bracket, is_enabled)
1265 })
1266 }
1267
1268 pub fn should_autoclose_before(&self, c: char) -> bool {
1269 c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1270 }
1271
1272 pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1273 let config = &self.language.config;
1274 let opt_in_servers = &config.scope_opt_in_language_servers;
1275 if opt_in_servers.iter().any(|o| *o == *name.0) {
1276 if let Some(over) = self.config_override() {
1277 over.opt_into_language_servers.iter().any(|o| *o == *name.0)
1278 } else {
1279 false
1280 }
1281 } else {
1282 true
1283 }
1284 }
1285
1286 fn config_override(&self) -> Option<&LanguageConfigOverride> {
1287 let id = self.override_id?;
1288 let grammar = self.language.grammar.as_ref()?;
1289 let override_config = grammar.override_config.as_ref()?;
1290 override_config.values.get(&id).map(|e| &e.1)
1291 }
1292}
1293
1294impl Hash for Language {
1295 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1296 self.id.hash(state)
1297 }
1298}
1299
1300impl PartialEq for Language {
1301 fn eq(&self, other: &Self) -> bool {
1302 self.id.eq(&other.id)
1303 }
1304}
1305
1306impl Eq for Language {}
1307
1308impl Debug for Language {
1309 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1310 f.debug_struct("Language")
1311 .field("name", &self.config.name)
1312 .finish()
1313 }
1314}
1315
1316impl Grammar {
1317 pub fn id(&self) -> GrammarId {
1318 self.id
1319 }
1320
1321 fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1322 PARSER.with(|parser| {
1323 let mut parser = parser.borrow_mut();
1324 parser
1325 .set_language(&self.ts_language)
1326 .expect("incompatible grammar");
1327 let mut chunks = text.chunks_in_range(0..text.len());
1328 parser
1329 .parse_with(
1330 &mut move |offset, _| {
1331 chunks.seek(offset);
1332 chunks.next().unwrap_or("").as_bytes()
1333 },
1334 old_tree.as_ref(),
1335 )
1336 .unwrap()
1337 })
1338 }
1339
1340 pub fn highlight_map(&self) -> HighlightMap {
1341 self.highlight_map.lock().clone()
1342 }
1343
1344 pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1345 let capture_id = self
1346 .highlights_query
1347 .as_ref()?
1348 .capture_index_for_name(name)?;
1349 Some(self.highlight_map.lock().get(capture_id))
1350 }
1351}
1352
1353impl CodeLabel {
1354 pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1355 let mut result = Self {
1356 runs: Vec::new(),
1357 filter_range: 0..text.len(),
1358 text,
1359 };
1360 if let Some(filter_text) = filter_text {
1361 if let Some(ix) = result.text.find(filter_text) {
1362 result.filter_range = ix..ix + filter_text.len();
1363 }
1364 }
1365 result
1366 }
1367}
1368
1369impl Ord for LanguageMatcher {
1370 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1371 self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
1372 self.first_line_pattern
1373 .as_ref()
1374 .map(Regex::as_str)
1375 .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
1376 })
1377 }
1378}
1379
1380impl PartialOrd for LanguageMatcher {
1381 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1382 Some(self.cmp(other))
1383 }
1384}
1385
1386impl Eq for LanguageMatcher {}
1387
1388impl PartialEq for LanguageMatcher {
1389 fn eq(&self, other: &Self) -> bool {
1390 self.path_suffixes == other.path_suffixes
1391 && self.first_line_pattern.as_ref().map(Regex::as_str)
1392 == other.first_line_pattern.as_ref().map(Regex::as_str)
1393 }
1394}
1395
1396#[cfg(any(test, feature = "test-support"))]
1397impl Default for FakeLspAdapter {
1398 fn default() -> Self {
1399 Self {
1400 name: "the-fake-language-server",
1401 capabilities: lsp::LanguageServer::full_capabilities(),
1402 initializer: None,
1403 disk_based_diagnostics_progress_token: None,
1404 initialization_options: None,
1405 disk_based_diagnostics_sources: Vec::new(),
1406 prettier_plugins: Vec::new(),
1407 }
1408 }
1409}
1410
1411#[cfg(any(test, feature = "test-support"))]
1412#[async_trait]
1413impl LspAdapter for Arc<FakeLspAdapter> {
1414 fn name(&self) -> LanguageServerName {
1415 LanguageServerName(self.name.into())
1416 }
1417
1418 fn short_name(&self) -> &'static str {
1419 "FakeLspAdapter"
1420 }
1421
1422 async fn fetch_latest_server_version(
1423 &self,
1424 _: &dyn LspAdapterDelegate,
1425 ) -> Result<Box<dyn 'static + Send + Any>> {
1426 unreachable!();
1427 }
1428
1429 async fn fetch_server_binary(
1430 &self,
1431 _: Box<dyn 'static + Send + Any>,
1432 _: PathBuf,
1433 _: &dyn LspAdapterDelegate,
1434 ) -> Result<LanguageServerBinary> {
1435 unreachable!();
1436 }
1437
1438 async fn cached_server_binary(
1439 &self,
1440 _: PathBuf,
1441 _: &dyn LspAdapterDelegate,
1442 ) -> Option<LanguageServerBinary> {
1443 unreachable!();
1444 }
1445
1446 async fn installation_test_binary(&self, _: PathBuf) -> Option<LanguageServerBinary> {
1447 unreachable!();
1448 }
1449
1450 fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
1451
1452 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
1453 self.disk_based_diagnostics_sources.clone()
1454 }
1455
1456 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
1457 self.disk_based_diagnostics_progress_token.clone()
1458 }
1459
1460 fn initialization_options(&self) -> Option<Value> {
1461 self.initialization_options.clone()
1462 }
1463
1464 fn prettier_plugins(&self) -> &[&'static str] {
1465 &self.prettier_plugins
1466 }
1467}
1468
1469fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
1470 for (ix, name) in query.capture_names().iter().enumerate() {
1471 for (capture_name, index) in captures.iter_mut() {
1472 if capture_name == name {
1473 **index = Some(ix as u32);
1474 break;
1475 }
1476 }
1477 }
1478}
1479
1480pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
1481 lsp::Position::new(point.row, point.column)
1482}
1483
1484pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
1485 Unclipped(PointUtf16::new(point.line, point.character))
1486}
1487
1488pub fn range_to_lsp(range: Range<PointUtf16>) -> lsp::Range {
1489 lsp::Range {
1490 start: point_to_lsp(range.start),
1491 end: point_to_lsp(range.end),
1492 }
1493}
1494
1495pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
1496 let mut start = point_from_lsp(range.start);
1497 let mut end = point_from_lsp(range.end);
1498 if start > end {
1499 mem::swap(&mut start, &mut end);
1500 }
1501 start..end
1502}
1503
1504#[cfg(test)]
1505mod tests {
1506 use super::*;
1507 use gpui::TestAppContext;
1508
1509 #[gpui::test(iterations = 10)]
1510 async fn test_first_line_pattern(cx: &mut TestAppContext) {
1511 let mut languages = LanguageRegistry::test();
1512
1513 languages.set_executor(cx.executor());
1514 let languages = Arc::new(languages);
1515 languages.register_test_language(LanguageConfig {
1516 name: "JavaScript".into(),
1517 matcher: LanguageMatcher {
1518 path_suffixes: vec!["js".into()],
1519 first_line_pattern: Some(Regex::new(r"\bnode\b").unwrap()),
1520 },
1521 ..Default::default()
1522 });
1523
1524 languages
1525 .language_for_file("the/script", None)
1526 .await
1527 .unwrap_err();
1528 languages
1529 .language_for_file("the/script", Some(&"nothing".into()))
1530 .await
1531 .unwrap_err();
1532 assert_eq!(
1533 languages
1534 .language_for_file("the/script", Some(&"#!/bin/env node".into()))
1535 .await
1536 .unwrap()
1537 .name()
1538 .as_ref(),
1539 "JavaScript"
1540 );
1541 }
1542
1543 #[gpui::test(iterations = 10)]
1544 async fn test_language_loading(cx: &mut TestAppContext) {
1545 let mut languages = LanguageRegistry::test();
1546 languages.set_executor(cx.executor());
1547 let languages = Arc::new(languages);
1548 languages.register_native_grammars([
1549 ("json", tree_sitter_json::language()),
1550 ("rust", tree_sitter_rust::language()),
1551 ]);
1552 languages.register_test_language(LanguageConfig {
1553 name: "JSON".into(),
1554 grammar: Some("json".into()),
1555 matcher: LanguageMatcher {
1556 path_suffixes: vec!["json".into()],
1557 ..Default::default()
1558 },
1559 ..Default::default()
1560 });
1561 languages.register_test_language(LanguageConfig {
1562 name: "Rust".into(),
1563 grammar: Some("rust".into()),
1564 matcher: LanguageMatcher {
1565 path_suffixes: vec!["rs".into()],
1566 ..Default::default()
1567 },
1568 ..Default::default()
1569 });
1570 assert_eq!(
1571 languages.language_names(),
1572 &[
1573 "JSON".to_string(),
1574 "Plain Text".to_string(),
1575 "Rust".to_string(),
1576 ]
1577 );
1578
1579 let rust1 = languages.language_for_name("Rust");
1580 let rust2 = languages.language_for_name("Rust");
1581
1582 // Ensure language is still listed even if it's being loaded.
1583 assert_eq!(
1584 languages.language_names(),
1585 &[
1586 "JSON".to_string(),
1587 "Plain Text".to_string(),
1588 "Rust".to_string(),
1589 ]
1590 );
1591
1592 let (rust1, rust2) = futures::join!(rust1, rust2);
1593 assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
1594
1595 // Ensure language is still listed even after loading it.
1596 assert_eq!(
1597 languages.language_names(),
1598 &[
1599 "JSON".to_string(),
1600 "Plain Text".to_string(),
1601 "Rust".to_string(),
1602 ]
1603 );
1604
1605 // Loading an unknown language returns an error.
1606 assert!(languages.language_for_name("Unknown").await.is_err());
1607 }
1608}