crates/highlight/src/grammar/pattern.rs 51.3 KiB raw
1
//! Pattern compilation and matching for TextMate grammars.
2
//!
3
//! Raw TextMate patterns compile into a tree of [`Pattern`] values grouped into
4
//! [`PatternSet`]s. Each set caches a combined Oniguruma [`RegSet`] on first
5
//! search so that finding the next match in a line is one regex search
6
//! regardless of how many patterns share that nesting level. Begin/end rules
7
//! carry their end pattern on the same node; static end patterns are
8
//! precompiled, while dynamic ones are resolved against the begin match the
9
//! first time they are needed and cached for subsequent lines.
10
11
use super::end::{EndPattern, EndRegex, EndRegexCache};
12
use super::selector::ScopeSelector;
13
use super::*;
14
use crate::raw::truthy_flag;
15
use std::cell::OnceCell;
16
17
/// Capture-group index to capture metadata mapping.
18
pub(super) type Captures = BTreeMap<usize, Capture>;
19
20
/// A scope assigned by a pattern.
21
#[derive(Clone, Debug, Eq, PartialEq)]
22
pub(super) enum Scope {
23
    /// Pattern names no scope.
24
    None,
25
    /// Pattern names a visible scope that emits spans.
26
    Visible(Vec<ScopeId>),
27
    /// Pattern names a structural scope used only to hold parser state.
28
    Structural(Vec<ScopeId>),
29
}
30
31
/// Compiled metadata for one capture group.
32
#[derive(Debug)]
33
pub(super) struct Capture {
34
    /// Scope assigned directly to the captured group.
35
    scope: Scope,
36
    /// Scope assigned to content retokenized inside the captured group.
37
    content_scope: Scope,
38
    /// Pattern set used to retokenize the captured group.
39
    nested: Option<PatternSetId>,
40
}
41
42
/// Capture-scope mappings for a pattern's three regex slots.
43
#[derive(Debug, Default)]
44
pub(super) struct PatternCaptures {
45
    /// Captures applied to a single match rule.
46
    pub(super) matched: Captures,
47
    /// Captures applied to a begin-match rule.
48
    pub(super) begin: Captures,
49
    /// Captures applied to an end-match rule.
50
    pub(super) end: Captures,
51
    /// Captures applied to a while-match rule.
52
    pub(super) while_rule: Captures,
53
}
54
55
/// Match form used by a compiled pattern.
56
#[derive(Debug)]
57
enum PatternBody {
58
    /// Single regex match rule.
59
    Match {
60
        /// Regex source.
61
        source: String,
62
    },
63
    /// Stateful begin/end rule.
64
    BeginEnd {
65
        /// Begin regex source (also the entry inside the parent set's RegSet).
66
        begin_source: String,
67
        /// End regex (compiled now or deferred until begin captures are known).
68
        end: EndPattern,
69
        /// Whether nested patterns take priority over the end pattern at the same position.
70
        apply_end_pattern_last: bool,
71
    },
72
    /// Stateful begin/while rule.
73
    BeginWhile {
74
        /// Begin regex source (also the entry inside the parent set's RegSet).
75
        begin_source: String,
76
        /// While regex tested at the start of each continued line.
77
        while_rule: EndPattern,
78
    },
79
}
80
81
/// Stable arena id for a compiled pattern set.
82
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
83
pub(super) struct PatternSetId(
84
    /// Index into [`CompiledPatterns::sets`].
85
    usize,
86
);
87
88
/// Compiled patterns at one nesting level plus their combined search regex.
89
#[derive(Debug)]
90
pub(super) struct PatternSet {
91
    /// Patterns in declaration order.
92
    pub(super) patterns: Vec<Pattern>,
93
    /// Ordered local patterns and includes declared in this set.
94
    entries: Vec<PatternEntry>,
95
    /// Pattern locations in flattened search order.
96
    matches: Vec<RuleLocation>,
97
    /// Combined RegSet covering flattened pattern match or begin sources.
98
    regexes: OnceCell<Option<SearchRegexes>>,
99
}
100
101
/// Lazily compiled combined regex set plus its filtered match table.
102
#[derive(Debug)]
103
struct SearchRegexes {
104
    /// Pattern locations in the same order as [`Self::regexes`].
105
    matches: Vec<RuleLocation>,
106
    /// Combined Oniguruma regex set for all valid search sources.
107
    regexes: RegSet,
108
}
109
110
/// Ordered search entry inside one pattern set.
111
#[derive(Clone, Copy, Debug)]
112
enum PatternEntry {
113
    /// Local pattern index inside the set.
114
    Pattern(usize),
115
    /// Included pattern set searched at this point.
116
    Include(PatternSetId),
117
}
118
119
/// Compiled injection rule searched against matching scope stacks.
120
#[derive(Debug)]
121
pub(super) struct Injection {
122
    /// Selector that decides when this injection applies.
123
    pub(super) selector: ScopeSelector,
124
    /// Pattern set searched when the selector matches.
125
    pub(super) patterns: PatternSetId,
126
}
127
128
/// One compiled TextMate pattern with its scope, captures, and nested rules.
129
///
130
/// A [`Pattern`] is what the grammar tokenizer matches against the source text.
131
/// One match produces a [`Match`] (the higher-level result with emitted spans),
132
/// which wraps the underlying [`RegexMatch`] (raw capture positions).
133
#[derive(Debug)]
134
pub(super) struct Pattern {
135
    /// Stable rule id used to reopen this pattern from line state.
136
    id: usize,
137
    /// Scope assigned by this pattern.
138
    pub(super) scope: Scope,
139
    /// Scope assigned to content inside a begin rule.
140
    pub(super) content_scope: Scope,
141
    /// Per-slot capture-scope mappings.
142
    pub(super) captures: PatternCaptures,
143
    /// Match form (single match or begin/end pair).
144
    body: PatternBody,
145
    /// Pattern set that may match inside this one.
146
    pub(super) nested: PatternSetId,
147
}
148
149
/// Begin/end rule pushed onto the parser stack and held across line boundaries.
150
///
151
/// The matching [`Pattern`] is recovered through `Grammar::pattern_by_rule`, so
152
/// the open rule itself only stores what cannot be derived from the grammar:
153
/// the rule's id and any resolved regex source for dynamic end or while
154
/// patterns.
155
#[derive(Clone, Debug, Eq, PartialEq)]
156
pub(super) struct OpenRule {
157
    /// Compiled rule id.
158
    pub(super) rule_id: usize,
159
    /// Resolved regex source for dynamic end or while patterns.
160
    pub(super) dynamic_rule: Option<String>,
161
    /// Parent `\G` anchor restored when this rule closes.
162
    pub(super) anchor_position: Option<usize>,
163
}
164
165
/// Result of one pattern matching in a line: the byte range it covered, the
166
/// scope spans it emitted, and any begin/end rule it pushed onto the stack.
167
pub(super) struct Match {
168
    /// Start byte of the match in the line.
169
    pub(super) start: usize,
170
    /// End byte of the match (or of the same-line close, for begin/end rules).
171
    pub(super) end: usize,
172
    /// Scope spans emitted by the match and its captures.
173
    pub(super) spans: Vec<ScopeSpan>,
174
    /// New rule pushed onto the parser stack, when this match opened one.
175
    pub(super) open_rule: Option<OpenRule>,
176
}
177
178
/// Shared inputs for finding the next pattern and emitting capture spans.
179
pub(super) struct PatternSearch<'line, 'sets, 'cache> {
180
    /// Pattern sets in the compiled grammar.
181
    sets: &'sets [PatternSet],
182
    /// Line being searched.
183
    line: &'line str,
184
    /// Exclusive byte limit for the search.
185
    limit: usize,
186
    /// Cache for dynamically resolved end regexes.
187
    cache: &'cache mut EndRegexCache,
188
    /// Anchor availability for this search.
189
    anchors: AnchorState,
190
}
191
192
impl<'line, 'sets, 'cache> PatternSearch<'line, 'sets, 'cache> {
193
    /// Creates a pattern search context.
194
    pub(super) fn new(
195
        sets: &'sets [PatternSet],
196
        line: &'line str,
197
        limit: usize,
198
        cache: &'cache mut EndRegexCache,
199
        anchors: AnchorState,
200
    ) -> Self {
201
        Self {
202
            sets,
203
            line,
204
            limit,
205
            cache,
206
            anchors,
207
        }
208
    }
209
}
210
211
/// Raw regex hit: byte range plus the positions of any retained capture groups.
212
pub(super) struct RegexMatch {
213
    /// Start byte of the full regex match.
214
    pub(super) start: usize,
215
    /// End byte of the full regex match.
216
    pub(super) end: usize,
217
    /// Byte ranges for capture groups by capture index, when captures were retained.
218
    captures: Vec<Option<(usize, usize)>>,
219
}
220
221
/// Compiled grammar pattern arena and indexes.
222
pub(super) struct CompiledPatterns {
223
    /// Root pattern set id.
224
    pub(super) root: PatternSetId,
225
    /// Compiled pattern-set arena.
226
    pub(super) sets: Vec<PatternSet>,
227
    /// Interned scope names in id order.
228
    pub(super) scopes: Vec<String>,
229
    /// Direct lookup from rule id to its pattern's arena location.
230
    pub(super) rule_locations: Vec<Option<RuleLocation>>,
231
    /// Compiled runtime injections.
232
    pub(super) injections: Vec<Injection>,
233
}
234
235
/// Direct arena location for a compiled rule.
236
#[derive(Clone, Copy, Debug)]
237
pub(super) struct RuleLocation {
238
    /// Pattern set containing the rule.
239
    pub(super) set: PatternSetId,
240
    /// Index of the rule inside the containing pattern set.
241
    pub(super) index: usize,
242
}
243
244
/// Builder-time table that assigns stable ids to scope names.
245
#[derive(Default)]
246
pub(super) struct ScopeInterner {
247
    /// Interned scope names in id order.
248
    pub(super) scopes: Vec<String>,
249
    /// Lookup table from scope name to interned id.
250
    ids: BTreeMap<String, ScopeId>,
251
}
252
253
/// Parsed TextMate include target.
254
enum IncludeReference {
255
    /// `$base`.
256
    Base,
257
    /// `$self`.
258
    SelfReference,
259
    /// `#name`.
260
    Repository(String),
261
    /// `scope.name`.
262
    External(String),
263
    /// `scope.name#name`.
264
    ExternalRepository(String, String),
265
}
266
267
impl IncludeReference {
268
    /// Parses a raw include string.
269
    fn parse(include: &str) -> Self {
270
        if include == "$base" {
271
            return Self::Base;
272
        }
273
        if include == "$self" {
274
            return Self::SelfReference;
275
        }
276
        let Some((scope, name)) = include.split_once('#') else {
277
            return Self::External(include.to_owned());
278
        };
279
        if scope.is_empty() {
280
            Self::Repository(name.to_owned())
281
        } else {
282
            Self::ExternalRepository(scope.to_owned(), name.to_owned())
283
        }
284
    }
285
}
286
287
/// Compiler for one raw TextMate grammar.
288
pub(super) struct PatternCompiler<'raw> {
289
    /// Source grammar being compiled.
290
    raw: &'raw RawGrammar,
291
    /// Raw grammars visible to cross-grammar includes.
292
    grammars: BTreeMap<&'raw str, &'raw RawGrammar>,
293
    /// Root pattern set, available while compiling `$self` includes.
294
    root: PatternSetId,
295
    /// Root pattern sets compiled for raw grammars in this arena.
296
    roots: BTreeMap<&'raw str, PatternSetId>,
297
    /// Compiled pattern-set arena.
298
    sets: Vec<PatternSet>,
299
    /// Repository entries compiled so far.
300
    repository: BTreeMap<(&'raw str, String), PatternSetId>,
301
    /// Repository include nesting depth, used as a recursion guard.
302
    repository_depth: usize,
303
    /// Next stable rule id.
304
    next_rule: usize,
305
    /// Scope-name interner.
306
    interner: ScopeInterner,
307
}
308
309
impl Scope {
310
    /// Builds a scope from an optional raw TextMate name.
311
    fn from_raw(name: Option<&str>, interner: &mut ScopeInterner) -> Self {
312
        let Some(name) = name else { return Self::None };
313
        let path = name
314
            .split_whitespace()
315
            .map(|scope| interner.intern(scope))
316
            .collect::<Vec<_>>();
317
        // A blank or whitespace-only name interns no scopes; treat it as unscoped.
318
        if path.is_empty() {
319
            return Self::None;
320
        }
321
        if name.starts_with("meta.structure.") {
322
            Self::Structural(path)
323
        } else {
324
            Self::Visible(path)
325
        }
326
    }
327
328
    /// Pushes a span for this scope's region when it is visible and non-empty.
329
    pub(super) fn push_visible(&self, spans: &mut Vec<ScopeSpan>, start: usize, end: usize) {
330
        if let Self::Visible(path) = self
331
            && start < end
332
        {
333
            for scope in path {
334
                spans.push(ScopeSpan {
335
                    start,
336
                    end,
337
                    scope: *scope,
338
                });
339
            }
340
        }
341
    }
342
343
    /// Extends `scopes` with every scope name carried by this scope.
344
    pub(super) fn extend_names<'grammar>(
345
        &self,
346
        names: &'grammar [String],
347
        scopes: &mut Vec<&'grammar str>,
348
    ) {
349
        match self {
350
            Self::None => {}
351
            Self::Visible(path) | Self::Structural(path) => scopes.extend(
352
                path.iter()
353
                    .filter_map(|scope| names.get(scope.index()).map(String::as_str)),
354
            ),
355
        }
356
    }
357
358
    /// Pushes visible name and content scopes for an inner rule region.
359
    pub(super) fn push_content_visible(
360
        name: &Self,
361
        content: &Self,
362
        spans: &mut Vec<ScopeSpan>,
363
        start: usize,
364
        end: usize,
365
    ) {
366
        name.push_visible(spans, start, end);
367
        content.push_visible(spans, start, end);
368
    }
369
}
370
371
impl Pattern {
372
    /// Extends `scopes` with this pattern's name and content scope names.
373
    pub(super) fn extend_scope_names<'grammar>(
374
        &self,
375
        names: &'grammar [String],
376
        scopes: &mut Vec<&'grammar str>,
377
    ) {
378
        self.scope.extend_names(names, scopes);
379
        self.content_scope.extend_names(names, scopes);
380
    }
381
}
382
383
impl Capture {
384
    /// Pushes this capture's direct and retokenized spans.
385
    fn push_spans(
386
        &self,
387
        spans: &mut Vec<ScopeSpan>,
388
        start: usize,
389
        end: usize,
390
        context: &mut PatternSearch<'_, '_, '_>,
391
    ) {
392
        Scope::push_content_visible(&self.scope, &self.content_scope, spans, start, end);
393
        if let Some(nested) = self.nested {
394
            retokenize_capture(nested, spans, start, end, context);
395
        }
396
    }
397
}
398
399
/// One event found inside an open begin/end rule.
400
pub(super) enum InsideEvent {
401
    /// Nested pattern matched before the end pattern.
402
    Nested(Match),
403
    /// End pattern closed the open rule.
404
    Close(RegexMatch),
405
    /// Neither nested nor end matched on the rest of the searched region.
406
    None,
407
}
408
409
impl InsideEvent {
410
    /// Returns the byte position this event advances to.
411
    pub(super) fn next_pos(&self, line: &str) -> usize {
412
        match self {
413
            Self::Close(close) => close.end,
414
            Self::Nested(nested) => nested.next_pos_after_open(line),
415
            Self::None => line.len(),
416
        }
417
    }
418
}
419
420
/// Returns the pattern for a rule id by scanning the pattern sets.
421
fn pattern_by_rule(sets: &[PatternSet], rule_id: usize) -> Option<&Pattern> {
422
    sets.iter()
423
        .find_map(|set| set.patterns.iter().find(|pattern| pattern.id == rule_id))
424
}
425
426
/// Retokenizes one captured region against a nested pattern set.
427
///
428
/// This mirrors the main tokenizer loop, bounded to the region: begin/end
429
/// rules opened inside the region are tracked on a local stack so that their
430
/// nested patterns and end captures apply, and every emitted span is clamped
431
/// to the region. `\G` is allowed at each step's search position, since the
432
/// region has no begin match of its own to anchor against.
433
fn retokenize_capture(
434
    root: PatternSetId,
435
    spans: &mut Vec<ScopeSpan>,
436
    start: usize,
437
    end: usize,
438
    context: &mut PatternSearch<'_, '_, '_>,
439
) {
440
    let sets = context.sets;
441
    let line = &context.line[..end];
442
    let mut search = PatternSearch::new(sets, line, end, context.cache, context.anchors);
443
    let emit_open_content =
444
        |spans: &mut Vec<ScopeSpan>, stack: &[OpenRule], from: usize, to: usize| {
445
            for open in stack.iter().rev() {
446
                if let Some(pattern) = pattern_by_rule(sets, open.rule_id) {
447
                    pattern.push_content_visible(spans, from, to);
448
                }
449
            }
450
        };
451
    let mut stack = Vec::<OpenRule>::new();
452
    let mut pos = start;
453
454
    while pos < end {
455
        search.anchors.set_begin_position(pos);
456
        let event = if let Some(open) = stack.last().cloned() {
457
            let Some(pattern) = pattern_by_rule(sets, open.rule_id) else {
458
                stack.pop();
459
                continue;
460
            };
461
            let Some(end_regex) = pattern.resume_end(open.dynamic_rule.as_deref(), search.cache)
462
            else {
463
                stack.pop();
464
                continue;
465
            };
466
            pattern.next_event_inside(&end_regex, line, pos, &mut search)
467
        } else {
468
            match root.find_next(&mut search, pos) {
469
                Some(matched) => InsideEvent::Nested(matched),
470
                None => InsideEvent::None,
471
            }
472
        };
473
474
        let previous_depth = stack.len();
475
        let next_pos = match event {
476
            InsideEvent::Nested(matched) => {
477
                let next_pos = matched.next_pos_after_open(line).min(end);
478
                emit_open_content(spans, &stack, pos, next_pos);
479
                spans.extend(matched.spans.into_iter().filter_map(|mut span| {
480
                    span.end = span.end.min(end);
481
                    (span.start < span.end).then_some(span)
482
                }));
483
                if let Some(opened) = matched.open_rule {
484
                    stack.push(opened);
485
                }
486
                next_pos
487
            }
488
            InsideEvent::Close(close) => {
489
                emit_open_content(spans, &stack, pos, close.start);
490
                if let Some(pattern) = stack
491
                    .last()
492
                    .and_then(|open| pattern_by_rule(sets, open.rule_id))
493
                {
494
                    pattern.append_capture_spans(&close, &pattern.captures.end, spans, &mut search);
495
                }
496
                stack.pop();
497
                close.end.min(end)
498
            }
499
            InsideEvent::None => {
500
                emit_open_content(spans, &stack, pos, end);
501
                break;
502
            }
503
        };
504
        // A match either advances or opens a rule; otherwise skip one byte.
505
        if next_pos > pos || stack.len() != previous_depth {
506
            pos = next_pos;
507
        } else {
508
            pos = (pos + 1).min(end);
509
        }
510
    }
511
}
512
513
impl ScopeInterner {
514
    /// Returns the id for a scope, inserting it when needed.
515
    fn intern(&mut self, scope: &str) -> ScopeId {
516
        if let Some(id) = self.ids.get(scope) {
517
            return *id;
518
        }
519
        let id = ScopeId::new(self.scopes.len());
520
        self.scopes.push(scope.to_owned());
521
        self.ids.insert(scope.to_owned(), id);
522
        id
523
    }
524
}
525
526
impl PatternSetId {
527
    /// Creates a pattern-set id from an arena index.
528
    pub(super) fn new(index: usize) -> Self {
529
        Self(index)
530
    }
531
532
    /// Returns this id's pattern-set arena index.
533
    pub(super) fn index(self) -> usize {
534
        self.0
535
    }
536
537
    /// Finds the next pattern match in this set or its included sets.
538
    pub(super) fn find_next(
539
        self,
540
        search: &mut PatternSearch<'_, '_, '_>,
541
        pos: usize,
542
    ) -> Option<Match> {
543
        search
544
            .sets
545
            .get(self.index())
546
            .and_then(|set| set.find_next(search, pos))
547
    }
548
}
549
550
impl PatternSet {
551
    /// Creates an empty pattern set.
552
    pub(super) fn empty() -> Self {
553
        Self {
554
            patterns: Vec::new(),
555
            entries: Vec::new(),
556
            matches: Vec::new(),
557
            regexes: OnceCell::new(),
558
        }
559
    }
560
561
    /// Builds a pattern set from local patterns and declaration-order search entries.
562
    fn new(patterns: Vec<Pattern>, entries: Vec<PatternEntry>) -> Self {
563
        Self {
564
            patterns,
565
            entries,
566
            matches: Vec::new(),
567
            regexes: OnceCell::new(),
568
        }
569
    }
570
571
    /// Finds the next flattened pattern match at or after `pos`.
572
    fn find_next(&self, search: &mut PatternSearch<'_, '_, '_>, pos: usize) -> Option<Match> {
573
        if pos > search.limit
574
            || search.limit > search.line.len()
575
            || !search.line.is_char_boundary(pos)
576
        {
577
            return None;
578
        }
579
        let search_regexes = self.regexes(search.sets)?;
580
        let (entry, captures) = search_regexes.regexes.captures_with_options(
581
            search.line,
582
            pos,
583
            search.limit,
584
            RegSetLead::Position,
585
            search.anchors.search_options(pos),
586
        )?;
587
        let location = search_regexes.matches.get(entry)?;
588
        let pattern = search
589
            .sets
590
            .get(location.set.index())?
591
            .patterns
592
            .get(location.index)?;
593
        let regex_match = RegexMatch::from_captures(captures, pattern.needs_match_captures())?;
594
595
        pattern.match_result(regex_match, search)
596
    }
597
598
    /// Returns the compiled search regex set, building it on first use.
599
    fn regexes(&self, sets: &[PatternSet]) -> Option<&SearchRegexes> {
600
        self.regexes
601
            .get_or_init(|| SearchRegexes::new(&self.matches, sets))
602
            .as_ref()
603
    }
604
}
605
606
impl SearchRegexes {
607
    /// Compiles a combined search set, filtering invalid sources only on failure.
608
    fn new(matches: &[RuleLocation], sets: &[PatternSet]) -> Option<Self> {
609
        if matches.is_empty() {
610
            return None;
611
        }
612
        let mut compiled_matches = Vec::new();
613
        let mut sources = Vec::new();
614
        for location in matches {
615
            let Some(source) = search_source(sets, *location) else {
616
                continue;
617
            };
618
            compiled_matches.push(*location);
619
            sources.push(source);
620
        }
621
        if sources.is_empty() {
622
            return None;
623
        }
624
        if let Ok(regexes) = RegSet::with_options(&sources, TEXTMATE_REGEX_OPTIONS) {
625
            return Some(Self {
626
                matches: compiled_matches,
627
                regexes,
628
            });
629
        }
630
631
        let mut valid_matches = Vec::new();
632
        let mut sources = Vec::new();
633
        for location in matches {
634
            let Some(source) = search_source(sets, *location) else {
635
                continue;
636
            };
637
            if regex(source).is_ok() {
638
                valid_matches.push(*location);
639
                sources.push(source);
640
            }
641
        }
642
        if sources.is_empty() {
643
            return None;
644
        }
645
        RegSet::with_options(&sources, TEXTMATE_REGEX_OPTIONS)
646
            .ok()
647
            .map(|regexes| Self {
648
                matches: valid_matches,
649
                regexes,
650
            })
651
    }
652
}
653
654
/// Returns the search regex source for a flattened pattern location.
655
fn search_source(sets: &[PatternSet], location: RuleLocation) -> Option<&str> {
656
    sets.get(location.set.index())?
657
        .patterns
658
        .get(location.index)
659
        .map(Pattern::search_source)
660
}
661
662
impl<'raw> PatternCompiler<'raw> {
663
    /// Creates a compiler for a raw grammar.
664
    pub(super) fn new(raw: &'raw RawGrammar, dependencies: &'raw [RawGrammar]) -> Self {
665
        let mut grammars = BTreeMap::new();
666
        for dependency in dependencies {
667
            grammars.insert(dependency.scope_name.as_str(), dependency);
668
        }
669
        grammars.insert(raw.scope_name.as_str(), raw);
670
        PatternCompiler {
671
            raw,
672
            grammars,
673
            root: PatternSetId::new(0),
674
            roots: BTreeMap::new(),
675
            sets: Vec::new(),
676
            repository: BTreeMap::new(),
677
            repository_depth: 0,
678
            next_rule: 0,
679
            interner: ScopeInterner::default(),
680
        }
681
    }
682
683
    /// Compiles the grammar's root pattern set and any referenced repository sets.
684
    pub(super) fn compile(mut self) -> Result<CompiledPatterns, Error> {
685
        let root = self.reserve_set();
686
        self.root = root;
687
        self.roots.insert(self.raw.scope_name.as_str(), root);
688
        let root_set = self.compile_patterns(
689
            self.raw,
690
            &self.raw.patterns,
691
            &mut vec![&self.raw.repository],
692
        )?;
693
        self.assign_set(root, root_set);
694
        let injections = self.compile_injections()?;
695
        self.compile_searches();
696
        let rule_locations = self.rule_locations();
697
698
        Ok(CompiledPatterns {
699
            root,
700
            sets: self.sets,
701
            scopes: self.interner.scopes,
702
            rule_locations,
703
            injections,
704
        })
705
    }
706
707
    /// Reserves an empty pattern-set slot and returns its id.
708
    fn reserve_set(&mut self) -> PatternSetId {
709
        let id = PatternSetId::new(self.sets.len());
710
        self.sets.push(PatternSet::empty());
711
        id
712
    }
713
714
    /// Assigns a compiled pattern set to a reserved slot.
715
    fn assign_set(&mut self, id: PatternSetId, set: PatternSet) {
716
        self.sets[id.index()] = set;
717
    }
718
719
    /// Compiles raw TextMate patterns into one pattern set.
720
    fn compile_patterns(
721
        &mut self,
722
        current: &'raw RawGrammar,
723
        patterns: &'raw [RawPattern],
724
        repositories: &mut Vec<&'raw BTreeMap<String, RawPattern>>,
725
    ) -> Result<PatternSet, Error> {
726
        let mut compiled = Vec::new();
727
        let mut entries = Vec::new();
728
        for pattern in patterns {
729
            if let Some(include) = &pattern.include {
730
                if let Some(include) = self.compile_include(current, include, repositories)? {
731
                    entries.push(PatternEntry::Include(include));
732
                }
733
                continue;
734
            }
735
            self.compile_pattern(current, pattern, repositories, &mut compiled, &mut entries)?;
736
        }
737
        Ok(PatternSet::new(compiled, entries))
738
    }
739
740
    /// Compiles one raw pattern into the current pattern-set builder.
741
    fn compile_pattern(
742
        &mut self,
743
        current: &'raw RawGrammar,
744
        pattern: &'raw RawPattern,
745
        repositories: &mut Vec<&'raw BTreeMap<String, RawPattern>>,
746
        compiled: &mut Vec<Pattern>,
747
        entries: &mut Vec<PatternEntry>,
748
    ) -> Result<(), Error> {
749
        let scope = Scope::from_raw(pattern.name.as_deref(), &mut self.interner);
750
        let body = match (
751
            &pattern.match_rule,
752
            &pattern.begin,
753
            &pattern.end,
754
            &pattern.while_rule,
755
        ) {
756
            (Some(source), _, _, _) => PatternBody::Match {
757
                source: source.clone(),
758
            },
759
            (None, Some(begin), Some(end), _) => {
760
                let Some(end) = EndPattern::compile(end) else {
761
                    return Ok(());
762
                };
763
                PatternBody::BeginEnd {
764
                    begin_source: begin.clone(),
765
                    end,
766
                    apply_end_pattern_last: truthy_flag(pattern.apply_end_pattern_last.as_ref()),
767
                }
768
            }
769
            (None, Some(begin), None, Some(while_rule)) => {
770
                let Some(while_rule) = EndPattern::compile(while_rule) else {
771
                    return Ok(());
772
                };
773
                PatternBody::BeginWhile {
774
                    begin_source: begin.clone(),
775
                    while_rule,
776
                }
777
            }
778
            _ => {
779
                self.inline_patterns(current, pattern, repositories, compiled, entries)?;
780
                return Ok(());
781
            }
782
        };
783
        // Nested children are compiled — and assigned their rule ids — before
784
        // this pattern, so every parent has a higher rule id than its children.
785
        let nested = self.compile_nested_set(current, &pattern.patterns, repositories)?;
786
        let id = self.next_rule;
787
        self.next_rule += 1;
788
789
        // The slot-specific capture maps fall back to the shared `captures` map.
790
        let shared = pattern.captures.as_ref();
791
        let matched = self.captures(current, shared, repositories)?;
792
        let begin = self.captures(
793
            current,
794
            pattern.begin_captures.as_ref().or(shared),
795
            repositories,
796
        )?;
797
        let end = self.captures(
798
            current,
799
            pattern.end_captures.as_ref().or(shared),
800
            repositories,
801
        )?;
802
        let while_rule = self.captures(
803
            current,
804
            pattern.while_captures.as_ref().or(shared),
805
            repositories,
806
        )?;
807
808
        let index = compiled.len();
809
        compiled.push(Pattern {
810
            id,
811
            scope,
812
            content_scope: Scope::from_raw(pattern.content_name.as_deref(), &mut self.interner),
813
            captures: PatternCaptures {
814
                matched,
815
                begin,
816
                end,
817
                while_rule,
818
            },
819
            body,
820
            nested,
821
        });
822
        entries.push(PatternEntry::Pattern(index));
823
        Ok(())
824
    }
825
826
    /// Compiles grouping pattern children directly into the parent builder.
827
    fn inline_patterns(
828
        &mut self,
829
        current: &'raw RawGrammar,
830
        pattern: &'raw RawPattern,
831
        repositories: &mut Vec<&'raw BTreeMap<String, RawPattern>>,
832
        compiled: &mut Vec<Pattern>,
833
        entries: &mut Vec<PatternEntry>,
834
    ) -> Result<(), Error> {
835
        let offset = compiled.len();
836
        let inline = self.compile_patterns(current, &pattern.patterns, repositories)?;
837
        compiled.extend(inline.patterns);
838
        entries.extend(inline.entries.into_iter().map(|entry| match entry {
839
            PatternEntry::Pattern(index) => PatternEntry::Pattern(index + offset),
840
            PatternEntry::Include(id) => PatternEntry::Include(id),
841
        }));
842
843
        Ok(())
844
    }
845
846
    /// Compiles a nested pattern set into the arena and returns its id.
847
    fn compile_nested_set(
848
        &mut self,
849
        current: &'raw RawGrammar,
850
        patterns: &'raw [RawPattern],
851
        repositories: &mut Vec<&'raw BTreeMap<String, RawPattern>>,
852
    ) -> Result<PatternSetId, Error> {
853
        let id = self.reserve_set();
854
        let set = self.compile_patterns(current, patterns, repositories)?;
855
        self.assign_set(id, set);
856
857
        Ok(id)
858
    }
859
860
    /// Compiles an include target into a pattern-set reference.
861
    fn compile_include(
862
        &mut self,
863
        current: &'raw RawGrammar,
864
        include: &str,
865
        repositories: &mut Vec<&'raw BTreeMap<String, RawPattern>>,
866
    ) -> Result<Option<PatternSetId>, Error> {
867
        match IncludeReference::parse(include) {
868
            IncludeReference::Base => Ok(Some(self.root)),
869
            IncludeReference::SelfReference => self.compile_root(current),
870
            IncludeReference::Repository(name) => {
871
                self.compile_repository_entry(current, &name, repositories)
872
            }
873
            IncludeReference::External(scope) => {
874
                let Some(grammar) = self.grammars.get(scope.as_str()).copied() else {
875
                    return Ok(None);
876
                };
877
                self.compile_external_root(grammar)
878
            }
879
            IncludeReference::ExternalRepository(scope, name) => {
880
                let Some(grammar) = self.grammars.get(scope.as_str()).copied() else {
881
                    return Ok(None);
882
                };
883
                self.compile_external_repository_entry(grammar, &name)
884
            }
885
        }
886
    }
887
888
    /// Compiles one raw grammar root once and returns its pattern-set id.
889
    fn compile_root(&mut self, raw: &'raw RawGrammar) -> Result<Option<PatternSetId>, Error> {
890
        if let Some(id) = self.roots.get(raw.scope_name.as_str()) {
891
            return Ok(Some(*id));
892
        }
893
        let id = self.reserve_set();
894
        self.roots.insert(raw.scope_name.as_str(), id);
895
        let set = self.compile_patterns(raw, &raw.patterns, &mut vec![&raw.repository])?;
896
        self.assign_set(id, set);
897
        Ok(Some(id))
898
    }
899
900
    /// Compiles one external raw grammar root with an independent include budget.
901
    fn compile_external_root(
902
        &mut self,
903
        raw: &'raw RawGrammar,
904
    ) -> Result<Option<PatternSetId>, Error> {
905
        let depth = self.repository_depth;
906
        self.repository_depth = 0;
907
        let root = self.compile_root(raw);
908
        self.repository_depth = depth;
909
        root
910
    }
911
912
    /// Compiles one external repository entry with an independent include budget.
913
    fn compile_external_repository_entry(
914
        &mut self,
915
        raw: &'raw RawGrammar,
916
        name: &str,
917
    ) -> Result<Option<PatternSetId>, Error> {
918
        let depth = self.repository_depth;
919
        self.repository_depth = 0;
920
        let entry = self.compile_repository_entry(raw, name, &mut vec![&raw.repository]);
921
        self.repository_depth = depth;
922
        entry
923
    }
924
925
    /// Compiles one repository entry once and returns its pattern-set id.
926
    fn compile_repository_entry(
927
        &mut self,
928
        current: &'raw RawGrammar,
929
        name: &str,
930
        repositories: &mut Vec<&'raw BTreeMap<String, RawPattern>>,
931
    ) -> Result<Option<PatternSetId>, Error> {
932
        let Some((pattern, top_level)) = repositories.iter().rev().find_map(|repository| {
933
            repository.get(name).map(|pattern| {
934
                let top_level = std::ptr::eq(*repository, &current.repository);
935
                (pattern, top_level)
936
            })
937
        }) else {
938
            return Ok(None);
939
        };
940
        let key = (current.scope_name.as_str(), name.to_owned());
941
        if top_level && let Some(id) = self.repository.get(&key) {
942
            return Ok(Some(*id));
943
        }
944
        if self.repository_depth > MAX_INCLUDE_DEPTH {
945
            return Ok(None);
946
        }
947
        let id = self.reserve_set();
948
949
        if top_level {
950
            self.repository.insert(key, id);
951
        }
952
        self.repository_depth += 1;
953
954
        let set = self.compile_patterns(current, std::slice::from_ref(pattern), repositories)?;
955
956
        self.repository_depth -= 1;
957
        self.assign_set(id, set);
958
959
        Ok(Some(id))
960
    }
961
962
    /// Compiles injections from the root grammar.
963
    fn compile_injections(&mut self) -> Result<Vec<Injection>, Error> {
964
        let mut injections = Vec::new();
965
        for (selector, pattern) in &self.raw.injections {
966
            let patterns = self.compile_nested_set(
967
                self.raw,
968
                std::slice::from_ref(pattern),
969
                &mut vec![&self.raw.repository],
970
            )?;
971
            for selector in ScopeSelector::parse_all(selector) {
972
                injections.push(Injection { selector, patterns });
973
            }
974
        }
975
        injections.sort_by_key(|injection| injection.selector.priority);
976
        Ok(injections)
977
    }
978
979
    /// Compiles flattened regex search sets after all pattern sets are assigned.
980
    fn compile_searches(&mut self) {
981
        let mut searches = Vec::with_capacity(self.sets.len());
982
        for index in 0..self.sets.len() {
983
            let mut active = Vec::new();
984
            let mut collected = Vec::new();
985
            self.collect_search_entries(PatternSetId::new(index), &mut active, &mut collected);
986
            searches.push(collected);
987
        }
988
989
        for (set, matches) in self.sets.iter_mut().zip(searches) {
990
            set.matches = matches;
991
        }
992
    }
993
994
    /// Collects the declaration-order patterns searched for `set`.
995
    fn collect_search_entries(
996
        &self,
997
        set: PatternSetId,
998
        active: &mut Vec<PatternSetId>,
999
        matches: &mut Vec<RuleLocation>,
1000
    ) {
1001
        if active.contains(&set) || active.len() > MAX_INCLUDE_DEPTH {
1002
            return;
1003
        }
1004
        let Some(pattern_set) = self.sets.get(set.index()) else {
1005
            return;
1006
        };
1007
1008
        active.push(set);
1009
        for entry in &pattern_set.entries {
1010
            match entry {
1011
                PatternEntry::Pattern(index) => matches.push(RuleLocation { set, index: *index }),
1012
                PatternEntry::Include(include) => {
1013
                    self.collect_search_entries(*include, active, matches);
1014
                }
1015
            }
1016
        }
1017
        active.pop();
1018
    }
1019
1020
    /// Compiles capture metadata.
1021
    fn captures(
1022
        &mut self,
1023
        current: &'raw RawGrammar,
1024
        raw: Option<&'raw BTreeMap<String, RawCapture>>,
1025
        repositories: &mut Vec<&'raw BTreeMap<String, RawPattern>>,
1026
    ) -> Result<Captures, Error> {
1027
        let mut captures = Captures::new();
1028
        let Some(raw) = raw else {
1029
            return Ok(captures);
1030
        };
1031
        for (index, capture) in raw {
1032
            let Ok(scope_index) = index.parse() else {
1033
                continue;
1034
            };
1035
            let nested = if capture.patterns.is_empty() {
1036
                None
1037
            } else {
1038
                Some(self.compile_nested_set(current, &capture.patterns, repositories)?)
1039
            };
1040
            captures.insert(
1041
                scope_index,
1042
                Capture {
1043
                    scope: Scope::from_raw(capture.name.as_deref(), &mut self.interner),
1044
                    content_scope: Scope::from_raw(
1045
                        capture.content_name.as_deref(),
1046
                        &mut self.interner,
1047
                    ),
1048
                    nested,
1049
                },
1050
            );
1051
        }
1052
        Ok(captures)
1053
    }
1054
1055
    /// Builds direct rule-id lookups after compilation.
1056
    fn rule_locations(&self) -> Vec<Option<RuleLocation>> {
1057
        let mut locations = vec![None; self.next_rule];
1058
        for (set_index, set) in self.sets.iter().enumerate() {
1059
            let set_id = PatternSetId::new(set_index);
1060
            for (index, pattern) in set.patterns.iter().enumerate() {
1061
                if let Some(slot) = locations.get_mut(pattern.id) {
1062
                    *slot = Some(RuleLocation { set: set_id, index });
1063
                }
1064
            }
1065
        }
1066
        locations
1067
    }
1068
}
1069
1070
impl Pattern {
1071
    /// Pushes this pattern's name and content scopes over an inner-region range.
1072
    pub(super) fn push_content_visible(
1073
        &self,
1074
        spans: &mut Vec<ScopeSpan>,
1075
        start: usize,
1076
        end: usize,
1077
    ) {
1078
        Scope::push_content_visible(&self.scope, &self.content_scope, spans, start, end);
1079
    }
1080
1081
    /// Returns the active end regex when reopening this pattern from line state.
1082
    pub(super) fn resume_end<'pat>(
1083
        &'pat self,
1084
        dynamic_rule: Option<&str>,
1085
        cache: &mut EndRegexCache,
1086
    ) -> Option<EndRegex<'pat>> {
1087
        let PatternBody::BeginEnd { end, .. } = &self.body else {
1088
            return None;
1089
        };
1090
        end.resume(dynamic_rule, cache)
1091
    }
1092
1093
    /// Finds this rule's while match at the start of a continued line.
1094
    pub(super) fn while_match(
1095
        &self,
1096
        dynamic_while: Option<&str>,
1097
        line: &str,
1098
        cache: &mut EndRegexCache,
1099
        anchors: AnchorState,
1100
    ) -> Option<RegexMatch> {
1101
        let PatternBody::BeginWhile { while_rule, .. } = &self.body else {
1102
            return None;
1103
        };
1104
        let while_regex = while_rule.resume(dynamic_while, cache)?;
1105
        let matched = RegexMatch::find(
1106
            while_regex.regex(),
1107
            line,
1108
            0,
1109
            !self.captures.while_rule.is_empty(),
1110
            anchors,
1111
        )?;
1112
        // The while pattern must anchor at column 0; a search from offset 0 can
1113
        // still return a later match, which does not count as a continuation.
1114
        (matched.start == 0).then_some(matched)
1115
    }
1116
1117
    /// Returns true when nested patterns should win same-position end matches.
1118
    pub(super) fn apply_end_pattern_last(&self) -> bool {
1119
        matches!(
1120
            &self.body,
1121
            PatternBody::BeginEnd {
1122
                apply_end_pattern_last: true,
1123
                ..
1124
            }
1125
        )
1126
    }
1127
1128
    /// Finds this rule's end match at or after `pos`.
1129
    pub(super) fn find_end_match(
1130
        &self,
1131
        end: &EndRegex<'_>,
1132
        line: &str,
1133
        mut pos: usize,
1134
        anchors: AnchorState,
1135
    ) -> Option<RegexMatch> {
1136
        loop {
1137
            let matched = RegexMatch::find_end(
1138
                end.regex(),
1139
                line,
1140
                pos,
1141
                !self.captures.end.is_empty(),
1142
                anchors,
1143
            )?;
1144
            if matches!(end.source(), "\"" | "'") && is_escaped_at(line, matched.start) {
1145
                pos = matched.next_pos(line);
1146
                continue;
1147
            }
1148
            return Some(matched);
1149
        }
1150
    }
1151
1152
    /// Finds the next event inside this open rule: a nested pattern match, the
1153
    /// end pattern closing the rule, or neither within the search limit.
1154
    ///
1155
    /// The end pattern is searched on `line`, which may extend past the search
1156
    /// limit; an end match counts only when it starts inside the limit.
1157
    pub(super) fn next_event_inside(
1158
        &self,
1159
        end: &EndRegex<'_>,
1160
        line: &str,
1161
        pos: usize,
1162
        search: &mut PatternSearch<'_, '_, '_>,
1163
    ) -> InsideEvent {
1164
        let nested = self.nested.find_next(search, pos);
1165
        let close = self
1166
            .find_end_match(end, line, pos, search.anchors)
1167
            .filter(|close| close.start <= search.limit);
1168
1169
        match (nested, close) {
1170
            (Some(nested), Some(close))
1171
                if nested.start < close.start
1172
                    || (self.apply_end_pattern_last() && nested.start == close.start) =>
1173
            {
1174
                InsideEvent::Nested(nested)
1175
            }
1176
            (_, Some(close)) => InsideEvent::Close(close),
1177
            (Some(nested), None) => InsideEvent::Nested(nested),
1178
            (None, None) => InsideEvent::None,
1179
        }
1180
    }
1181
1182
    /// Adds capture-group spans plus the pattern's own scope span for one regex match.
1183
    pub(super) fn append_match_spans(
1184
        &self,
1185
        matched: &RegexMatch,
1186
        captures: &Captures,
1187
        spans: &mut Vec<ScopeSpan>,
1188
        context: &mut PatternSearch<'_, '_, '_>,
1189
    ) {
1190
        self.scope.push_visible(spans, matched.start, matched.end);
1191
        self.append_capture_spans(matched, captures, spans, context);
1192
        spans.sort_by_key(|span| (span.start, span.end));
1193
    }
1194
1195
    /// Adds capture-group spans for one regex match.
1196
    pub(super) fn append_capture_spans(
1197
        &self,
1198
        matched: &RegexMatch,
1199
        captures: &Captures,
1200
        spans: &mut Vec<ScopeSpan>,
1201
        context: &mut PatternSearch<'_, '_, '_>,
1202
    ) {
1203
        for (index, capture) in captures {
1204
            if let Some(Some((start, end))) = matched.captures.get(*index)
1205
                && *start < *end
1206
            {
1207
                capture.push_spans(spans, *start, *end, context);
1208
            }
1209
        }
1210
    }
1211
1212
    /// Whether match-time regex captures must be retained.
1213
    fn needs_match_captures(&self) -> bool {
1214
        match &self.body {
1215
            PatternBody::Match { .. } => !self.captures.matched.is_empty(),
1216
            PatternBody::BeginEnd { end, .. } => {
1217
                !self.captures.begin.is_empty() || end.is_dynamic()
1218
            }
1219
            PatternBody::BeginWhile { while_rule, .. } => {
1220
                !self.captures.begin.is_empty()
1221
                    || !self.captures.while_rule.is_empty()
1222
                    || while_rule.is_dynamic()
1223
            }
1224
        }
1225
    }
1226
1227
    /// The regex source used in the parent set's combined `RegSet`.
1228
    fn search_source(&self) -> &str {
1229
        match &self.body {
1230
            PatternBody::Match { source } => source,
1231
            PatternBody::BeginEnd { begin_source, .. } => begin_source,
1232
            PatternBody::BeginWhile { begin_source, .. } => begin_source,
1233
        }
1234
    }
1235
1236
    /// Builds a [`Match`] for one regex hit, dispatching by body kind.
1237
    fn match_result(
1238
        &self,
1239
        regex_match: RegexMatch,
1240
        search: &mut PatternSearch<'_, '_, '_>,
1241
    ) -> Option<Match> {
1242
        match &self.body {
1243
            PatternBody::Match { .. } => Some(self.simple_match(regex_match, search)),
1244
            PatternBody::BeginEnd { end, .. } => self.begin_match(end, regex_match, search),
1245
            PatternBody::BeginWhile { .. } => Some(self.begin_while_match(regex_match, search)),
1246
        }
1247
    }
1248
1249
    /// Builds a match for a single-line match rule.
1250
    fn simple_match(
1251
        &self,
1252
        regex_match: RegexMatch,
1253
        search: &mut PatternSearch<'_, '_, '_>,
1254
    ) -> Match {
1255
        let mut spans = Vec::new();
1256
        self.append_match_spans(&regex_match, &self.captures.matched, &mut spans, search);
1257
        Match {
1258
            start: regex_match.start,
1259
            end: regex_match.end,
1260
            spans,
1261
            open_rule: None,
1262
        }
1263
    }
1264
1265
    /// Builds a match for a begin/end rule, eagerly closing on the same line if possible.
1266
    fn begin_match(
1267
        &self,
1268
        end_pattern: &EndPattern,
1269
        begin: RegexMatch,
1270
        search: &mut PatternSearch<'_, '_, '_>,
1271
    ) -> Option<Match> {
1272
        let end_regex = end_pattern.resolve_for_begin(&begin, search.line, search.cache)?;
1273
        let dynamic_rule = end_regex.dynamic_source();
1274
        let mut spans = Vec::new();
1275
        self.append_match_spans(&begin, &self.captures.begin, &mut spans, search);
1276
1277
        Some(Match {
1278
            start: begin.start,
1279
            end: begin.end,
1280
            spans,
1281
            open_rule: Some(OpenRule {
1282
                rule_id: self.id,
1283
                dynamic_rule,
1284
                anchor_position: search.anchors.begin_position(),
1285
            }),
1286
        })
1287
    }
1288
1289
    /// Builds a match for a begin/while rule.
1290
    fn begin_while_match(
1291
        &self,
1292
        begin: RegexMatch,
1293
        search: &mut PatternSearch<'_, '_, '_>,
1294
    ) -> Match {
1295
        let PatternBody::BeginWhile { while_rule, .. } = &self.body else {
1296
            return self.simple_match(begin, search);
1297
        };
1298
        let while_regex = while_rule.resolve_for_begin(&begin, search.line, search.cache);
1299
        let dynamic_rule = while_regex.and_then(|while_regex| while_regex.dynamic_source());
1300
        let mut spans = Vec::new();
1301
1302
        self.append_match_spans(&begin, &self.captures.begin, &mut spans, search);
1303
        self.scope.push_visible(&mut spans, begin.start, begin.end);
1304
1305
        Match {
1306
            start: begin.start,
1307
            end: begin.end,
1308
            spans,
1309
            open_rule: Some(OpenRule {
1310
                rule_id: self.id,
1311
                dynamic_rule,
1312
                anchor_position: search.anchors.begin_position(),
1313
            }),
1314
        }
1315
    }
1316
}
1317
1318
/// Whether the byte at `pos` is preceded by an odd number of backslashes.
1319
fn is_escaped_at(line: &str, pos: usize) -> bool {
1320
    if pos > line.len() || !line.is_char_boundary(pos) {
1321
        return false;
1322
    }
1323
    line[..pos]
1324
        .bytes()
1325
        .rev()
1326
        .take_while(|byte| *byte == b'\\')
1327
        .count()
1328
        % 2
1329
        == 1
1330
}
1331
1332
impl Match {
1333
    /// Returns the next byte position after this match, ensuring forward progress.
1334
    pub(super) fn next_pos(&self, line: &str) -> usize {
1335
        next_pos_after(line, self.start, self.end)
1336
    }
1337
1338
    /// Returns the next byte position after opening this rule.
1339
    pub(super) fn next_pos_after_open(&self, line: &str) -> usize {
1340
        if self.open_rule.is_some() && self.start == self.end {
1341
            self.start
1342
        } else {
1343
            self.next_pos(line)
1344
        }
1345
    }
1346
}
1347
1348
impl RegexMatch {
1349
    /// Finds one regex match starting at `pos`.
1350
    pub(super) fn find(
1351
        regex: &Regex,
1352
        line: &str,
1353
        pos: usize,
1354
        keep_captures: bool,
1355
        anchors: AnchorState,
1356
    ) -> Option<Self> {
1357
        if pos > line.len() || !line.is_char_boundary(pos) {
1358
            return None;
1359
        }
1360
        let mut region = Region::new();
1361
        let _ = regex.search_with_options(
1362
            line,
1363
            pos,
1364
            line.len(),
1365
            anchors.search_options(pos),
1366
            Some(&mut region),
1367
        )?;
1368
        let (start, end) = region.pos(0)?;
1369
        if start > end || end > line.len() {
1370
            return None;
1371
        }
1372
        let captures = if keep_captures {
1373
            (0..region.len())
1374
                .map(|index| {
1375
                    region.pos(index).and_then(|(start, end)| {
1376
                        (start <= end && end <= line.len()).then_some((start, end))
1377
                    })
1378
                })
1379
                .collect()
1380
        } else {
1381
            Vec::new()
1382
        };
1383
        Some(Self {
1384
            start,
1385
            end,
1386
            captures,
1387
        })
1388
    }
1389
1390
    /// Finds one end-regex match at or after `pos`.
1391
    pub(super) fn find_end(
1392
        regex: &Regex,
1393
        line: &str,
1394
        pos: usize,
1395
        keep_captures: bool,
1396
        anchors: AnchorState,
1397
    ) -> Option<Self> {
1398
        if let Some(matched) = Self::find(regex, line, pos, keep_captures, anchors) {
1399
            return Some(matched);
1400
        }
1401
        let search = pos.checked_sub(1)?;
1402
        let matched = Self::find(regex, line, search, keep_captures, anchors)?;
1403
1404
        (matched.start >= pos).then_some(matched)
1405
    }
1406
1407
    /// Builds a match record from Oniguruma captures.
1408
    fn from_captures(captures: onig::Captures<'_>, keep_captures: bool) -> Option<Self> {
1409
        let (start, end) = captures.pos(0)?;
1410
        let captures = if keep_captures {
1411
            (0..captures.len())
1412
                .map(|index| captures.pos(index))
1413
                .collect()
1414
        } else {
1415
            Vec::new()
1416
        };
1417
        Some(Self {
1418
            start,
1419
            end,
1420
            captures,
1421
        })
1422
    }
1423
1424
    /// Returns the next byte position after this regex match.
1425
    pub(super) fn next_pos(&self, line: &str) -> usize {
1426
        next_pos_after(line, self.start, self.end)
1427
    }
1428
1429
    /// Returns the captured text for one group, or `None` when the group is unset.
1430
    pub(super) fn capture_text<'a>(&self, index: usize, line: &'a str) -> Option<&'a str> {
1431
        let (start, end) = self.captures.get(index)?.as_ref().copied()?;
1432
        line.get(start..end)
1433
    }
1434
1435
    /// Substitutes this match's captures into a regex template containing
1436
    /// backslash-prefixed numeric backreferences (`\1`, `\2`, …).
1437
    ///
1438
    /// Captured text is regex-escaped before substitution so that metacharacters
1439
    /// in the source line are matched literally on the next invocation.
1440
    pub(super) fn expand_backrefs(&self, template: &str, line: &str) -> String {
1441
        let mut resolved = String::new();
1442
        let mut chars = template.chars();
1443
        while let Some(ch) = chars.next() {
1444
            if ch != '\\' {
1445
                resolved.push(ch);
1446
                continue;
1447
            }
1448
            let Some(next) = chars.next() else {
1449
                resolved.push(ch);
1450
                break;
1451
            };
1452
            if let Some(index) = next.to_digit(10)
1453
                && let Some(text) = self.capture_text(index as usize, line)
1454
            {
1455
                push_regex_escaped(&mut resolved, text);
1456
            } else {
1457
                resolved.push(ch);
1458
                resolved.push(next);
1459
            }
1460
        }
1461
        resolved
1462
    }
1463
}
1464
1465
/// Appends `input` to `out`, escaping any regex metacharacters.
1466
fn push_regex_escaped(out: &mut String, input: &str) {
1467
    const META: &[char] = &[
1468
        '\\', '.', '+', '*', '?', '(', ')', '|', '[', ']', '{', '}', '^', '$',
1469
    ];
1470
    for ch in input.chars() {
1471
        if META.contains(&ch) {
1472
            out.push('\\');
1473
        }
1474
        out.push(ch);
1475
    }
1476
}
1477
1478
/// Returns a forward-progress position after a possibly-empty regex match.
1479
fn next_pos_after(line: &str, start: usize, end: usize) -> usize {
1480
    if end > start {
1481
        end
1482
    } else {
1483
        next_char_boundary(line, start.saturating_add(1))
1484
    }
1485
}
1486
1487
#[cfg(test)]
1488
#[allow(clippy::unwrap_used)]
1489
mod tests {
1490
    use std::str::FromStr;
1491
1492
    use super::*;
1493
1494
    #[test]
1495
    fn invalid_regex_offsets_are_ignored() {
1496
        let regex = Regex::new("\"").unwrap();
1497
        let anchors = AnchorState::new(true);
1498
1499
        assert!(
1500
            RegexMatch::find(&regex, r#"      "patterns": ["#, usize::MAX, true, anchors).is_none()
1501
        );
1502
        assert!(RegexMatch::find(&regex, "é", 1, true, anchors).is_none());
1503
    }
1504
1505
    #[test]
1506
    fn regex_match_offsets_are_absolute_after_full_line_search() {
1507
        let regex = Regex::new("(bar)").unwrap();
1508
        let matched = RegexMatch::find(&regex, "foobar", 3, true, AnchorState::new(true)).unwrap();
1509
1510
        assert_eq!(matched.start, 3);
1511
        assert_eq!(matched.end, 6);
1512
        assert_eq!(matched.captures[1], Some((3, 6)));
1513
    }
1514
1515
    #[test]
1516
    fn line_tokenizer_caches_dynamic_end_regexes() {
1517
        let grammar = Grammar::from_str(
1518
            r#"{
1519
                "name":"Demo",
1520
                "scopeName":"source.demo",
1521
                "patterns":[
1522
                    {
1523
                        "begin":"<([A-Za-z.]+)>",
1524
                        "end":"</\\1>",
1525
                        "name":"meta.tag.demo"
1526
                    }
1527
                ],
1528
                "repository":{}
1529
            }"#,
1530
        )
1531
        .unwrap();
1532
        let mut tokenizer = LineTokenizer::new(&grammar);
1533
        let mut state = LineState::default();
1534
        let mut spans = Vec::new();
1535
1536
        tokenizer.tokenize_line_into(&mut state, "<foo.bar>", &mut spans);
1537
        assert_eq!(tokenizer.end_regex_cache_len(), 1);
1538
1539
        tokenizer.tokenize_line_into(&mut state, "body", &mut spans);
1540
        assert_eq!(tokenizer.end_regex_cache_len(), 1);
1541
1542
        tokenizer.tokenize_line_into(&mut state, "</foo.bar>", &mut spans);
1543
        assert!(state.is_empty());
1544
        assert_eq!(tokenizer.end_regex_cache_len(), 1);
1545
    }
1546
}