crates/highlight/src/grammar/tokenize.rs 12.0 KiB raw
1
//! Runtime line tokenization for compiled grammars.
2
//!
3
//! Each step picks the next event in the line — a fresh root-pattern match, a
4
//! nested match inside the currently open begin/end rule, or that rule's end —
5
//! emits the spans it produces, and updates the parser state accordingly.
6
7
use super::end::EndRegexCache;
8
use super::pattern::{InsideEvent, Match, OpenRule, Pattern, PatternSearch};
9
use super::selector::InjectionPriority;
10
use super::*;
11
12
/// Maximum consecutive grammar events allowed without consuming source text.
13
///
14
/// Zero-width begin and end rules can legitimately nest at one position, but
15
/// a malformed or mutually recursive pair must not trap the tokenizer there.
16
const MAX_ZERO_WIDTH_EVENTS: usize = MAX_INCLUDE_DEPTH * 2;
17
18
/// Reusable line tokenizer for one compiled grammar.
19
///
20
/// The tokenizer keeps runtime scratch that is not part of immutable grammar
21
/// data, such as dynamically resolved end regexes. Reuse one tokenizer across
22
/// a blob or visible range to avoid recompiling those regexes unnecessarily.
23
#[derive(Debug)]
24
pub struct LineTokenizer<'grammar> {
25
    /// Grammar this tokenizer emits scopes for.
26
    pub(crate) grammar: &'grammar Grammar,
27
    /// Cache of compiled regexes for resolved dynamic end patterns.
28
    cache: EndRegexCache,
29
}
30
31
impl<'grammar> LineTokenizer<'grammar> {
32
    /// Creates a tokenizer for a compiled grammar.
33
    pub fn new(grammar: &'grammar Grammar) -> Self {
34
        Self {
35
            grammar,
36
            cache: EndRegexCache::new(),
37
        }
38
    }
39
40
    /// Clears cached dynamic end regexes while retaining allocations.
41
    pub fn clear(&mut self) {
42
        self.cache.clear();
43
    }
44
45
    /// Tokenizes one line, mutating the caller-owned line state.
46
    pub fn tokenize_line(&mut self, state: &mut LineState, line: &str) -> Vec<ScopeSpan> {
47
        let mut spans = Vec::new();
48
        self.tokenize_line_into(state, line, &mut spans);
49
        spans
50
    }
51
52
    /// Tokenizes one line into a caller-owned buffer.
53
    pub fn tokenize_line_into(
54
        &mut self,
55
        state: &mut LineState,
56
        line: &str,
57
        spans: &mut Vec<ScopeSpan>,
58
    ) {
59
        spans.clear();
60
61
        if matches!(self.grammar.kind, GrammarKind::Json) {
62
            json::tokenize_line_into(line, spans);
63
            return;
64
        }
65
        let visible = trim_line_end(line);
66
        let visible_len = visible.len();
67
        let mut line = String::with_capacity(visible_len + 1);
68
        line.push_str(visible);
69
        line.push('\n');
70
        let mut anchors = AnchorState::new(state.first_line);
71
        let mut pos = self.check_while_conditions(state, &line, spans, &mut anchors);
72
73
        let mut zero_width_events = 0;
74
        while pos < line.len() {
75
            let next = self.advance(state, &line, pos, spans, &mut anchors);
76
            if next == pos {
77
                zero_width_events += 1;
78
                if zero_width_events >= MAX_ZERO_WIDTH_EVENTS {
79
                    pos = next_char_boundary(&line, pos.saturating_add(1));
80
                    zero_width_events = 0;
81
                }
82
            } else {
83
                pos = next;
84
                zero_width_events = 0;
85
            }
86
        }
87
        self.close_empty_rules_at_end(state, &line, spans, &mut anchors);
88
        clamp_spans(spans, visible_len);
89
        state.first_line = false;
90
    }
91
92
    /// Performs one tokenization step and returns the next byte position.
93
    fn advance(
94
        &mut self,
95
        state: &mut LineState,
96
        line: &str,
97
        pos: usize,
98
        spans: &mut Vec<ScopeSpan>,
99
        anchors: &mut AnchorState,
100
    ) -> usize {
101
        if let Some(open) = state.stack.last().cloned() {
102
            self.advance_inside_open_rule(state, line, pos, spans, open, anchors)
103
        } else {
104
            self.advance_at_root(state, line, pos, spans, anchors)
105
        }
106
    }
107
108
    /// Advances past one root-level pattern match, or to end of line if there is none.
109
    fn advance_at_root(
110
        &mut self,
111
        state: &mut LineState,
112
        line: &str,
113
        pos: usize,
114
        spans: &mut Vec<ScopeSpan>,
115
        anchors: &mut AnchorState,
116
    ) -> usize {
117
        let found =
118
            self.match_rule_or_injections(self.grammar.patterns, state, line, pos, *anchors);
119
        let Some(found) = found else {
120
            return line.len();
121
        };
122
        let next_pos = found.next_pos_after_open(line);
123
        let opened = found.open_rule;
124
        let anchor = found.end;
125
        spans.extend(found.spans);
126
127
        if let Some(opened) = opened {
128
            state.stack.push(opened);
129
            anchors.set_begin_position(anchor);
130
        }
131
        next_pos
132
    }
133
134
    /// Advances past one event inside the currently open begin/end rule.
135
    fn advance_inside_open_rule(
136
        &mut self,
137
        state: &mut LineState,
138
        line: &str,
139
        pos: usize,
140
        spans: &mut Vec<ScopeSpan>,
141
        open: OpenRule,
142
        anchors: &mut AnchorState,
143
    ) -> usize {
144
        let Some(pattern) = self.grammar.pattern_by_rule(open.rule_id) else {
145
            state.stack.pop();
146
            return pos;
147
        };
148
        let Some(end) = pattern.resume_end(open.dynamic_rule.as_deref(), &mut self.cache) else {
149
            return self.advance_inside_while_rule(state, line, pos, spans, pattern, anchors);
150
        };
151
        let mut search = PatternSearch::new(
152
            &self.grammar.pattern_sets,
153
            line,
154
            line.len(),
155
            &mut self.cache,
156
            *anchors,
157
        );
158
        let event = pattern.next_event_inside(&end, line, pos, &mut search);
159
        let next_pos = event.next_pos(line);
160
        // Parent rules wrap the whole span consumed by this step; the current
161
        // rule's own content scope is emitted below for each event.
162
        if let Some((_current, parents)) = state.stack.split_last() {
163
            for open in parents {
164
                if let Some(pattern) = self.grammar.pattern_by_rule(open.rule_id) {
165
                    pattern.push_content_visible(spans, pos, next_pos);
166
                }
167
            }
168
        }
169
170
        match event {
171
            InsideEvent::Close(close) => {
172
                pattern.push_content_visible(spans, pos, close.start);
173
                pattern.append_match_spans(&close, &pattern.captures.end, spans, &mut search);
174
                if let Some(closed) = state.stack.pop() {
175
                    anchors.restore_begin_position(closed.anchor_position);
176
                }
177
            }
178
            InsideEvent::Nested(nested) => {
179
                let anchor = nested.end;
180
                let opened = nested.open_rule;
181
182
                pattern.push_content_visible(spans, pos, next_pos);
183
                spans.extend(nested.spans);
184
185
                if let Some(opened) = opened {
186
                    state.stack.push(opened);
187
                    anchors.set_begin_position(anchor);
188
                }
189
            }
190
            InsideEvent::None => {
191
                pattern.push_content_visible(spans, pos, next_pos);
192
            }
193
        }
194
        next_pos
195
    }
196
197
    /// Checks active begin/while rules before scanning a continued line.
198
    fn check_while_conditions(
199
        &mut self,
200
        state: &mut LineState,
201
        line: &str,
202
        spans: &mut Vec<ScopeSpan>,
203
        anchors: &mut AnchorState,
204
    ) -> usize {
205
        let mut pos = 0;
206
        let mut index = 0;
207
        while index < state.stack.len() {
208
            let Some(pattern) = self.grammar.pattern_by_rule(state.stack[index].rule_id) else {
209
                state.stack.truncate(index);
210
                break;
211
            };
212
            let Some(matched) = pattern.while_match(
213
                state.stack[index].dynamic_rule.as_deref(),
214
                line,
215
                &mut self.cache,
216
                *anchors,
217
            ) else {
218
                if pattern
219
                    .resume_end(state.stack[index].dynamic_rule.as_deref(), &mut self.cache)
220
                    .is_none()
221
                {
222
                    state.stack.truncate(index);
223
                    break;
224
                }
225
                index += 1;
226
                continue;
227
            };
228
            let mut context = PatternSearch::new(
229
                &self.grammar.pattern_sets,
230
                line,
231
                line.len(),
232
                &mut self.cache,
233
                *anchors,
234
            );
235
            pattern.append_capture_spans(
236
                &matched,
237
                &pattern.captures.while_rule,
238
                spans,
239
                &mut context,
240
            );
241
            anchors.set_begin_position(matched.end);
242
            pos = pos.max(matched.end);
243
            index += 1;
244
        }
245
        spans.sort_by_key(|span| (span.start, span.end));
246
        pos
247
    }
248
249
    /// Advances past one nested event inside an open begin/while rule.
250
    fn advance_inside_while_rule(
251
        &mut self,
252
        state: &mut LineState,
253
        line: &str,
254
        pos: usize,
255
        spans: &mut Vec<ScopeSpan>,
256
        pattern: &Pattern,
257
        anchors: &mut AnchorState,
258
    ) -> usize {
259
        let nested = self.match_rule_or_injections(pattern.nested, state, line, pos, *anchors);
260
        let Some(nested) = nested else {
261
            pattern.push_content_visible(spans, pos, line.len());
262
            return line.len();
263
        };
264
        let next_pos = nested.next_pos_after_open(line);
265
        let opened = nested.open_rule;
266
        let anchor = nested.end;
267
268
        pattern.push_content_visible(spans, pos, next_pos);
269
        spans.extend(nested.spans);
270
271
        if let Some(opened) = opened {
272
            state.stack.push(opened);
273
            anchors.set_begin_position(anchor);
274
        }
275
        next_pos
276
    }
277
278
    /// Returns the next normal grammar or injected pattern match.
279
    fn match_rule_or_injections(
280
        &mut self,
281
        patterns: PatternSetId,
282
        state: &LineState,
283
        line: &str,
284
        pos: usize,
285
        anchors: AnchorState,
286
    ) -> Option<Match> {
287
        let mut found = {
288
            let mut search = PatternSearch::new(
289
                &self.grammar.pattern_sets,
290
                line,
291
                line.len(),
292
                &mut self.cache,
293
                anchors,
294
            );
295
            patterns.find_next(&mut search, pos)
296
        };
297
        if self.grammar.injections.is_empty() {
298
            return found;
299
        }
300
301
        let mut scopes = Vec::new();
302
        self.grammar.scope_names_for_state(state, &mut scopes);
303
        for injection in &self.grammar.injections {
304
            if !injection.selector.matches(&scopes) {
305
                continue;
306
            }
307
            let mut search = PatternSearch::new(
308
                &self.grammar.pattern_sets,
309
                line,
310
                line.len(),
311
                &mut self.cache,
312
                anchors,
313
            );
314
            let Some(candidate) = injection.patterns.find_next(&mut search, pos) else {
315
                continue;
316
            };
317
            found = match found {
318
                Some(current)
319
                    if current.start < candidate.start
320
                        || (current.start == candidate.start
321
                            && injection.selector.priority != InjectionPriority::Left) =>
322
                {
323
                    Some(current)
324
                }
325
                _ => Some(candidate),
326
            };
327
        }
328
        found
329
    }
330
331
    /// Closes zero-width end rules that match at the end of a line.
332
    fn close_empty_rules_at_end(
333
        &mut self,
334
        state: &mut LineState,
335
        line: &str,
336
        spans: &mut Vec<ScopeSpan>,
337
        anchors: &mut AnchorState,
338
    ) {
339
        while !state.is_empty() {
340
            let depth = state.depth();
341
            let pos = self.advance(state, line, line.len(), spans, anchors);
342
            if pos != line.len() || state.depth() >= depth {
343
                break;
344
            }
345
        }
346
    }
347
348
    /// Returns the number of cached dynamic end regexes (test helper).
349
    #[cfg(test)]
350
    pub(super) fn end_regex_cache_len(&self) -> usize {
351
        self.cache.len()
352
    }
353
}
354
355
/// Trims token spans back to the caller-visible line range.
356
fn clamp_spans(spans: &mut Vec<ScopeSpan>, visible_len: usize) {
357
    spans.retain_mut(|span| {
358
        span.end = span.end.min(visible_len);
359
        span.start < span.end
360
    });
361
}