| 1 | use gpui::{App, FontWeight, HighlightStyle, Hsla, SharedString}; |
| 2 | use schemars::JsonSchema; |
| 3 | use serde::{Deserialize, Serialize}; |
| 4 | use serde_repr::{Deserialize_repr, Serialize_repr}; |
| 5 | use std::{ |
| 6 | collections::HashMap, |
| 7 | ops::Deref, |
| 8 | sync::{ |
| 9 | Arc, LazyLock, Mutex, |
| 10 | atomic::{AtomicU64, Ordering}, |
| 11 | }, |
| 12 | }; |
| 13 | |
| 14 | use anyhow::Result; |
| 15 | |
| 16 | use crate::{ActiveTheme, DEFAULT_THEME_COLORS, ThemeMode, highlighter::languages}; |
| 17 | |
| 18 | pub(super) const HIGHLIGHT_NAMES: [&str; 41] = [ |
| 19 | "attribute", |
| 20 | "boolean", |
| 21 | "comment", |
| 22 | "comment.doc", |
| 23 | "constant", |
| 24 | "constructor", |
| 25 | "embedded", |
| 26 | "emphasis", |
| 27 | "emphasis.strong", |
| 28 | "enum", |
| 29 | "function", |
| 30 | "hint", |
| 31 | "keyword", |
| 32 | "label", |
| 33 | "link_text", |
| 34 | "link_uri", |
| 35 | "number", |
| 36 | "operator", |
| 37 | "predictive", |
| 38 | "preproc", |
| 39 | "primary", |
| 40 | "property", |
| 41 | "punctuation", |
| 42 | "punctuation.bracket", |
| 43 | "punctuation.delimiter", |
| 44 | "punctuation.list_marker", |
| 45 | "punctuation.special", |
| 46 | "string", |
| 47 | "string.escape", |
| 48 | "string.regex", |
| 49 | "string.special", |
| 50 | "string.special.symbol", |
| 51 | "tag", |
| 52 | "tag.doctype", |
| 53 | "text.code.span", |
| 54 | "text.literal", |
| 55 | "title", |
| 56 | "type", |
| 57 | "variable", |
| 58 | "variable.special", |
| 59 | "variant", |
| 60 | ]; |
| 61 | |
| 62 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 63 | pub struct LanguageConfig { |
| 64 | pub name: SharedString, |
| 65 | pub language: Option<tree_sitter::Language>, |
| 66 | pub injection_languages: Vec<SharedString>, |
| 67 | pub highlights: SharedString, |
| 68 | pub injections: SharedString, |
| 69 | pub locals: SharedString, |
| 70 | } |
| 71 | |
| 72 | /// Explicit name for grammar resources; editing rules use `input::language_config::LanguageConfig`. |
| 73 | pub type GrammarConfig = LanguageConfig; |
| 74 | |
| 75 | impl LanguageConfig { |
| 76 | pub fn new( |
| 77 | name: impl Into<SharedString>, |
| 78 | language: tree_sitter::Language, |
| 79 | injection_languages: Vec<SharedString>, |
| 80 | highlights: &str, |
| 81 | injections: &str, |
| 82 | locals: &str, |
| 83 | ) -> Self { |
| 84 | Self { |
| 85 | name: name.into(), |
| 86 | language: Some(language), |
| 87 | injection_languages, |
| 88 | highlights: SharedString::from(highlights.to_string()), |
| 89 | injections: SharedString::from(injections.to_string()), |
| 90 | locals: SharedString::from(locals.to_string()), |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | /// A plain text language without a grammar, it will never be parsed. |
| 95 | pub fn plain(name: impl Into<SharedString>) -> Self { |
| 96 | Self { |
| 97 | name: name.into(), |
| 98 | language: None, |
| 99 | injection_languages: vec![], |
| 100 | highlights: SharedString::default(), |
| 101 | injections: SharedString::default(), |
| 102 | locals: SharedString::default(), |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | /// Whether this language has a grammar to parse with. |
| 107 | pub fn has_grammar(&self) -> bool { |
| 108 | self.language.is_some() |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | /// Theme for Tree-sitter Highlight |
| 113 | /// |
| 114 | /// https://docs.rs/tree-sitter-highlight/0.26.8/tree_sitter_highlight/ |
| 115 | #[derive(Debug, Default, Clone, PartialEq, Eq, Hash, JsonSchema, Serialize, Deserialize)] |
| 116 | pub struct SyntaxColors { |
| 117 | pub attribute: Option<ThemeStyle>, |
| 118 | pub boolean: Option<ThemeStyle>, |
| 119 | pub comment: Option<ThemeStyle>, |
| 120 | pub comment_doc: Option<ThemeStyle>, |
| 121 | pub constant: Option<ThemeStyle>, |
| 122 | pub constructor: Option<ThemeStyle>, |
| 123 | pub embedded: Option<ThemeStyle>, |
| 124 | pub emphasis: Option<ThemeStyle>, |
| 125 | #[serde(rename = "emphasis.strong")] |
| 126 | pub emphasis_strong: Option<ThemeStyle>, |
| 127 | #[serde(rename = "enum")] |
| 128 | pub enum_: Option<ThemeStyle>, |
| 129 | pub function: Option<ThemeStyle>, |
| 130 | pub hint: Option<ThemeStyle>, |
| 131 | pub keyword: Option<ThemeStyle>, |
| 132 | pub label: Option<ThemeStyle>, |
| 133 | #[serde(rename = "link_text")] |
| 134 | pub link_text: Option<ThemeStyle>, |
| 135 | #[serde(rename = "link_uri")] |
| 136 | pub link_uri: Option<ThemeStyle>, |
| 137 | pub number: Option<ThemeStyle>, |
| 138 | pub operator: Option<ThemeStyle>, |
| 139 | pub predictive: Option<ThemeStyle>, |
| 140 | pub preproc: Option<ThemeStyle>, |
| 141 | pub primary: Option<ThemeStyle>, |
| 142 | pub property: Option<ThemeStyle>, |
| 143 | pub punctuation: Option<ThemeStyle>, |
| 144 | #[serde(rename = "punctuation.bracket")] |
| 145 | pub punctuation_bracket: Option<ThemeStyle>, |
| 146 | #[serde(rename = "punctuation.delimiter")] |
| 147 | pub punctuation_delimiter: Option<ThemeStyle>, |
| 148 | #[serde(rename = "punctuation.list_marker")] |
| 149 | pub punctuation_list_marker: Option<ThemeStyle>, |
| 150 | #[serde(rename = "punctuation.special")] |
| 151 | pub punctuation_special: Option<ThemeStyle>, |
| 152 | pub string: Option<ThemeStyle>, |
| 153 | #[serde(rename = "string.escape")] |
| 154 | pub string_escape: Option<ThemeStyle>, |
| 155 | #[serde(rename = "string.regex")] |
| 156 | pub string_regex: Option<ThemeStyle>, |
| 157 | #[serde(rename = "string.special")] |
| 158 | pub string_special: Option<ThemeStyle>, |
| 159 | #[serde(rename = "string.special.symbol")] |
| 160 | pub string_special_symbol: Option<ThemeStyle>, |
| 161 | pub tag: Option<ThemeStyle>, |
| 162 | #[serde(rename = "tag.doctype")] |
| 163 | pub tag_doctype: Option<ThemeStyle>, |
| 164 | #[serde(rename = "text.code.span")] |
| 165 | pub text_code_span: Option<ThemeStyle>, |
| 166 | #[serde(rename = "text.literal")] |
| 167 | pub text_literal: Option<ThemeStyle>, |
| 168 | pub title: Option<ThemeStyle>, |
| 169 | #[serde(rename = "type")] |
| 170 | pub type_: Option<ThemeStyle>, |
| 171 | pub variable: Option<ThemeStyle>, |
| 172 | #[serde(rename = "variable.special")] |
| 173 | pub variable_special: Option<ThemeStyle>, |
| 174 | pub variant: Option<ThemeStyle>, |
| 175 | } |
| 176 | |
| 177 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, JsonSchema, Serialize, Deserialize)] |
| 178 | #[serde(rename_all = "lowercase")] |
| 179 | pub enum FontStyle { |
| 180 | Normal, |
| 181 | Italic, |
| 182 | Underline, |
| 183 | } |
| 184 | |
| 185 | impl From<FontStyle> for gpui::FontStyle { |
| 186 | fn from(style: FontStyle) -> Self { |
| 187 | match style { |
| 188 | FontStyle::Normal => gpui::FontStyle::Normal, |
| 189 | FontStyle::Italic => gpui::FontStyle::Italic, |
| 190 | FontStyle::Underline => gpui::FontStyle::Normal, |
| 191 | } |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Serialize_repr, Deserialize_repr, JsonSchema)] |
| 196 | #[repr(u16)] |
| 197 | pub enum FontWeightContent { |
| 198 | Thin = 100, |
| 199 | ExtraLight = 200, |
| 200 | Light = 300, |
| 201 | Normal = 400, |
| 202 | Medium = 500, |
| 203 | Semibold = 600, |
| 204 | Bold = 700, |
| 205 | ExtraBold = 800, |
| 206 | Black = 900, |
| 207 | } |
| 208 | |
| 209 | impl From<FontWeightContent> for FontWeight { |
| 210 | fn from(value: FontWeightContent) -> Self { |
| 211 | match value { |
| 212 | FontWeightContent::Thin => FontWeight::THIN, |
| 213 | FontWeightContent::ExtraLight => FontWeight::EXTRA_LIGHT, |
| 214 | FontWeightContent::Light => FontWeight::LIGHT, |
| 215 | FontWeightContent::Normal => FontWeight::NORMAL, |
| 216 | FontWeightContent::Medium => FontWeight::MEDIUM, |
| 217 | FontWeightContent::Semibold => FontWeight::SEMIBOLD, |
| 218 | FontWeightContent::Bold => FontWeight::BOLD, |
| 219 | FontWeightContent::ExtraBold => FontWeight::EXTRA_BOLD, |
| 220 | FontWeightContent::Black => FontWeight::BLACK, |
| 221 | } |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, JsonSchema, Serialize, Deserialize)] |
| 226 | pub struct ThemeStyle { |
| 227 | color: Option<Hsla>, |
| 228 | font_style: Option<FontStyle>, |
| 229 | font_weight: Option<FontWeightContent>, |
| 230 | } |
| 231 | |
| 232 | impl From<ThemeStyle> for HighlightStyle { |
| 233 | fn from(style: ThemeStyle) -> Self { |
| 234 | HighlightStyle { |
| 235 | color: style.color, |
| 236 | font_weight: style.font_weight.map(Into::into), |
| 237 | font_style: style.font_style.map(Into::into), |
| 238 | ..Default::default() |
| 239 | } |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | impl SyntaxColors { |
| 244 | pub fn style(&self, name: &str) -> Option<HighlightStyle> { |
| 245 | if name.is_empty() { |
| 246 | return None; |
| 247 | } |
| 248 | |
| 249 | let style = match name { |
| 250 | "attribute" => self.attribute, |
| 251 | "boolean" => self.boolean, |
| 252 | "comment" => self.comment, |
| 253 | "comment.doc" => self.comment_doc, |
| 254 | "constant" => self.constant, |
| 255 | "constructor" => self.constructor, |
| 256 | "embedded" => self.embedded, |
| 257 | "emphasis" => self.emphasis, |
| 258 | "emphasis.strong" => self.emphasis_strong, |
| 259 | "enum" => self.enum_, |
| 260 | "function" => self.function, |
| 261 | "hint" => self.hint, |
| 262 | "keyword" => self.keyword, |
| 263 | "label" => self.label, |
| 264 | "link_text" => self.link_text, |
| 265 | "link_uri" => self.link_uri, |
| 266 | "number" => self.number, |
| 267 | "operator" => self.operator, |
| 268 | "predictive" => self.predictive, |
| 269 | "preproc" => self.preproc, |
| 270 | "primary" => self.primary, |
| 271 | "property" => self.property, |
| 272 | "punctuation" => self.punctuation, |
| 273 | "punctuation.bracket" => self.punctuation_bracket, |
| 274 | "punctuation.delimiter" => self.punctuation_delimiter, |
| 275 | "punctuation.list_marker" => self.punctuation_list_marker, |
| 276 | "punctuation.special" => self.punctuation_special, |
| 277 | "string" => self.string, |
| 278 | "string.escape" => self.string_escape, |
| 279 | "string.regex" => self.string_regex, |
| 280 | "string.special" => self.string_special, |
| 281 | "string.special.symbol" => self.string_special_symbol, |
| 282 | "tag" => self.tag, |
| 283 | "tag.doctype" => self.tag_doctype, |
| 284 | "text.code.span" => self.text_code_span, |
| 285 | "text.literal" => self.text_literal, |
| 286 | "title" => self.title, |
| 287 | "type" => self.type_, |
| 288 | "variable" => self.variable, |
| 289 | "variable.special" => self.variable_special, |
| 290 | "variant" => self.variant, |
| 291 | _ => None, |
| 292 | } |
| 293 | .map(|s| s.into()); |
| 294 | |
| 295 | if style.is_some() { |
| 296 | style |
| 297 | } else { |
| 298 | // Fallback `keyword.modifier` to `keyword` |
| 299 | if name.contains(".") { |
| 300 | if let Some(prefix) = name.split(".").next() { |
| 301 | return self.style(prefix); |
| 302 | } |
| 303 | |
| 304 | None |
| 305 | } else { |
| 306 | None |
| 307 | } |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | #[inline] |
| 312 | pub fn style_for_index(&self, index: usize) -> Option<HighlightStyle> { |
| 313 | HIGHLIGHT_NAMES.get(index).and_then(|name| self.style(name)) |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | #[derive(Debug, Default, Clone, PartialEq, Eq, Hash, JsonSchema, Serialize, Deserialize)] |
| 318 | pub struct StatusColors { |
| 319 | #[serde(rename = "error")] |
| 320 | error: Option<Hsla>, |
| 321 | #[serde(rename = "error.background")] |
| 322 | error_background: Option<Hsla>, |
| 323 | #[serde(rename = "error.border")] |
| 324 | error_border: Option<Hsla>, |
| 325 | #[serde(rename = "warning")] |
| 326 | warning: Option<Hsla>, |
| 327 | #[serde(rename = "warning.background")] |
| 328 | warning_background: Option<Hsla>, |
| 329 | #[serde(rename = "warning.border")] |
| 330 | warning_border: Option<Hsla>, |
| 331 | #[serde(rename = "info")] |
| 332 | info: Option<Hsla>, |
| 333 | #[serde(rename = "info.background")] |
| 334 | info_background: Option<Hsla>, |
| 335 | #[serde(rename = "info.border")] |
| 336 | info_border: Option<Hsla>, |
| 337 | #[serde(rename = "success")] |
| 338 | success: Option<Hsla>, |
| 339 | #[serde(rename = "success.background")] |
| 340 | success_background: Option<Hsla>, |
| 341 | #[serde(rename = "success.border")] |
| 342 | success_border: Option<Hsla>, |
| 343 | #[serde(rename = "hint")] |
| 344 | hint: Option<Hsla>, |
| 345 | #[serde(rename = "hint.background")] |
| 346 | hint_background: Option<Hsla>, |
| 347 | #[serde(rename = "hint.border")] |
| 348 | hint_border: Option<Hsla>, |
| 349 | } |
| 350 | |
| 351 | impl StatusColors { |
| 352 | #[inline] |
| 353 | pub fn error(&self, cx: &App) -> Hsla { |
| 354 | self.error.unwrap_or(cx.theme().red) |
| 355 | } |
| 356 | |
| 357 | #[inline] |
| 358 | pub fn error_background(&self, cx: &App) -> Hsla { |
| 359 | let bg = cx.theme().background; |
| 360 | self.error_background |
| 361 | .unwrap_or(bg.blend(self.error(cx).alpha(0.2))) |
| 362 | } |
| 363 | |
| 364 | #[inline] |
| 365 | pub fn error_border(&self, cx: &App) -> Hsla { |
| 366 | self.error_border.unwrap_or(self.error(cx)) |
| 367 | } |
| 368 | |
| 369 | #[inline] |
| 370 | pub fn warning(&self, cx: &App) -> Hsla { |
| 371 | self.warning.unwrap_or(cx.theme().yellow) |
| 372 | } |
| 373 | |
| 374 | #[inline] |
| 375 | pub fn warning_background(&self, cx: &App) -> Hsla { |
| 376 | let bg = cx.theme().background; |
| 377 | self.warning_background |
| 378 | .unwrap_or(bg.blend(self.warning(cx).alpha(0.2))) |
| 379 | } |
| 380 | |
| 381 | #[inline] |
| 382 | pub fn warning_border(&self, cx: &App) -> Hsla { |
| 383 | self.warning_border.unwrap_or(self.warning(cx)) |
| 384 | } |
| 385 | |
| 386 | #[inline] |
| 387 | pub fn info(&self, cx: &App) -> Hsla { |
| 388 | self.info.unwrap_or(cx.theme().blue) |
| 389 | } |
| 390 | |
| 391 | #[inline] |
| 392 | pub fn info_background(&self, cx: &App) -> Hsla { |
| 393 | let bg = cx.theme().background; |
| 394 | self.info_background |
| 395 | .unwrap_or(bg.blend(self.info(cx).alpha(0.2))) |
| 396 | } |
| 397 | |
| 398 | #[inline] |
| 399 | pub fn info_border(&self, cx: &App) -> Hsla { |
| 400 | self.info_border.unwrap_or(self.info(cx)) |
| 401 | } |
| 402 | |
| 403 | #[inline] |
| 404 | pub fn success(&self, cx: &App) -> Hsla { |
| 405 | self.success.unwrap_or(cx.theme().green) |
| 406 | } |
| 407 | |
| 408 | #[inline] |
| 409 | pub fn success_background(&self, cx: &App) -> Hsla { |
| 410 | let bg = cx.theme().background; |
| 411 | self.success_background |
| 412 | .unwrap_or(bg.blend(self.success(cx).alpha(0.2))) |
| 413 | } |
| 414 | |
| 415 | #[inline] |
| 416 | pub fn success_border(&self, cx: &App) -> Hsla { |
| 417 | self.success_border.unwrap_or(self.success(cx)) |
| 418 | } |
| 419 | |
| 420 | #[inline] |
| 421 | pub fn hint(&self, cx: &App) -> Hsla { |
| 422 | self.hint.unwrap_or(cx.theme().cyan) |
| 423 | } |
| 424 | |
| 425 | #[inline] |
| 426 | pub fn hint_background(&self, cx: &App) -> Hsla { |
| 427 | let bg = cx.theme().background; |
| 428 | self.hint_background |
| 429 | .unwrap_or(bg.blend(self.hint(cx).alpha(0.2))) |
| 430 | } |
| 431 | |
| 432 | #[inline] |
| 433 | pub fn hint_border(&self, cx: &App) -> Hsla { |
| 434 | self.hint_border.unwrap_or(self.hint(cx)) |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | #[derive(Debug, Default, Clone, PartialEq, Eq, Hash, JsonSchema, Serialize, Deserialize)] |
| 439 | pub struct HighlightThemeStyle { |
| 440 | #[serde(rename = "editor.background")] |
| 441 | pub editor_background: Option<Hsla>, |
| 442 | #[serde(rename = "editor.foreground")] |
| 443 | pub editor_foreground: Option<Hsla>, |
| 444 | #[serde(rename = "editor.active_line.background")] |
| 445 | pub editor_active_line: Option<Hsla>, |
| 446 | #[serde(rename = "editor.line_number")] |
| 447 | pub editor_line_number: Option<Hsla>, |
| 448 | #[serde(rename = "editor.active_line_number")] |
| 449 | pub editor_active_line_number: Option<Hsla>, |
| 450 | #[serde(rename = "editor.invisible")] |
| 451 | pub editor_invisible: Option<Hsla>, |
| 452 | /// Optional background color for the gutter (line-number column). |
| 453 | /// Falls back to [`Self::editor_background`] when unset. |
| 454 | #[serde(rename = "editor.gutter.background")] |
| 455 | pub editor_gutter_background: Option<Hsla>, |
| 456 | #[serde(flatten)] |
| 457 | pub status: StatusColors, |
| 458 | #[serde(rename = "syntax")] |
| 459 | pub syntax: SyntaxColors, |
| 460 | } |
| 461 | |
| 462 | /// Theme for Tree-sitter Highlight from JSON theme file. |
| 463 | /// |
| 464 | /// This json is compatible with the Zed theme format. |
| 465 | /// |
| 466 | /// https://zed.dev/docs/extensions/languages#syntax-highlighting |
| 467 | #[derive(Debug, Clone, PartialEq, Eq, Hash, JsonSchema, Serialize, Deserialize)] |
| 468 | pub struct HighlightTheme { |
| 469 | pub name: String, |
| 470 | #[serde(default)] |
| 471 | pub appearance: ThemeMode, |
| 472 | pub style: HighlightThemeStyle, |
| 473 | } |
| 474 | |
| 475 | impl Deref for HighlightTheme { |
| 476 | type Target = SyntaxColors; |
| 477 | |
| 478 | fn deref(&self) -> &Self::Target { |
| 479 | &self.style.syntax |
| 480 | } |
| 481 | } |
| 482 | |
| 483 | impl HighlightTheme { |
| 484 | pub fn default_dark() -> Arc<Self> { |
| 485 | DEFAULT_THEME_COLORS[&ThemeMode::Dark].1.clone() |
| 486 | } |
| 487 | |
| 488 | pub fn default_light() -> Arc<Self> { |
| 489 | DEFAULT_THEME_COLORS[&ThemeMode::Light].1.clone() |
| 490 | } |
| 491 | } |
| 492 | |
| 493 | impl gpui_base::input::HighlightStyleResolver for HighlightTheme { |
| 494 | fn style(&self, name: &str) -> Option<HighlightStyle> { |
| 495 | self.style.syntax.style(name) |
| 496 | } |
| 497 | } |
| 498 | |
| 499 | /// A factory that produces a fresh Tree-sitter parser and grammar for a language. |
| 500 | /// |
| 501 | /// Dynamic grammars (for example WASM-compiled parsers loaded at runtime) register |
| 502 | /// a factory here; when the highlighter needs to parse a buffer it prefers the |
| 503 | /// factory over the statically linked grammar. |
| 504 | pub type LanguageParserFactory = |
| 505 | Arc<dyn Fn() -> Result<(tree_sitter::Parser, tree_sitter::Language)> + Send + Sync>; |
| 506 | |
| 507 | /// Registry for code highlighter languages. |
| 508 | pub struct LanguageRegistry { |
| 509 | languages: Mutex<HashMap<SharedString, GrammarConfig>>, |
| 510 | parser_factories: Mutex<HashMap<SharedString, LanguageParserFactory>>, |
| 511 | /// Bumped by every registration; see [`Self::generation`]. |
| 512 | generation: AtomicU64, |
| 513 | } |
| 514 | |
| 515 | impl LanguageRegistry { |
| 516 | /// Returns the singleton instance of the `LanguageRegistry` with default languages and themes. |
| 517 | pub fn singleton() -> &'static LazyLock<LanguageRegistry> { |
| 518 | static INSTANCE: LazyLock<LanguageRegistry> = LazyLock::new(|| LanguageRegistry { |
| 519 | languages: Mutex::new( |
| 520 | languages::Language::all() |
| 521 | .map(|language| (language.name().into(), language.config())) |
| 522 | .collect(), |
| 523 | ), |
| 524 | parser_factories: Mutex::new(HashMap::new()), |
| 525 | generation: AtomicU64::new(0), |
| 526 | }); |
| 527 | &INSTANCE |
| 528 | } |
| 529 | |
| 530 | /// Registers a new language configuration to the registry. |
| 531 | pub fn register(&self, lang: &str, config: &GrammarConfig) { |
| 532 | self.languages |
| 533 | .lock() |
| 534 | .unwrap() |
| 535 | .insert(lang.to_string().into(), config.clone()); |
| 536 | self.generation.fetch_add(1, Ordering::Relaxed); |
| 537 | } |
| 538 | |
| 539 | /// Registers a parser factory for a dynamically loaded language. |
| 540 | /// |
| 541 | /// The factory takes precedence over the language's statically linked grammar |
| 542 | /// whenever a buffer in that language is parsed. |
| 543 | pub fn register_parser_factory(&self, lang: &str, factory: LanguageParserFactory) { |
| 544 | self.parser_factories |
| 545 | .lock() |
| 546 | .unwrap() |
| 547 | .insert(lang.to_string().into(), factory); |
| 548 | self.generation.fetch_add(1, Ordering::Relaxed); |
| 549 | } |
| 550 | |
| 551 | /// A counter that changes whenever a language or parser factory is |
| 552 | /// registered, so caches of highlighted output can tell when a language |
| 553 | /// they could not resolve before may now resolve. |
| 554 | pub(crate) fn generation(&self) -> u64 { |
| 555 | self.generation.load(Ordering::Relaxed) |
| 556 | } |
| 557 | |
| 558 | /// Returns a fresh parser and grammar for `name`, preferring a registered |
| 559 | /// parser factory over the statically linked grammar. |
| 560 | pub(crate) fn parser( |
| 561 | &self, |
| 562 | name: &str, |
| 563 | ) -> Result<(tree_sitter::Parser, tree_sitter::Language)> { |
| 564 | let config = self |
| 565 | .language(name) |
| 566 | .ok_or_else(|| anyhow::anyhow!("language {name:?} is not registered"))?; |
| 567 | // Bind the clone in its own statement so the guard is dropped before |
| 568 | // calling the factory. Otherwise a factory that re-enters the registry |
| 569 | // self-deadlocks on the non-reentrant mutex, every call is serialized |
| 570 | // behind the factory, and a panicking factory poisons the singleton. |
| 571 | let factory = self |
| 572 | .parser_factories |
| 573 | .lock() |
| 574 | .unwrap() |
| 575 | .get(&config.name) |
| 576 | .cloned(); |
| 577 | if let Some(factory) = factory { |
| 578 | return factory(); |
| 579 | } |
| 580 | |
| 581 | let language = config |
| 582 | .language |
| 583 | .ok_or_else(|| anyhow::anyhow!("language {name:?} has no grammar"))?; |
| 584 | Ok((tree_sitter::Parser::new(), language)) |
| 585 | } |
| 586 | |
| 587 | /// Returns whether `name` can produce a parser, either through a registered |
| 588 | /// parser factory or a statically linked grammar. |
| 589 | pub(crate) fn has_parser(&self, name: &str) -> bool { |
| 590 | let Some(config) = self.language(name) else { |
| 591 | return false; |
| 592 | }; |
| 593 | |
| 594 | config.language.is_some() |
| 595 | || self |
| 596 | .parser_factories |
| 597 | .lock() |
| 598 | .unwrap() |
| 599 | .contains_key(&config.name) |
| 600 | } |
| 601 | |
| 602 | /// Returns the grammar for `name`, preferring a registered parser factory. |
| 603 | pub(crate) fn grammar(&self, name: &str) -> Result<tree_sitter::Language> { |
| 604 | Ok(self.parser(name)?.1) |
| 605 | } |
| 606 | |
| 607 | pub(crate) fn editing_language_name(&self, name: &str) -> SharedString { |
| 608 | self.languages |
| 609 | .lock() |
| 610 | .unwrap() |
| 611 | .get_key_value(name) |
| 612 | .map(|(name, _)| name.clone()) |
| 613 | .unwrap_or_else(|| super::language_name(name)) |
| 614 | } |
| 615 | |
| 616 | /// Returns a list of all registered language names. |
| 617 | pub fn languages(&self) -> Vec<SharedString> { |
| 618 | self.languages.lock().unwrap().keys().cloned().collect() |
| 619 | } |
| 620 | |
| 621 | /// Returns the language configuration for the given language name. |
| 622 | pub fn language(&self, name: &str) -> Option<GrammarConfig> { |
| 623 | let languages = self.languages.lock().unwrap(); |
| 624 | languages.get(name).cloned().or_else(|| { |
| 625 | languages::Language::from_name(name) |
| 626 | .and_then(|language| languages.get(language.name()).cloned()) |
| 627 | }) |
| 628 | } |
| 629 | } |
| 630 | |
| 631 | #[cfg(test)] |
| 632 | mod tests { |
| 633 | use crate::highlighter::GrammarConfig; |
| 634 | |
| 635 | #[test] |
| 636 | fn registrations_preserve_exact_names_before_alias_fallback() { |
| 637 | let registry = super::LanguageRegistry { |
| 638 | languages: std::sync::Mutex::new(std::collections::HashMap::new()), |
| 639 | parser_factories: std::sync::Mutex::new(std::collections::HashMap::new()), |
| 640 | generation: std::sync::atomic::AtomicU64::new(0), |
| 641 | }; |
| 642 | registry.register("json", &GrammarConfig::plain("canonical")); |
| 643 | assert_eq!(registry.language("jsonc").unwrap().name, "canonical"); |
| 644 | registry.register("jsonc", &GrammarConfig::plain("custom alias")); |
| 645 | registry.register("JSON", &GrammarConfig::plain("custom uppercase")); |
| 646 | assert_eq!(registry.language("json").unwrap().name, "canonical"); |
| 647 | assert_eq!(registry.language("jsonc").unwrap().name, "custom alias"); |
| 648 | assert_eq!(registry.language("JSON").unwrap().name, "custom uppercase"); |
| 649 | assert!(registry.language("Json").is_none()); |
| 650 | let mut names = registry.languages(); |
| 651 | names.sort(); |
| 652 | assert_eq!(names, vec!["JSON", "json", "jsonc"]); |
| 653 | assert_eq!(registry.editing_language_name("jsonc"), "jsonc"); |
| 654 | assert_eq!(registry.editing_language_name("JSON"), "JSON"); |
| 655 | assert_eq!(registry.editing_language_name("pyi"), "python"); |
| 656 | } |
| 657 | |
| 658 | #[cfg(not(feature = "tree-sitter-typescript"))] |
| 659 | #[test] |
| 660 | fn custom_canonical_registration_does_not_enable_disabled_aliases() { |
| 661 | let registry = super::LanguageRegistry { |
| 662 | languages: std::sync::Mutex::new(std::collections::HashMap::new()), |
| 663 | parser_factories: std::sync::Mutex::new(std::collections::HashMap::new()), |
| 664 | generation: std::sync::atomic::AtomicU64::new(0), |
| 665 | }; |
| 666 | registry.register("typescript", &GrammarConfig::plain("typescript")); |
| 667 | assert!(registry.language("ts").is_none()); |
| 668 | registry.register("ts", &GrammarConfig::plain("custom")); |
| 669 | assert_eq!(registry.language("ts").unwrap().name, "custom"); |
| 670 | } |
| 671 | |
| 672 | #[test] |
| 673 | fn public_language_lookup_retains_case_sensitive_aliases() { |
| 674 | use super::languages::Language; |
| 675 | assert_eq!(Language::from_str("jsonc"), Language::Json); |
| 676 | assert_eq!(Language::from_str("JSON"), Language::Plain); |
| 677 | assert_eq!(Language::from_str("pyi"), Language::Plain); |
| 678 | #[cfg(feature = "tree-sitter-typescript")] |
| 679 | { |
| 680 | assert_eq!(Language::from_str("typescript"), Language::TypeScript); |
| 681 | assert_eq!(Language::from_str("ts"), Language::TypeScript); |
| 682 | } |
| 683 | } |
| 684 | |
| 685 | #[test] |
| 686 | fn test_registry() { |
| 687 | use super::LanguageRegistry; |
| 688 | let registry = LanguageRegistry::singleton(); |
| 689 | registry.register( |
| 690 | "foo", |
| 691 | &GrammarConfig::new("foo", tree_sitter_json::LANGUAGE.into(), vec![], "", "", ""), |
| 692 | ); |
| 693 | |
| 694 | assert!(registry.language("foo").is_some()); |
| 695 | assert!(registry.language("json").is_some()); |
| 696 | assert!(registry.language("text").is_some()); |
| 697 | assert!(registry.language("unknown").is_none()); |
| 698 | |
| 699 | #[cfg(feature = "tree-sitter-rust")] |
| 700 | { |
| 701 | assert!(registry.language("rust").is_some()); |
| 702 | assert!(registry.language("rs").is_some()); |
| 703 | } |
| 704 | #[cfg(not(feature = "tree-sitter-rust"))] |
| 705 | { |
| 706 | assert!(registry.language("rust").is_none()); |
| 707 | assert!(registry.language("rs").is_none()); |
| 708 | } |
| 709 | |
| 710 | #[cfg(feature = "tree-sitter-javascript")] |
| 711 | { |
| 712 | assert!(registry.language("javascript").is_some()); |
| 713 | assert!(registry.language("js").is_some()); |
| 714 | } |
| 715 | #[cfg(not(feature = "tree-sitter-javascript"))] |
| 716 | { |
| 717 | assert!(registry.language("javascript").is_none()); |
| 718 | assert!(registry.language("js").is_none()); |
| 719 | } |
| 720 | } |
| 721 | |
| 722 | #[test] |
| 723 | fn dynamic_language_uses_registered_parser_factory() { |
| 724 | use std::sync::{ |
| 725 | Arc, |
| 726 | atomic::{AtomicBool, Ordering}, |
| 727 | }; |
| 728 | |
| 729 | use super::LanguageRegistry; |
| 730 | |
| 731 | let registry = LanguageRegistry::singleton(); |
| 732 | let called = Arc::new(AtomicBool::new(false)); |
| 733 | registry.register( |
| 734 | "__dynamic_json__", |
| 735 | &GrammarConfig::new( |
| 736 | "__dynamic_json__", |
| 737 | tree_sitter_json::LANGUAGE.into(), |
| 738 | vec![], |
| 739 | "", |
| 740 | "", |
| 741 | "", |
| 742 | ), |
| 743 | ); |
| 744 | registry.register_parser_factory("__dynamic_json__", { |
| 745 | let called = called.clone(); |
| 746 | Arc::new(move || { |
| 747 | called.store(true, Ordering::Relaxed); |
| 748 | Ok(( |
| 749 | tree_sitter::Parser::new(), |
| 750 | tree_sitter_json::LANGUAGE.into(), |
| 751 | )) |
| 752 | }) |
| 753 | }); |
| 754 | |
| 755 | let (_, language) = registry.parser("__dynamic_json__").unwrap(); |
| 756 | |
| 757 | assert!(called.load(Ordering::Relaxed)); |
| 758 | assert_eq!(language, tree_sitter_json::LANGUAGE.into()); |
| 759 | } |
| 760 | |
| 761 | #[test] |
| 762 | fn factory_only_language_highlights_without_static_grammar() { |
| 763 | use std::sync::{ |
| 764 | Arc, |
| 765 | atomic::{AtomicBool, Ordering}, |
| 766 | }; |
| 767 | |
| 768 | use super::LanguageRegistry; |
| 769 | use crate::highlighter::SyntaxHighlighter; |
| 770 | |
| 771 | let registry = LanguageRegistry::singleton(); |
| 772 | let called = Arc::new(AtomicBool::new(false)); |
| 773 | // No statically linked grammar: `language` is `None`, so the grammar can |
| 774 | // only come from the registered factory. |
| 775 | registry.register( |
| 776 | "__dynamic_factory_only__", |
| 777 | &GrammarConfig::plain("__dynamic_factory_only__"), |
| 778 | ); |
| 779 | assert!( |
| 780 | !registry |
| 781 | .language("__dynamic_factory_only__") |
| 782 | .unwrap() |
| 783 | .has_grammar() |
| 784 | ); |
| 785 | registry.register_parser_factory("__dynamic_factory_only__", { |
| 786 | let called = called.clone(); |
| 787 | Arc::new(move || { |
| 788 | called.store(true, Ordering::Relaxed); |
| 789 | Ok(( |
| 790 | tree_sitter::Parser::new(), |
| 791 | tree_sitter_json::LANGUAGE.into(), |
| 792 | )) |
| 793 | }) |
| 794 | }); |
| 795 | |
| 796 | let highlighter = SyntaxHighlighter::new("__dynamic_factory_only__"); |
| 797 | |
| 798 | assert!(called.load(Ordering::Relaxed)); |
| 799 | assert_eq!(highlighter.language().as_ref(), "__dynamic_factory_only__"); |
| 800 | } |
| 801 | } |