//! Runtime line tokenization for compiled grammars. //! //! Each step picks the next event in the line — a fresh root-pattern match, a //! nested match inside the currently open begin/end rule, or that rule's end — //! emits the spans it produces, and updates the parser state accordingly. use super::end::EndRegexCache; use super::pattern::{InsideEvent, Match, OpenRule, Pattern, PatternSearch}; use super::selector::InjectionPriority; use super::*; /// Maximum consecutive grammar events allowed without consuming source text. /// /// Zero-width begin and end rules can legitimately nest at one position, but /// a malformed or mutually recursive pair must not trap the tokenizer there. const MAX_ZERO_WIDTH_EVENTS: usize = MAX_INCLUDE_DEPTH * 2; /// Reusable line tokenizer for one compiled grammar. /// /// The tokenizer keeps runtime scratch that is not part of immutable grammar /// data, such as dynamically resolved end regexes. Reuse one tokenizer across /// a blob or visible range to avoid recompiling those regexes unnecessarily. #[derive(Debug)] pub struct LineTokenizer<'grammar> { /// Grammar this tokenizer emits scopes for. pub(crate) grammar: &'grammar Grammar, /// Cache of compiled regexes for resolved dynamic end patterns. cache: EndRegexCache, } impl<'grammar> LineTokenizer<'grammar> { /// Creates a tokenizer for a compiled grammar. pub fn new(grammar: &'grammar Grammar) -> Self { Self { grammar, cache: EndRegexCache::new(), } } /// Clears cached dynamic end regexes while retaining allocations. pub fn clear(&mut self) { self.cache.clear(); } /// Tokenizes one line, mutating the caller-owned line state. pub fn tokenize_line(&mut 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( &mut self, state: &mut LineState, line: &str, spans: &mut Vec, ) { spans.clear(); if matches!(self.grammar.kind, GrammarKind::Json) { json::tokenize_line_into(line, spans); return; } let visible = trim_line_end(line); let visible_len = visible.len(); let mut line = String::with_capacity(visible_len + 1); line.push_str(visible); line.push('\n'); let mut anchors = AnchorState::new(state.first_line); let mut pos = self.check_while_conditions(state, &line, spans, &mut anchors); let mut zero_width_events = 0; while pos < line.len() { let next = self.advance(state, &line, pos, spans, &mut anchors); if next == pos { zero_width_events += 1; if zero_width_events >= MAX_ZERO_WIDTH_EVENTS { pos = next_char_boundary(&line, pos.saturating_add(1)); zero_width_events = 0; } } else { pos = next; zero_width_events = 0; } } self.close_empty_rules_at_end(state, &line, spans, &mut anchors); clamp_spans(spans, visible_len); state.first_line = false; } /// Performs one tokenization step and returns the next byte position. fn advance( &mut self, state: &mut LineState, line: &str, pos: usize, spans: &mut Vec, anchors: &mut AnchorState, ) -> usize { if let Some(open) = state.stack.last().cloned() { self.advance_inside_open_rule(state, line, pos, spans, open, anchors) } else { self.advance_at_root(state, line, pos, spans, anchors) } } /// Advances past one root-level pattern match, or to end of line if there is none. fn advance_at_root( &mut self, state: &mut LineState, line: &str, pos: usize, spans: &mut Vec, anchors: &mut AnchorState, ) -> usize { let found = self.match_rule_or_injections(self.grammar.patterns, state, line, pos, *anchors); let Some(found) = found else { return line.len(); }; let next_pos = found.next_pos_after_open(line); let opened = found.open_rule; let anchor = found.end; spans.extend(found.spans); if let Some(opened) = opened { state.stack.push(opened); anchors.set_begin_position(anchor); } next_pos } /// Advances past one event inside the currently open begin/end rule. fn advance_inside_open_rule( &mut self, state: &mut LineState, line: &str, pos: usize, spans: &mut Vec, open: OpenRule, anchors: &mut AnchorState, ) -> usize { let Some(pattern) = self.grammar.pattern_by_rule(open.rule_id) else { state.stack.pop(); return pos; }; let Some(end) = pattern.resume_end(open.dynamic_rule.as_deref(), &mut self.cache) else { return self.advance_inside_while_rule(state, line, pos, spans, pattern, anchors); }; let mut search = PatternSearch::new( &self.grammar.pattern_sets, line, line.len(), &mut self.cache, *anchors, ); let event = pattern.next_event_inside(&end, line, pos, &mut search); let next_pos = event.next_pos(line); // Parent rules wrap the whole span consumed by this step; the current // rule's own content scope is emitted below for each event. if let Some((_current, parents)) = state.stack.split_last() { for open in parents { if let Some(pattern) = self.grammar.pattern_by_rule(open.rule_id) { pattern.push_content_visible(spans, pos, next_pos); } } } match event { InsideEvent::Close(close) => { pattern.push_content_visible(spans, pos, close.start); pattern.append_match_spans(&close, &pattern.captures.end, spans, &mut search); if let Some(closed) = state.stack.pop() { anchors.restore_begin_position(closed.anchor_position); } } InsideEvent::Nested(nested) => { let anchor = nested.end; let opened = nested.open_rule; pattern.push_content_visible(spans, pos, next_pos); spans.extend(nested.spans); if let Some(opened) = opened { state.stack.push(opened); anchors.set_begin_position(anchor); } } InsideEvent::None => { pattern.push_content_visible(spans, pos, next_pos); } } next_pos } /// Checks active begin/while rules before scanning a continued line. fn check_while_conditions( &mut self, state: &mut LineState, line: &str, spans: &mut Vec, anchors: &mut AnchorState, ) -> usize { let mut pos = 0; let mut index = 0; while index < state.stack.len() { let Some(pattern) = self.grammar.pattern_by_rule(state.stack[index].rule_id) else { state.stack.truncate(index); break; }; let Some(matched) = pattern.while_match( state.stack[index].dynamic_rule.as_deref(), line, &mut self.cache, *anchors, ) else { if pattern .resume_end(state.stack[index].dynamic_rule.as_deref(), &mut self.cache) .is_none() { state.stack.truncate(index); break; } index += 1; continue; }; let mut context = PatternSearch::new( &self.grammar.pattern_sets, line, line.len(), &mut self.cache, *anchors, ); pattern.append_capture_spans( &matched, &pattern.captures.while_rule, spans, &mut context, ); anchors.set_begin_position(matched.end); pos = pos.max(matched.end); index += 1; } spans.sort_by_key(|span| (span.start, span.end)); pos } /// Advances past one nested event inside an open begin/while rule. fn advance_inside_while_rule( &mut self, state: &mut LineState, line: &str, pos: usize, spans: &mut Vec, pattern: &Pattern, anchors: &mut AnchorState, ) -> usize { let nested = self.match_rule_or_injections(pattern.nested, state, line, pos, *anchors); let Some(nested) = nested else { pattern.push_content_visible(spans, pos, line.len()); return line.len(); }; let next_pos = nested.next_pos_after_open(line); let opened = nested.open_rule; let anchor = nested.end; pattern.push_content_visible(spans, pos, next_pos); spans.extend(nested.spans); if let Some(opened) = opened { state.stack.push(opened); anchors.set_begin_position(anchor); } next_pos } /// Returns the next normal grammar or injected pattern match. fn match_rule_or_injections( &mut self, patterns: PatternSetId, state: &LineState, line: &str, pos: usize, anchors: AnchorState, ) -> Option { let mut found = { let mut search = PatternSearch::new( &self.grammar.pattern_sets, line, line.len(), &mut self.cache, anchors, ); patterns.find_next(&mut search, pos) }; if self.grammar.injections.is_empty() { return found; } let mut scopes = Vec::new(); self.grammar.scope_names_for_state(state, &mut scopes); for injection in &self.grammar.injections { if !injection.selector.matches(&scopes) { continue; } let mut search = PatternSearch::new( &self.grammar.pattern_sets, line, line.len(), &mut self.cache, anchors, ); let Some(candidate) = injection.patterns.find_next(&mut search, pos) else { continue; }; found = match found { Some(current) if current.start < candidate.start || (current.start == candidate.start && injection.selector.priority != InjectionPriority::Left) => { Some(current) } _ => Some(candidate), }; } found } /// Closes zero-width end rules that match at the end of a line. fn close_empty_rules_at_end( &mut self, state: &mut LineState, line: &str, spans: &mut Vec, anchors: &mut AnchorState, ) { while !state.is_empty() { let depth = state.depth(); let pos = self.advance(state, line, line.len(), spans, anchors); if pos != line.len() || state.depth() >= depth { break; } } } /// Returns the number of cached dynamic end regexes (test helper). #[cfg(test)] pub(super) fn end_regex_cache_len(&self) -> usize { self.cache.len() } } /// Trims token spans back to the caller-visible line range. fn clamp_spans(spans: &mut Vec, visible_len: usize) { spans.retain_mut(|span| { span.end = span.end.min(visible_len); span.start < span.end }); }