//! Grammar compilation and line tokenization. //! //! TextMate grammars are parsed into immutable pattern trees with interned //! scope names and compiled Oniguruma regex sets. The public tokenizer APIs use //! caller-owned [`LineState`] values so multi-line constructs can continue //! across line boundaries without forcing whole-file parsing. use std::collections::{BTreeMap, HashSet}; use std::path::Path; use std::str::FromStr; use onig::{RegSet, RegSetLead, Regex, RegexOptions, Region, SearchOptions, Syntax}; use crate::json; use crate::raw::{RawCapture, RawGrammar, RawPattern, head_patterns}; use crate::util::{key, next_char_boundary, path_keys, trim_line_end}; use crate::{Error, MAX_INCLUDE_DEPTH}; mod end; mod pattern; mod selector; mod tokenize; pub use tokenize::LineTokenizer; use pattern::{Injection, OpenRule, PatternCompiler, PatternSet, PatternSetId, RuleLocation}; /// Display name for the built-in plain-text fallback grammar. pub(crate) const PLAIN_TEXT_NAME: &str = "Plain Text"; /// Regex options used for TextMate pattern compilation. pub(super) const TEXTMATE_REGEX_OPTIONS: RegexOptions = RegexOptions::REGEX_OPTION_CAPTURE_GROUP; /// Compiles a TextMate regex with capture semantics expected by grammar captures. pub(super) fn regex(pattern: &str) -> Result { Regex::with_options(pattern, TEXTMATE_REGEX_OPTIONS, Syntax::default()) } /// Interned scope identifier. #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct ScopeId( /// Index into a grammar's interned scope-name table. usize, ); impl ScopeId { /// Returns this id's index into its grammar's interned scope-name table. pub const fn index(self) -> usize { self.0 } /// Creates a scope id from an interned scope-name table index. pub(crate) const fn new(index: usize) -> Self { Self(index) } } /// Scope span produced by tokenization. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct ScopeSpan { /// Start byte in the line. pub start: usize, /// End byte in the line. pub end: usize, /// Interned scope id. pub scope: ScopeId, } /// Per-line parser state. #[derive(Clone, Debug, Eq, PartialEq)] pub struct LineState { /// Open begin/end rules carried across line boundaries. stack: Vec, /// Whether the next line tokenized from this state is the first line. first_line: bool, } impl LineState { /// Returns true when there are no open multi-line rules. pub fn is_empty(&self) -> bool { self.stack.is_empty() } /// Returns the number of open multi-line rules. pub fn depth(&self) -> usize { self.stack.len() } } impl Default for LineState { /// Creates parser state for the first line of a document. fn default() -> Self { Self { stack: Vec::new(), first_line: true, } } } /// Regex anchor availability for one tokenizer step. #[derive(Clone, Copy, Debug)] pub(super) struct AnchorState { /// Whether `\A` should be allowed for this line. first_line: bool, /// Byte position where `\G` should be allowed. begin_position: Option, } impl AnchorState { /// Creates anchor state for a new line. pub(super) fn new(first_line: bool) -> Self { Self { first_line, begin_position: None, } } /// Allows `\G` at `position`. pub(super) fn set_begin_position(&mut self, position: usize) { self.begin_position = Some(position); } /// Replaces the active `\G` position with a previous stack frame's value. pub(super) fn restore_begin_position(&mut self, position: Option) { self.begin_position = position; } /// Returns the active `\G` position. pub(super) fn begin_position(self) -> Option { self.begin_position } /// Returns Oniguruma search options for a search starting at `position`. pub(super) fn search_options(self, position: usize) -> SearchOptions { let mut options = SearchOptions::SEARCH_OPTION_NONE; if !self.first_line { options |= SearchOptions::SEARCH_OPTION_NOT_BEGIN_STRING; } if self.begin_position != Some(position) { options |= SearchOptions::SEARCH_OPTION_NOT_BEGIN_POSITION; } options } } /// Immutable compiled grammar data. #[derive(Debug)] pub struct Grammar { /// Human-readable grammar name. pub name: String, /// Root scope name. pub scope_name: String, /// Interned scope names used by this grammar. pub scopes: Vec, /// Tokenization strategy used by this grammar. pub kind: GrammarKind, /// Lowercase file extensions, file names, and aliases matched by this grammar. file_types: HashSet, /// Regexes used to match a source file's head line. head_match: Vec, /// Root pattern set for TextMate tokenization. patterns: PatternSetId, /// Arena of compiled pattern sets. pattern_sets: Vec, /// Direct pattern locations indexed by rule id. rule_locations: Vec>, /// Runtime injections applied while tokenizing this grammar. injections: Vec, } /// Tokenization strategy used by a grammar. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum GrammarKind { /// TextMate grammar compiled to Oniguruma regex sets. TextMate, /// Dedicated line-oriented JSON scanner. Json, } impl Grammar { /// Compiles a raw grammar. pub fn compile(raw: &RawGrammar) -> Result { Self::compile_with(raw, &[]) } /// Compiles a raw grammar with raw cross-grammar include dependencies. pub fn compile_with(raw: &RawGrammar, dependencies: &[RawGrammar]) -> Result { let compiled = PatternCompiler::new(raw, dependencies).compile()?; let head_match = head_patterns(raw.first_line_match.as_ref()) .iter() .map(|pattern| regex(pattern).map_err(|_| Error::InvalidRegex(pattern.clone()))) .collect::, _>>()?; Ok(Self { name: raw.display_name.clone().unwrap_or_else(|| raw.name.clone()), scope_name: raw.scope_name.clone(), file_types: raw .file_types .iter() .chain(std::iter::once(&raw.name)) .map(|item| key(item)) .collect(), head_match, patterns: compiled.root, pattern_sets: compiled.sets, rule_locations: compiled.rule_locations, injections: compiled.injections, scopes: compiled.scopes, kind: GrammarKind::TextMate, }) } /// Builds a grammar with no patterns for plain text fallback. pub fn plain_text() -> Self { Self { name: PLAIN_TEXT_NAME.to_owned(), scope_name: "text.plain".to_owned(), file_types: ["txt".to_owned(), "text".to_owned()].into_iter().collect(), head_match: Vec::new(), patterns: PatternSetId::new(0), pattern_sets: vec![PatternSet::empty()], rule_locations: Vec::new(), injections: Vec::new(), scopes: Vec::new(), kind: GrammarKind::TextMate, } } /// Builds the dedicated fast JSON grammar. /// /// This does not use the recursive TextMate tokenizer. It emits the same /// kind of [`ScopeSpan`] values as compiled grammars while scanning each /// line directly. pub fn json() -> Self { Self { name: "JSON".to_owned(), scope_name: "source.json".to_owned(), file_types: ["json".to_owned()].into_iter().collect(), head_match: Vec::new(), patterns: PatternSetId::new(0), pattern_sets: vec![PatternSet::empty()], rule_locations: Vec::new(), injections: Vec::new(), scopes: json::SCOPES .iter() .map(|scope| (*scope).to_owned()) .collect(), kind: GrammarKind::Json, } } /// Returns true when this grammar matches a syntax name or alias. pub fn matches_name(&self, name: &str) -> bool { name.eq_ignore_ascii_case(&self.name) || name.eq_ignore_ascii_case(&self.scope_name) || self.file_types.contains(&key(name)) } /// Returns true when this grammar matches a file path. pub fn matches_path(&self, path: &Path) -> bool { path_keys(path).any(|key| self.file_types.contains(&key)) } /// Returns true when this grammar matches the head source line. pub fn matches_head(&self, line: &str) -> bool { self.head_match .iter() .any(|regex| regex.find(line).is_some()) } /// Tokenizes one line, mutating the caller-owned line state. pub fn tokenize_line(&self, state: &mut LineState, line: &str) -> Vec { let mut spans = Vec::new(); self.tokenize_line_into(state, line, &mut spans); spans } /// Tokenizes one line into a caller-owned buffer. pub fn tokenize_line_into( &self, state: &mut LineState, line: &str, spans: &mut Vec, ) { LineTokenizer::new(self).tokenize_line_into(state, line, spans); } /// Returns the compiled pattern for a stored rule id. fn pattern_by_rule(&self, rule_id: usize) -> Option<&pattern::Pattern> { let location = self.rule_locations.get(rule_id)?.as_ref()?; self.pattern_sets .get(location.set.index())? .patterns .get(location.index) } /// Builds the active scope stack used by injection selectors. fn scope_names_for_state<'grammar>( &'grammar self, state: &LineState, scopes: &mut Vec<&'grammar str>, ) { scopes.clear(); scopes.push(&self.scope_name); for open in &state.stack { let Some(pattern) = self.pattern_by_rule(open.rule_id) else { continue; }; pattern.extend_scope_names(&self.scopes, scopes); } } } impl FromStr for Grammar { type Err = Error; /// Parses and compiles a grammar from JSON. fn from_str(input: &str) -> Result { let raw = RawGrammar::from_str(input)?; Self::compile(&raw) } }