//! Pattern compilation and matching for TextMate grammars. //! //! Raw TextMate patterns compile into a tree of [`Pattern`] values grouped into //! [`PatternSet`]s. Each set caches a combined Oniguruma [`RegSet`] on first //! search so that finding the next match in a line is one regex search //! regardless of how many patterns share that nesting level. Begin/end rules //! carry their end pattern on the same node; static end patterns are //! precompiled, while dynamic ones are resolved against the begin match the //! first time they are needed and cached for subsequent lines. use super::end::{EndPattern, EndRegex, EndRegexCache}; use super::selector::ScopeSelector; use super::*; use crate::raw::truthy_flag; use std::cell::OnceCell; /// Capture-group index to capture metadata mapping. pub(super) type Captures = BTreeMap; /// A scope assigned by a pattern. #[derive(Clone, Debug, Eq, PartialEq)] pub(super) enum Scope { /// Pattern names no scope. None, /// Pattern names a visible scope that emits spans. Visible(Vec), /// Pattern names a structural scope used only to hold parser state. Structural(Vec), } /// Compiled metadata for one capture group. #[derive(Debug)] pub(super) struct Capture { /// Scope assigned directly to the captured group. scope: Scope, /// Scope assigned to content retokenized inside the captured group. content_scope: Scope, /// Pattern set used to retokenize the captured group. nested: Option, } /// Capture-scope mappings for a pattern's three regex slots. #[derive(Debug, Default)] pub(super) struct PatternCaptures { /// Captures applied to a single match rule. pub(super) matched: Captures, /// Captures applied to a begin-match rule. pub(super) begin: Captures, /// Captures applied to an end-match rule. pub(super) end: Captures, /// Captures applied to a while-match rule. pub(super) while_rule: Captures, } /// Match form used by a compiled pattern. #[derive(Debug)] enum PatternBody { /// Single regex match rule. Match { /// Regex source. source: String, }, /// Stateful begin/end rule. BeginEnd { /// Begin regex source (also the entry inside the parent set's RegSet). begin_source: String, /// End regex (compiled now or deferred until begin captures are known). end: EndPattern, /// Whether nested patterns take priority over the end pattern at the same position. apply_end_pattern_last: bool, }, /// Stateful begin/while rule. BeginWhile { /// Begin regex source (also the entry inside the parent set's RegSet). begin_source: String, /// While regex tested at the start of each continued line. while_rule: EndPattern, }, } /// Stable arena id for a compiled pattern set. #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] pub(super) struct PatternSetId( /// Index into [`CompiledPatterns::sets`]. usize, ); /// Compiled patterns at one nesting level plus their combined search regex. #[derive(Debug)] pub(super) struct PatternSet { /// Patterns in declaration order. pub(super) patterns: Vec, /// Ordered local patterns and includes declared in this set. entries: Vec, /// Pattern locations in flattened search order. matches: Vec, /// Combined RegSet covering flattened pattern match or begin sources. regexes: OnceCell>, } /// Lazily compiled combined regex set plus its filtered match table. #[derive(Debug)] struct SearchRegexes { /// Pattern locations in the same order as [`Self::regexes`]. matches: Vec, /// Combined Oniguruma regex set for all valid search sources. regexes: RegSet, } /// Ordered search entry inside one pattern set. #[derive(Clone, Copy, Debug)] enum PatternEntry { /// Local pattern index inside the set. Pattern(usize), /// Included pattern set searched at this point. Include(PatternSetId), } /// Compiled injection rule searched against matching scope stacks. #[derive(Debug)] pub(super) struct Injection { /// Selector that decides when this injection applies. pub(super) selector: ScopeSelector, /// Pattern set searched when the selector matches. pub(super) patterns: PatternSetId, } /// One compiled TextMate pattern with its scope, captures, and nested rules. /// /// A [`Pattern`] is what the grammar tokenizer matches against the source text. /// One match produces a [`Match`] (the higher-level result with emitted spans), /// which wraps the underlying [`RegexMatch`] (raw capture positions). #[derive(Debug)] pub(super) struct Pattern { /// Stable rule id used to reopen this pattern from line state. id: usize, /// Scope assigned by this pattern. pub(super) scope: Scope, /// Scope assigned to content inside a begin rule. pub(super) content_scope: Scope, /// Per-slot capture-scope mappings. pub(super) captures: PatternCaptures, /// Match form (single match or begin/end pair). body: PatternBody, /// Pattern set that may match inside this one. pub(super) nested: PatternSetId, } /// Begin/end rule pushed onto the parser stack and held across line boundaries. /// /// The matching [`Pattern`] is recovered through `Grammar::pattern_by_rule`, so /// the open rule itself only stores what cannot be derived from the grammar: /// the rule's id and any resolved regex source for dynamic end or while /// patterns. #[derive(Clone, Debug, Eq, PartialEq)] pub(super) struct OpenRule { /// Compiled rule id. pub(super) rule_id: usize, /// Resolved regex source for dynamic end or while patterns. pub(super) dynamic_rule: Option, /// Parent `\G` anchor restored when this rule closes. pub(super) anchor_position: Option, } /// Result of one pattern matching in a line: the byte range it covered, the /// scope spans it emitted, and any begin/end rule it pushed onto the stack. pub(super) struct Match { /// Start byte of the match in the line. pub(super) start: usize, /// End byte of the match (or of the same-line close, for begin/end rules). pub(super) end: usize, /// Scope spans emitted by the match and its captures. pub(super) spans: Vec, /// New rule pushed onto the parser stack, when this match opened one. pub(super) open_rule: Option, } /// Shared inputs for finding the next pattern and emitting capture spans. pub(super) struct PatternSearch<'line, 'sets, 'cache> { /// Pattern sets in the compiled grammar. sets: &'sets [PatternSet], /// Line being searched. line: &'line str, /// Exclusive byte limit for the search. limit: usize, /// Cache for dynamically resolved end regexes. cache: &'cache mut EndRegexCache, /// Anchor availability for this search. anchors: AnchorState, } impl<'line, 'sets, 'cache> PatternSearch<'line, 'sets, 'cache> { /// Creates a pattern search context. pub(super) fn new( sets: &'sets [PatternSet], line: &'line str, limit: usize, cache: &'cache mut EndRegexCache, anchors: AnchorState, ) -> Self { Self { sets, line, limit, cache, anchors, } } } /// Raw regex hit: byte range plus the positions of any retained capture groups. pub(super) struct RegexMatch { /// Start byte of the full regex match. pub(super) start: usize, /// End byte of the full regex match. pub(super) end: usize, /// Byte ranges for capture groups by capture index, when captures were retained. captures: Vec>, } /// Compiled grammar pattern arena and indexes. pub(super) struct CompiledPatterns { /// Root pattern set id. pub(super) root: PatternSetId, /// Compiled pattern-set arena. pub(super) sets: Vec, /// Interned scope names in id order. pub(super) scopes: Vec, /// Direct lookup from rule id to its pattern's arena location. pub(super) rule_locations: Vec>, /// Compiled runtime injections. pub(super) injections: Vec, } /// Direct arena location for a compiled rule. #[derive(Clone, Copy, Debug)] pub(super) struct RuleLocation { /// Pattern set containing the rule. pub(super) set: PatternSetId, /// Index of the rule inside the containing pattern set. pub(super) index: usize, } /// Builder-time table that assigns stable ids to scope names. #[derive(Default)] pub(super) struct ScopeInterner { /// Interned scope names in id order. pub(super) scopes: Vec, /// Lookup table from scope name to interned id. ids: BTreeMap, } /// Parsed TextMate include target. enum IncludeReference { /// `$base`. Base, /// `$self`. SelfReference, /// `#name`. Repository(String), /// `scope.name`. External(String), /// `scope.name#name`. ExternalRepository(String, String), } impl IncludeReference { /// Parses a raw include string. fn parse(include: &str) -> Self { if include == "$base" { return Self::Base; } if include == "$self" { return Self::SelfReference; } let Some((scope, name)) = include.split_once('#') else { return Self::External(include.to_owned()); }; if scope.is_empty() { Self::Repository(name.to_owned()) } else { Self::ExternalRepository(scope.to_owned(), name.to_owned()) } } } /// Compiler for one raw TextMate grammar. pub(super) struct PatternCompiler<'raw> { /// Source grammar being compiled. raw: &'raw RawGrammar, /// Raw grammars visible to cross-grammar includes. grammars: BTreeMap<&'raw str, &'raw RawGrammar>, /// Root pattern set, available while compiling `$self` includes. root: PatternSetId, /// Root pattern sets compiled for raw grammars in this arena. roots: BTreeMap<&'raw str, PatternSetId>, /// Compiled pattern-set arena. sets: Vec, /// Repository entries compiled so far. repository: BTreeMap<(&'raw str, String), PatternSetId>, /// Repository include nesting depth, used as a recursion guard. repository_depth: usize, /// Next stable rule id. next_rule: usize, /// Scope-name interner. interner: ScopeInterner, } impl Scope { /// Builds a scope from an optional raw TextMate name. fn from_raw(name: Option<&str>, interner: &mut ScopeInterner) -> Self { let Some(name) = name else { return Self::None }; let path = name .split_whitespace() .map(|scope| interner.intern(scope)) .collect::>(); // A blank or whitespace-only name interns no scopes; treat it as unscoped. if path.is_empty() { return Self::None; } if name.starts_with("meta.structure.") { Self::Structural(path) } else { Self::Visible(path) } } /// Pushes a span for this scope's region when it is visible and non-empty. pub(super) fn push_visible(&self, spans: &mut Vec, start: usize, end: usize) { if let Self::Visible(path) = self && start < end { for scope in path { spans.push(ScopeSpan { start, end, scope: *scope, }); } } } /// Extends `scopes` with every scope name carried by this scope. pub(super) fn extend_names<'grammar>( &self, names: &'grammar [String], scopes: &mut Vec<&'grammar str>, ) { match self { Self::None => {} Self::Visible(path) | Self::Structural(path) => scopes.extend( path.iter() .filter_map(|scope| names.get(scope.index()).map(String::as_str)), ), } } /// Pushes visible name and content scopes for an inner rule region. pub(super) fn push_content_visible( name: &Self, content: &Self, spans: &mut Vec, start: usize, end: usize, ) { name.push_visible(spans, start, end); content.push_visible(spans, start, end); } } impl Pattern { /// Extends `scopes` with this pattern's name and content scope names. pub(super) fn extend_scope_names<'grammar>( &self, names: &'grammar [String], scopes: &mut Vec<&'grammar str>, ) { self.scope.extend_names(names, scopes); self.content_scope.extend_names(names, scopes); } } impl Capture { /// Pushes this capture's direct and retokenized spans. fn push_spans( &self, spans: &mut Vec, start: usize, end: usize, context: &mut PatternSearch<'_, '_, '_>, ) { Scope::push_content_visible(&self.scope, &self.content_scope, spans, start, end); if let Some(nested) = self.nested { retokenize_capture(nested, spans, start, end, context); } } } /// One event found inside an open begin/end rule. pub(super) enum InsideEvent { /// Nested pattern matched before the end pattern. Nested(Match), /// End pattern closed the open rule. Close(RegexMatch), /// Neither nested nor end matched on the rest of the searched region. None, } impl InsideEvent { /// Returns the byte position this event advances to. pub(super) fn next_pos(&self, line: &str) -> usize { match self { Self::Close(close) => close.end, Self::Nested(nested) => nested.next_pos_after_open(line), Self::None => line.len(), } } } /// Returns the pattern for a rule id by scanning the pattern sets. fn pattern_by_rule(sets: &[PatternSet], rule_id: usize) -> Option<&Pattern> { sets.iter() .find_map(|set| set.patterns.iter().find(|pattern| pattern.id == rule_id)) } /// Retokenizes one captured region against a nested pattern set. /// /// This mirrors the main tokenizer loop, bounded to the region: begin/end /// rules opened inside the region are tracked on a local stack so that their /// nested patterns and end captures apply, and every emitted span is clamped /// to the region. `\G` is allowed at each step's search position, since the /// region has no begin match of its own to anchor against. fn retokenize_capture( root: PatternSetId, spans: &mut Vec, start: usize, end: usize, context: &mut PatternSearch<'_, '_, '_>, ) { let sets = context.sets; let line = &context.line[..end]; let mut search = PatternSearch::new(sets, line, end, context.cache, context.anchors); let emit_open_content = |spans: &mut Vec, stack: &[OpenRule], from: usize, to: usize| { for open in stack.iter().rev() { if let Some(pattern) = pattern_by_rule(sets, open.rule_id) { pattern.push_content_visible(spans, from, to); } } }; let mut stack = Vec::::new(); let mut pos = start; while pos < end { search.anchors.set_begin_position(pos); let event = if let Some(open) = stack.last().cloned() { let Some(pattern) = pattern_by_rule(sets, open.rule_id) else { stack.pop(); continue; }; let Some(end_regex) = pattern.resume_end(open.dynamic_rule.as_deref(), search.cache) else { stack.pop(); continue; }; pattern.next_event_inside(&end_regex, line, pos, &mut search) } else { match root.find_next(&mut search, pos) { Some(matched) => InsideEvent::Nested(matched), None => InsideEvent::None, } }; let previous_depth = stack.len(); let next_pos = match event { InsideEvent::Nested(matched) => { let next_pos = matched.next_pos_after_open(line).min(end); emit_open_content(spans, &stack, pos, next_pos); spans.extend(matched.spans.into_iter().filter_map(|mut span| { span.end = span.end.min(end); (span.start < span.end).then_some(span) })); if let Some(opened) = matched.open_rule { stack.push(opened); } next_pos } InsideEvent::Close(close) => { emit_open_content(spans, &stack, pos, close.start); if let Some(pattern) = stack .last() .and_then(|open| pattern_by_rule(sets, open.rule_id)) { pattern.append_capture_spans(&close, &pattern.captures.end, spans, &mut search); } stack.pop(); close.end.min(end) } InsideEvent::None => { emit_open_content(spans, &stack, pos, end); break; } }; // A match either advances or opens a rule; otherwise skip one byte. if next_pos > pos || stack.len() != previous_depth { pos = next_pos; } else { pos = (pos + 1).min(end); } } } impl ScopeInterner { /// Returns the id for a scope, inserting it when needed. fn intern(&mut self, scope: &str) -> ScopeId { if let Some(id) = self.ids.get(scope) { return *id; } let id = ScopeId::new(self.scopes.len()); self.scopes.push(scope.to_owned()); self.ids.insert(scope.to_owned(), id); id } } impl PatternSetId { /// Creates a pattern-set id from an arena index. pub(super) fn new(index: usize) -> Self { Self(index) } /// Returns this id's pattern-set arena index. pub(super) fn index(self) -> usize { self.0 } /// Finds the next pattern match in this set or its included sets. pub(super) fn find_next( self, search: &mut PatternSearch<'_, '_, '_>, pos: usize, ) -> Option { search .sets .get(self.index()) .and_then(|set| set.find_next(search, pos)) } } impl PatternSet { /// Creates an empty pattern set. pub(super) fn empty() -> Self { Self { patterns: Vec::new(), entries: Vec::new(), matches: Vec::new(), regexes: OnceCell::new(), } } /// Builds a pattern set from local patterns and declaration-order search entries. fn new(patterns: Vec, entries: Vec) -> Self { Self { patterns, entries, matches: Vec::new(), regexes: OnceCell::new(), } } /// Finds the next flattened pattern match at or after `pos`. fn find_next(&self, search: &mut PatternSearch<'_, '_, '_>, pos: usize) -> Option { if pos > search.limit || search.limit > search.line.len() || !search.line.is_char_boundary(pos) { return None; } let search_regexes = self.regexes(search.sets)?; let (entry, captures) = search_regexes.regexes.captures_with_options( search.line, pos, search.limit, RegSetLead::Position, search.anchors.search_options(pos), )?; let location = search_regexes.matches.get(entry)?; let pattern = search .sets .get(location.set.index())? .patterns .get(location.index)?; let regex_match = RegexMatch::from_captures(captures, pattern.needs_match_captures())?; pattern.match_result(regex_match, search) } /// Returns the compiled search regex set, building it on first use. fn regexes(&self, sets: &[PatternSet]) -> Option<&SearchRegexes> { self.regexes .get_or_init(|| SearchRegexes::new(&self.matches, sets)) .as_ref() } } impl SearchRegexes { /// Compiles a combined search set, filtering invalid sources only on failure. fn new(matches: &[RuleLocation], sets: &[PatternSet]) -> Option { if matches.is_empty() { return None; } let mut compiled_matches = Vec::new(); let mut sources = Vec::new(); for location in matches { let Some(source) = search_source(sets, *location) else { continue; }; compiled_matches.push(*location); sources.push(source); } if sources.is_empty() { return None; } if let Ok(regexes) = RegSet::with_options(&sources, TEXTMATE_REGEX_OPTIONS) { return Some(Self { matches: compiled_matches, regexes, }); } let mut valid_matches = Vec::new(); let mut sources = Vec::new(); for location in matches { let Some(source) = search_source(sets, *location) else { continue; }; if regex(source).is_ok() { valid_matches.push(*location); sources.push(source); } } if sources.is_empty() { return None; } RegSet::with_options(&sources, TEXTMATE_REGEX_OPTIONS) .ok() .map(|regexes| Self { matches: valid_matches, regexes, }) } } /// Returns the search regex source for a flattened pattern location. fn search_source(sets: &[PatternSet], location: RuleLocation) -> Option<&str> { sets.get(location.set.index())? .patterns .get(location.index) .map(Pattern::search_source) } impl<'raw> PatternCompiler<'raw> { /// Creates a compiler for a raw grammar. pub(super) fn new(raw: &'raw RawGrammar, dependencies: &'raw [RawGrammar]) -> Self { let mut grammars = BTreeMap::new(); for dependency in dependencies { grammars.insert(dependency.scope_name.as_str(), dependency); } grammars.insert(raw.scope_name.as_str(), raw); PatternCompiler { raw, grammars, root: PatternSetId::new(0), roots: BTreeMap::new(), sets: Vec::new(), repository: BTreeMap::new(), repository_depth: 0, next_rule: 0, interner: ScopeInterner::default(), } } /// Compiles the grammar's root pattern set and any referenced repository sets. pub(super) fn compile(mut self) -> Result { let root = self.reserve_set(); self.root = root; self.roots.insert(self.raw.scope_name.as_str(), root); let root_set = self.compile_patterns( self.raw, &self.raw.patterns, &mut vec![&self.raw.repository], )?; self.assign_set(root, root_set); let injections = self.compile_injections()?; self.compile_searches(); let rule_locations = self.rule_locations(); Ok(CompiledPatterns { root, sets: self.sets, scopes: self.interner.scopes, rule_locations, injections, }) } /// Reserves an empty pattern-set slot and returns its id. fn reserve_set(&mut self) -> PatternSetId { let id = PatternSetId::new(self.sets.len()); self.sets.push(PatternSet::empty()); id } /// Assigns a compiled pattern set to a reserved slot. fn assign_set(&mut self, id: PatternSetId, set: PatternSet) { self.sets[id.index()] = set; } /// Compiles raw TextMate patterns into one pattern set. fn compile_patterns( &mut self, current: &'raw RawGrammar, patterns: &'raw [RawPattern], repositories: &mut Vec<&'raw BTreeMap>, ) -> Result { let mut compiled = Vec::new(); let mut entries = Vec::new(); for pattern in patterns { if let Some(include) = &pattern.include { if let Some(include) = self.compile_include(current, include, repositories)? { entries.push(PatternEntry::Include(include)); } continue; } self.compile_pattern(current, pattern, repositories, &mut compiled, &mut entries)?; } Ok(PatternSet::new(compiled, entries)) } /// Compiles one raw pattern into the current pattern-set builder. fn compile_pattern( &mut self, current: &'raw RawGrammar, pattern: &'raw RawPattern, repositories: &mut Vec<&'raw BTreeMap>, compiled: &mut Vec, entries: &mut Vec, ) -> Result<(), Error> { let scope = Scope::from_raw(pattern.name.as_deref(), &mut self.interner); let body = match ( &pattern.match_rule, &pattern.begin, &pattern.end, &pattern.while_rule, ) { (Some(source), _, _, _) => PatternBody::Match { source: source.clone(), }, (None, Some(begin), Some(end), _) => { let Some(end) = EndPattern::compile(end) else { return Ok(()); }; PatternBody::BeginEnd { begin_source: begin.clone(), end, apply_end_pattern_last: truthy_flag(pattern.apply_end_pattern_last.as_ref()), } } (None, Some(begin), None, Some(while_rule)) => { let Some(while_rule) = EndPattern::compile(while_rule) else { return Ok(()); }; PatternBody::BeginWhile { begin_source: begin.clone(), while_rule, } } _ => { self.inline_patterns(current, pattern, repositories, compiled, entries)?; return Ok(()); } }; // Nested children are compiled — and assigned their rule ids — before // this pattern, so every parent has a higher rule id than its children. let nested = self.compile_nested_set(current, &pattern.patterns, repositories)?; let id = self.next_rule; self.next_rule += 1; // The slot-specific capture maps fall back to the shared `captures` map. let shared = pattern.captures.as_ref(); let matched = self.captures(current, shared, repositories)?; let begin = self.captures( current, pattern.begin_captures.as_ref().or(shared), repositories, )?; let end = self.captures( current, pattern.end_captures.as_ref().or(shared), repositories, )?; let while_rule = self.captures( current, pattern.while_captures.as_ref().or(shared), repositories, )?; let index = compiled.len(); compiled.push(Pattern { id, scope, content_scope: Scope::from_raw(pattern.content_name.as_deref(), &mut self.interner), captures: PatternCaptures { matched, begin, end, while_rule, }, body, nested, }); entries.push(PatternEntry::Pattern(index)); Ok(()) } /// Compiles grouping pattern children directly into the parent builder. fn inline_patterns( &mut self, current: &'raw RawGrammar, pattern: &'raw RawPattern, repositories: &mut Vec<&'raw BTreeMap>, compiled: &mut Vec, entries: &mut Vec, ) -> Result<(), Error> { let offset = compiled.len(); let inline = self.compile_patterns(current, &pattern.patterns, repositories)?; compiled.extend(inline.patterns); entries.extend(inline.entries.into_iter().map(|entry| match entry { PatternEntry::Pattern(index) => PatternEntry::Pattern(index + offset), PatternEntry::Include(id) => PatternEntry::Include(id), })); Ok(()) } /// Compiles a nested pattern set into the arena and returns its id. fn compile_nested_set( &mut self, current: &'raw RawGrammar, patterns: &'raw [RawPattern], repositories: &mut Vec<&'raw BTreeMap>, ) -> Result { let id = self.reserve_set(); let set = self.compile_patterns(current, patterns, repositories)?; self.assign_set(id, set); Ok(id) } /// Compiles an include target into a pattern-set reference. fn compile_include( &mut self, current: &'raw RawGrammar, include: &str, repositories: &mut Vec<&'raw BTreeMap>, ) -> Result, Error> { match IncludeReference::parse(include) { IncludeReference::Base => Ok(Some(self.root)), IncludeReference::SelfReference => self.compile_root(current), IncludeReference::Repository(name) => { self.compile_repository_entry(current, &name, repositories) } IncludeReference::External(scope) => { let Some(grammar) = self.grammars.get(scope.as_str()).copied() else { return Ok(None); }; self.compile_external_root(grammar) } IncludeReference::ExternalRepository(scope, name) => { let Some(grammar) = self.grammars.get(scope.as_str()).copied() else { return Ok(None); }; self.compile_external_repository_entry(grammar, &name) } } } /// Compiles one raw grammar root once and returns its pattern-set id. fn compile_root(&mut self, raw: &'raw RawGrammar) -> Result, Error> { if let Some(id) = self.roots.get(raw.scope_name.as_str()) { return Ok(Some(*id)); } let id = self.reserve_set(); self.roots.insert(raw.scope_name.as_str(), id); let set = self.compile_patterns(raw, &raw.patterns, &mut vec![&raw.repository])?; self.assign_set(id, set); Ok(Some(id)) } /// Compiles one external raw grammar root with an independent include budget. fn compile_external_root( &mut self, raw: &'raw RawGrammar, ) -> Result, Error> { let depth = self.repository_depth; self.repository_depth = 0; let root = self.compile_root(raw); self.repository_depth = depth; root } /// Compiles one external repository entry with an independent include budget. fn compile_external_repository_entry( &mut self, raw: &'raw RawGrammar, name: &str, ) -> Result, Error> { let depth = self.repository_depth; self.repository_depth = 0; let entry = self.compile_repository_entry(raw, name, &mut vec![&raw.repository]); self.repository_depth = depth; entry } /// Compiles one repository entry once and returns its pattern-set id. fn compile_repository_entry( &mut self, current: &'raw RawGrammar, name: &str, repositories: &mut Vec<&'raw BTreeMap>, ) -> Result, Error> { let Some((pattern, top_level)) = repositories.iter().rev().find_map(|repository| { repository.get(name).map(|pattern| { let top_level = std::ptr::eq(*repository, ¤t.repository); (pattern, top_level) }) }) else { return Ok(None); }; let key = (current.scope_name.as_str(), name.to_owned()); if top_level && let Some(id) = self.repository.get(&key) { return Ok(Some(*id)); } if self.repository_depth > MAX_INCLUDE_DEPTH { return Ok(None); } let id = self.reserve_set(); if top_level { self.repository.insert(key, id); } self.repository_depth += 1; let set = self.compile_patterns(current, std::slice::from_ref(pattern), repositories)?; self.repository_depth -= 1; self.assign_set(id, set); Ok(Some(id)) } /// Compiles injections from the root grammar. fn compile_injections(&mut self) -> Result, Error> { let mut injections = Vec::new(); for (selector, pattern) in &self.raw.injections { let patterns = self.compile_nested_set( self.raw, std::slice::from_ref(pattern), &mut vec![&self.raw.repository], )?; for selector in ScopeSelector::parse_all(selector) { injections.push(Injection { selector, patterns }); } } injections.sort_by_key(|injection| injection.selector.priority); Ok(injections) } /// Compiles flattened regex search sets after all pattern sets are assigned. fn compile_searches(&mut self) { let mut searches = Vec::with_capacity(self.sets.len()); for index in 0..self.sets.len() { let mut active = Vec::new(); let mut collected = Vec::new(); self.collect_search_entries(PatternSetId::new(index), &mut active, &mut collected); searches.push(collected); } for (set, matches) in self.sets.iter_mut().zip(searches) { set.matches = matches; } } /// Collects the declaration-order patterns searched for `set`. fn collect_search_entries( &self, set: PatternSetId, active: &mut Vec, matches: &mut Vec, ) { if active.contains(&set) || active.len() > MAX_INCLUDE_DEPTH { return; } let Some(pattern_set) = self.sets.get(set.index()) else { return; }; active.push(set); for entry in &pattern_set.entries { match entry { PatternEntry::Pattern(index) => matches.push(RuleLocation { set, index: *index }), PatternEntry::Include(include) => { self.collect_search_entries(*include, active, matches); } } } active.pop(); } /// Compiles capture metadata. fn captures( &mut self, current: &'raw RawGrammar, raw: Option<&'raw BTreeMap>, repositories: &mut Vec<&'raw BTreeMap>, ) -> Result { let mut captures = Captures::new(); let Some(raw) = raw else { return Ok(captures); }; for (index, capture) in raw { let Ok(scope_index) = index.parse() else { continue; }; let nested = if capture.patterns.is_empty() { None } else { Some(self.compile_nested_set(current, &capture.patterns, repositories)?) }; captures.insert( scope_index, Capture { scope: Scope::from_raw(capture.name.as_deref(), &mut self.interner), content_scope: Scope::from_raw( capture.content_name.as_deref(), &mut self.interner, ), nested, }, ); } Ok(captures) } /// Builds direct rule-id lookups after compilation. fn rule_locations(&self) -> Vec> { let mut locations = vec![None; self.next_rule]; for (set_index, set) in self.sets.iter().enumerate() { let set_id = PatternSetId::new(set_index); for (index, pattern) in set.patterns.iter().enumerate() { if let Some(slot) = locations.get_mut(pattern.id) { *slot = Some(RuleLocation { set: set_id, index }); } } } locations } } impl Pattern { /// Pushes this pattern's name and content scopes over an inner-region range. pub(super) fn push_content_visible( &self, spans: &mut Vec, start: usize, end: usize, ) { Scope::push_content_visible(&self.scope, &self.content_scope, spans, start, end); } /// Returns the active end regex when reopening this pattern from line state. pub(super) fn resume_end<'pat>( &'pat self, dynamic_rule: Option<&str>, cache: &mut EndRegexCache, ) -> Option> { let PatternBody::BeginEnd { end, .. } = &self.body else { return None; }; end.resume(dynamic_rule, cache) } /// Finds this rule's while match at the start of a continued line. pub(super) fn while_match( &self, dynamic_while: Option<&str>, line: &str, cache: &mut EndRegexCache, anchors: AnchorState, ) -> Option { let PatternBody::BeginWhile { while_rule, .. } = &self.body else { return None; }; let while_regex = while_rule.resume(dynamic_while, cache)?; let matched = RegexMatch::find( while_regex.regex(), line, 0, !self.captures.while_rule.is_empty(), anchors, )?; // The while pattern must anchor at column 0; a search from offset 0 can // still return a later match, which does not count as a continuation. (matched.start == 0).then_some(matched) } /// Returns true when nested patterns should win same-position end matches. pub(super) fn apply_end_pattern_last(&self) -> bool { matches!( &self.body, PatternBody::BeginEnd { apply_end_pattern_last: true, .. } ) } /// Finds this rule's end match at or after `pos`. pub(super) fn find_end_match( &self, end: &EndRegex<'_>, line: &str, mut pos: usize, anchors: AnchorState, ) -> Option { loop { let matched = RegexMatch::find_end( end.regex(), line, pos, !self.captures.end.is_empty(), anchors, )?; if matches!(end.source(), "\"" | "'") && is_escaped_at(line, matched.start) { pos = matched.next_pos(line); continue; } return Some(matched); } } /// Finds the next event inside this open rule: a nested pattern match, the /// end pattern closing the rule, or neither within the search limit. /// /// The end pattern is searched on `line`, which may extend past the search /// limit; an end match counts only when it starts inside the limit. pub(super) fn next_event_inside( &self, end: &EndRegex<'_>, line: &str, pos: usize, search: &mut PatternSearch<'_, '_, '_>, ) -> InsideEvent { let nested = self.nested.find_next(search, pos); let close = self .find_end_match(end, line, pos, search.anchors) .filter(|close| close.start <= search.limit); match (nested, close) { (Some(nested), Some(close)) if nested.start < close.start || (self.apply_end_pattern_last() && nested.start == close.start) => { InsideEvent::Nested(nested) } (_, Some(close)) => InsideEvent::Close(close), (Some(nested), None) => InsideEvent::Nested(nested), (None, None) => InsideEvent::None, } } /// Adds capture-group spans plus the pattern's own scope span for one regex match. pub(super) fn append_match_spans( &self, matched: &RegexMatch, captures: &Captures, spans: &mut Vec, context: &mut PatternSearch<'_, '_, '_>, ) { self.scope.push_visible(spans, matched.start, matched.end); self.append_capture_spans(matched, captures, spans, context); spans.sort_by_key(|span| (span.start, span.end)); } /// Adds capture-group spans for one regex match. pub(super) fn append_capture_spans( &self, matched: &RegexMatch, captures: &Captures, spans: &mut Vec, context: &mut PatternSearch<'_, '_, '_>, ) { for (index, capture) in captures { if let Some(Some((start, end))) = matched.captures.get(*index) && *start < *end { capture.push_spans(spans, *start, *end, context); } } } /// Whether match-time regex captures must be retained. fn needs_match_captures(&self) -> bool { match &self.body { PatternBody::Match { .. } => !self.captures.matched.is_empty(), PatternBody::BeginEnd { end, .. } => { !self.captures.begin.is_empty() || end.is_dynamic() } PatternBody::BeginWhile { while_rule, .. } => { !self.captures.begin.is_empty() || !self.captures.while_rule.is_empty() || while_rule.is_dynamic() } } } /// The regex source used in the parent set's combined `RegSet`. fn search_source(&self) -> &str { match &self.body { PatternBody::Match { source } => source, PatternBody::BeginEnd { begin_source, .. } => begin_source, PatternBody::BeginWhile { begin_source, .. } => begin_source, } } /// Builds a [`Match`] for one regex hit, dispatching by body kind. fn match_result( &self, regex_match: RegexMatch, search: &mut PatternSearch<'_, '_, '_>, ) -> Option { match &self.body { PatternBody::Match { .. } => Some(self.simple_match(regex_match, search)), PatternBody::BeginEnd { end, .. } => self.begin_match(end, regex_match, search), PatternBody::BeginWhile { .. } => Some(self.begin_while_match(regex_match, search)), } } /// Builds a match for a single-line match rule. fn simple_match( &self, regex_match: RegexMatch, search: &mut PatternSearch<'_, '_, '_>, ) -> Match { let mut spans = Vec::new(); self.append_match_spans(®ex_match, &self.captures.matched, &mut spans, search); Match { start: regex_match.start, end: regex_match.end, spans, open_rule: None, } } /// Builds a match for a begin/end rule, eagerly closing on the same line if possible. fn begin_match( &self, end_pattern: &EndPattern, begin: RegexMatch, search: &mut PatternSearch<'_, '_, '_>, ) -> Option { let end_regex = end_pattern.resolve_for_begin(&begin, search.line, search.cache)?; let dynamic_rule = end_regex.dynamic_source(); let mut spans = Vec::new(); self.append_match_spans(&begin, &self.captures.begin, &mut spans, search); Some(Match { start: begin.start, end: begin.end, spans, open_rule: Some(OpenRule { rule_id: self.id, dynamic_rule, anchor_position: search.anchors.begin_position(), }), }) } /// Builds a match for a begin/while rule. fn begin_while_match( &self, begin: RegexMatch, search: &mut PatternSearch<'_, '_, '_>, ) -> Match { let PatternBody::BeginWhile { while_rule, .. } = &self.body else { return self.simple_match(begin, search); }; let while_regex = while_rule.resolve_for_begin(&begin, search.line, search.cache); let dynamic_rule = while_regex.and_then(|while_regex| while_regex.dynamic_source()); let mut spans = Vec::new(); self.append_match_spans(&begin, &self.captures.begin, &mut spans, search); self.scope.push_visible(&mut spans, begin.start, begin.end); Match { start: begin.start, end: begin.end, spans, open_rule: Some(OpenRule { rule_id: self.id, dynamic_rule, anchor_position: search.anchors.begin_position(), }), } } } /// Whether the byte at `pos` is preceded by an odd number of backslashes. fn is_escaped_at(line: &str, pos: usize) -> bool { if pos > line.len() || !line.is_char_boundary(pos) { return false; } line[..pos] .bytes() .rev() .take_while(|byte| *byte == b'\\') .count() % 2 == 1 } impl Match { /// Returns the next byte position after this match, ensuring forward progress. pub(super) fn next_pos(&self, line: &str) -> usize { next_pos_after(line, self.start, self.end) } /// Returns the next byte position after opening this rule. pub(super) fn next_pos_after_open(&self, line: &str) -> usize { if self.open_rule.is_some() && self.start == self.end { self.start } else { self.next_pos(line) } } } impl RegexMatch { /// Finds one regex match starting at `pos`. pub(super) fn find( regex: &Regex, line: &str, pos: usize, keep_captures: bool, anchors: AnchorState, ) -> Option { if pos > line.len() || !line.is_char_boundary(pos) { return None; } let mut region = Region::new(); let _ = regex.search_with_options( line, pos, line.len(), anchors.search_options(pos), Some(&mut region), )?; let (start, end) = region.pos(0)?; if start > end || end > line.len() { return None; } let captures = if keep_captures { (0..region.len()) .map(|index| { region.pos(index).and_then(|(start, end)| { (start <= end && end <= line.len()).then_some((start, end)) }) }) .collect() } else { Vec::new() }; Some(Self { start, end, captures, }) } /// Finds one end-regex match at or after `pos`. pub(super) fn find_end( regex: &Regex, line: &str, pos: usize, keep_captures: bool, anchors: AnchorState, ) -> Option { if let Some(matched) = Self::find(regex, line, pos, keep_captures, anchors) { return Some(matched); } let search = pos.checked_sub(1)?; let matched = Self::find(regex, line, search, keep_captures, anchors)?; (matched.start >= pos).then_some(matched) } /// Builds a match record from Oniguruma captures. fn from_captures(captures: onig::Captures<'_>, keep_captures: bool) -> Option { let (start, end) = captures.pos(0)?; let captures = if keep_captures { (0..captures.len()) .map(|index| captures.pos(index)) .collect() } else { Vec::new() }; Some(Self { start, end, captures, }) } /// Returns the next byte position after this regex match. pub(super) fn next_pos(&self, line: &str) -> usize { next_pos_after(line, self.start, self.end) } /// Returns the captured text for one group, or `None` when the group is unset. pub(super) fn capture_text<'a>(&self, index: usize, line: &'a str) -> Option<&'a str> { let (start, end) = self.captures.get(index)?.as_ref().copied()?; line.get(start..end) } /// Substitutes this match's captures into a regex template containing /// backslash-prefixed numeric backreferences (`\1`, `\2`, …). /// /// Captured text is regex-escaped before substitution so that metacharacters /// in the source line are matched literally on the next invocation. pub(super) fn expand_backrefs(&self, template: &str, line: &str) -> String { let mut resolved = String::new(); let mut chars = template.chars(); while let Some(ch) = chars.next() { if ch != '\\' { resolved.push(ch); continue; } let Some(next) = chars.next() else { resolved.push(ch); break; }; if let Some(index) = next.to_digit(10) && let Some(text) = self.capture_text(index as usize, line) { push_regex_escaped(&mut resolved, text); } else { resolved.push(ch); resolved.push(next); } } resolved } } /// Appends `input` to `out`, escaping any regex metacharacters. fn push_regex_escaped(out: &mut String, input: &str) { const META: &[char] = &[ '\\', '.', '+', '*', '?', '(', ')', '|', '[', ']', '{', '}', '^', '$', ]; for ch in input.chars() { if META.contains(&ch) { out.push('\\'); } out.push(ch); } } /// Returns a forward-progress position after a possibly-empty regex match. fn next_pos_after(line: &str, start: usize, end: usize) -> usize { if end > start { end } else { next_char_boundary(line, start.saturating_add(1)) } } #[cfg(test)] #[allow(clippy::unwrap_used)] mod tests { use std::str::FromStr; use super::*; #[test] fn invalid_regex_offsets_are_ignored() { let regex = Regex::new("\"").unwrap(); let anchors = AnchorState::new(true); assert!( RegexMatch::find(®ex, r#" "patterns": ["#, usize::MAX, true, anchors).is_none() ); assert!(RegexMatch::find(®ex, "é", 1, true, anchors).is_none()); } #[test] fn regex_match_offsets_are_absolute_after_full_line_search() { let regex = Regex::new("(bar)").unwrap(); let matched = RegexMatch::find(®ex, "foobar", 3, true, AnchorState::new(true)).unwrap(); assert_eq!(matched.start, 3); assert_eq!(matched.end, 6); assert_eq!(matched.captures[1], Some((3, 6))); } #[test] fn line_tokenizer_caches_dynamic_end_regexes() { let grammar = Grammar::from_str( r#"{ "name":"Demo", "scopeName":"source.demo", "patterns":[ { "begin":"<([A-Za-z.]+)>", "end":"", "name":"meta.tag.demo" } ], "repository":{} }"#, ) .unwrap(); let mut tokenizer = LineTokenizer::new(&grammar); let mut state = LineState::default(); let mut spans = Vec::new(); tokenizer.tokenize_line_into(&mut state, "", &mut spans); assert_eq!(tokenizer.end_regex_cache_len(), 1); tokenizer.tokenize_line_into(&mut state, "body", &mut spans); assert_eq!(tokenizer.end_regex_cache_len(), 1); tokenizer.tokenize_line_into(&mut state, "", &mut spans); assert!(state.is_empty()); assert_eq!(tokenizer.end_regex_cache_len(), 1); } }