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