//! Raw TextMate JSON data structures. //! //! These types mirror the loose JSON shapes accepted by TextMate and VS Code //! grammar/theme files before the crate compiles them into stricter runtime //! data. Keeping this layer separate lets parsing tolerate source-file quirks //! without leaking those shapes into tokenization and styling code. use std::collections::BTreeMap; use std::str::FromStr; use serde::{Deserialize, json as serde_json}; use crate::Error; /// A parsed, uncompiled TextMate grammar. #[derive(Clone, Debug, Deserialize)] pub struct RawGrammar { /// Human-readable display name. #[serde(rename = "displayName")] pub display_name: Option, /// Human-readable grammar name. pub name: String, /// Root scope name. #[serde(rename = "scopeName")] pub scope_name: String, /// File extensions and special file names. #[serde(default)] #[serde(rename = "fileTypes")] pub file_types: Vec, /// First-line match expressions, as either a string or string array. #[serde(rename = "firstLineMatch")] pub first_line_match: Option, /// Root patterns. pub patterns: Vec, /// Named pattern repository. #[serde(default)] pub repository: BTreeMap, /// Injection selectors and the pattern injected at each selector. #[serde(default)] pub injections: BTreeMap, } /// A parsed, uncompiled TextMate pattern. #[derive(Clone, Debug, Default, Deserialize)] pub struct RawPattern { /// Scope assigned to the match. pub name: Option, /// Scope assigned to a begin rule's inner content. #[serde(rename = "contentName")] pub content_name: Option, /// Single-line match expression. #[serde(rename = "match")] pub match_rule: Option, /// Begin expression for a stateful rule. pub begin: Option, /// End expression for a stateful rule. pub end: Option, /// Whether nested patterns should be searched before this rule's end pattern. #[serde(rename = "applyEndPatternLast")] pub apply_end_pattern_last: Option, /// While expression for a stateful rule. #[serde(rename = "while")] pub while_rule: Option, /// Nested patterns. #[serde(default)] pub patterns: Vec, /// Include target such as `$self`, `$base`, or `#name`. pub include: Option, /// Captures shared by match rules and by begin/end/while rules that do not /// define slot-specific captures. pub captures: Option>, /// Begin captures. #[serde(rename = "beginCaptures")] pub begin_captures: Option>, /// End captures. #[serde(rename = "endCaptures")] pub end_captures: Option>, /// While captures. #[serde(rename = "whileCaptures")] pub while_captures: Option>, } /// A parsed, uncompiled TextMate capture. #[derive(Clone, Debug, Deserialize)] pub struct RawCapture { /// Scope assigned to the captured group. pub name: Option, /// Scope assigned to retokenized captured content. #[serde(rename = "contentName")] pub content_name: Option, /// Nested patterns used to retokenize the captured group. #[serde(default)] pub patterns: Vec, } /// A parsed, uncompiled TextMate theme. #[derive(Clone, Debug, Deserialize)] pub struct RawTheme { /// Theme name. pub name: String, /// Editor UI color keys. #[serde(default)] pub colors: BTreeMap, /// TextMate theme settings. #[serde(default)] pub settings: Vec, /// TextMate token color rules. #[serde(default)] #[serde(rename = "tokenColors")] pub token_colors: Vec, } /// One parsed TextMate theme rule. #[derive(Clone, Debug, Deserialize)] pub struct RawThemeRule { /// Optional selector string or selector array. pub scope: Option, /// Style settings. pub settings: RawStyle, } /// Parsed TextMate style settings. #[derive(Clone, Debug, Default, Deserialize)] pub struct RawStyle { /// Foreground color as `#rrggbb`. pub foreground: Option, /// Space-separated text style flags. #[serde(rename = "fontStyle")] pub font_style: Option, } impl RawGrammar { /// Parses a raw grammar from JSON. pub fn parse(input: &str) -> Result { input.parse() } } impl FromStr for RawGrammar { type Err = Error; fn from_str(input: &str) -> Result { serde_json::from_str(input).map_err(|_| Error::InvalidGrammar) } } impl RawTheme { /// Parses a raw theme from JSON. pub fn parse(input: &str) -> Result { input.parse() } } impl FromStr for RawTheme { type Err = Error; fn from_str(input: &str) -> Result { serde_json::from_str(input).map_err(|_| Error::InvalidTheme) } } impl RawThemeRule { /// Returns normalized selector strings from a TextMate `scope` value. pub(crate) fn scope_selectors(&self) -> Vec { let Some(scope) = self.scope.as_ref() else { return Vec::new(); }; let mut selectors = Vec::new(); match scope { serde_json::Value::String(scope) => push_selectors(scope, &mut selectors), serde_json::Value::Array(scopes) => { for scope in scopes { if let serde_json::Value::String(scope) = scope { push_selectors(scope, &mut selectors); } } } _ => {} } selectors } } /// Normalizes `firstLineMatch` from TextMate's string-or-array shape. pub(crate) fn head_patterns(value: Option<&serde_json::Value>) -> Vec { match value { Some(serde_json::Value::String(pattern)) => vec![pattern.clone()], Some(serde_json::Value::Array(values)) => values .iter() .filter_map(|value| { if let serde_json::Value::String(pattern) = value { Some(pattern.clone()) } else { None } }) .collect(), _ => Vec::new(), } } /// Returns true for TextMate's loose truthy JSON flag values. pub(crate) fn truthy_flag(value: Option<&serde_json::Value>) -> bool { matches!( value, Some(serde_json::Value::Bool(true)) | Some(serde_json::Value::Number(serde_json::Number::U64(1))) | Some(serde_json::Value::Number(serde_json::Number::I64(1))) | Some(serde_json::Value::Number(serde_json::Number::F64(1.0))) ) } /// Splits a comma-separated TextMate selector list. fn push_selectors(input: &str, selectors: &mut Vec) { selectors.extend( input .split(',') .map(str::trim) .filter(|selector| !selector.is_empty()) .map(str::to_owned), ); }