highlight: Retokenize capture patterns

58ca2c6139c7a57e9ee57e3cb24ebac70e67e52d
Compile capture content names and nested patterns so captured text can
produce its own scopes. This covers TextMate grammars that attach
finer-grained tokenization to a capture instead of the parent match.
Alexis Sellier committed ago 1 parent c456f70e
crates/highlight/src/grammar/pattern.rs +170 -41
9 9
//! cached for subsequent lines.
10 10
11 11
use super::end::{EndPattern, EndRegex, EndRegexCache};
12 12
use super::*;
13 13
14 -
/// Capture-group index to scope path mapping.
15 -
pub(super) type Captures = BTreeMap<usize, Scope>;
14 +
/// Capture-group index to capture metadata mapping.
15 +
pub(super) type Captures = BTreeMap<usize, Capture>;
16 16
17 17
/// A scope assigned by a pattern.
18 18
#[derive(Clone, Debug, Eq, PartialEq)]
19 19
pub(super) enum Scope {
20 20
    /// Pattern names no scope.
23 23
    Visible(Vec<ScopeId>),
24 24
    /// Pattern names a structural scope used only to hold parser state.
25 25
    Structural(Vec<ScopeId>),
26 26
}
27 27
28 +
/// Compiled metadata for one capture group.
29 +
#[derive(Debug)]
30 +
pub(super) struct Capture {
31 +
    /// Scope assigned directly to the captured group.
32 +
    scope: Scope,
33 +
    /// Scope assigned to content retokenized inside the captured group.
34 +
    content_scope: Scope,
35 +
    /// Pattern set used to retokenize the captured group.
36 +
    nested: Option<PatternSetId>,
37 +
}
38 +
28 39
/// Capture-scope mappings for a pattern's three regex slots.
29 40
#[derive(Debug, Default)]
30 41
pub(super) struct PatternCaptures {
31 42
    /// Captures applied to a single match rule.
32 43
    pub(super) matched: Captures,
234 245
        name.push_visible(spans, start, end);
235 246
        content.push_visible(spans, start, end);
236 247
    }
237 248
}
238 249
250 +
impl Capture {
251 +
    /// Pushes this capture's direct and retokenized spans.
252 +
    fn push_spans(
253 +
        &self,
254 +
        spans: &mut Vec<ScopeSpan>,
255 +
        sets: &[PatternSet],
256 +
        line: &str,
257 +
        start: usize,
258 +
        end: usize,
259 +
        cache: &mut EndRegexCache,
260 +
        anchors: AnchorState,
261 +
    ) {
262 +
        self.scope.push_visible(spans, start, end);
263 +
        self.content_scope.push_visible(spans, start, end);
264 +
        let Some(nested) = self.nested else {
265 +
            return;
266 +
        };
267 +
        let mut pos = start;
268 +
        while pos < end {
269 +
            let Some(matched) = nested.find_next(sets, line, pos, end, cache, anchors) else {
270 +
                break;
271 +
            };
272 +
            if matched.start >= end {
273 +
                break;
274 +
            }
275 +
            let next_pos = matched.next_pos(line).min(end);
276 +
            spans.extend(
277 +
                matched
278 +
                    .spans
279 +
                    .into_iter()
280 +
                    .filter_map(|span| clamp_scope_span(span, end)),
281 +
            );
282 +
            pos = next_pos;
283 +
        }
284 +
    }
285 +
}
286 +
287 +
/// Clamps a span to a retokenized capture's end byte.
288 +
fn clamp_scope_span(mut span: ScopeSpan, end: usize) -> Option<ScopeSpan> {
289 +
    span.end = span.end.min(end);
290 +
    (span.start < span.end).then_some(span)
291 +
}
292 +
239 293
impl ScopeInterner {
240 294
    /// Returns the id for a scope, inserting it when needed.
241 295
    fn intern(&mut self, scope: &str) -> ScopeId {
242 296
        if let Some(id) = self.ids.get(scope) {
243 297
            return *id;
246 300
        self.scopes.push(scope.to_owned());
247 301
        self.ids.insert(scope.to_owned(), id);
248 302
        id
249 303
    }
250 304
251 -
    /// Converts raw capture maps into interned capture scopes.
252 -
    fn captures(&mut self, raw: Option<&BTreeMap<String, RawCapture>>) -> Captures {
253 -
        raw.into_iter()
254 -
            .flat_map(BTreeMap::iter)
255 -
            .filter_map(|(index, capture)| {
256 -
                let index = index.parse().ok()?;
257 -
                let name = capture.name.as_ref()?;
258 -
                let scope = Scope::from_raw(Some(name), self);
259 -
                Some((index, scope))
260 -
            })
261 -
            .collect()
262 -
    }
263 305
}
264 306
265 307
impl PatternSetId {
266 308
    /// Creates a pattern-set id from an arena index.
267 309
    pub(super) fn new(index: usize) -> Self {
277 319
    pub(super) fn find_next(
278 320
        self,
279 321
        sets: &[PatternSet],
280 322
        line: &str,
281 323
        pos: usize,
324 +
        limit: usize,
282 325
        cache: &mut EndRegexCache,
283 326
        anchors: AnchorState,
284 327
    ) -> Option<Match> {
285 328
        let mut active = Vec::new();
286 -
        self.find_next_inner(sets, line, pos, cache, anchors, &mut active)
329 +
        self.find_next_inner(sets, line, pos, limit, cache, anchors, &mut active)
287 330
    }
288 331
289 332
    /// Finds the next pattern match while carrying the active include stack.
290 333
    fn find_next_inner(
291 334
        self,
292 335
        sets: &[PatternSet],
293 336
        line: &str,
294 337
        pos: usize,
338 +
        limit: usize,
295 339
        cache: &mut EndRegexCache,
296 340
        anchors: AnchorState,
297 341
        active: &mut Vec<PatternSetId>,
298 342
    ) -> Option<Match> {
299 343
        if active.contains(&self) || active.len() > MAX_INCLUDE_DEPTH {
300 344
            return None;
301 345
        }
302 346
        active.push(self);
303 347
        let found = sets
304 348
            .get(self.index())
305 -
            .and_then(|set| set.find_next_inner(sets, line, pos, cache, anchors, active));
349 +
            .and_then(|set| set.find_next_inner(sets, line, pos, limit, cache, anchors, active));
306 350
        active.pop();
307 351
        found
308 352
    }
309 353
}
310 354
336 380
    fn find_next_inner(
337 381
        &self,
338 382
        sets: &[PatternSet],
339 383
        line: &str,
340 384
        pos: usize,
385 +
        limit: usize,
341 386
        cache: &mut EndRegexCache,
342 387
        anchors: AnchorState,
343 388
        active: &mut Vec<PatternSetId>,
344 389
    ) -> Option<Match> {
345 -
        if pos > line.len() || !line.is_char_boundary(pos) {
390 +
        if pos > limit || limit > line.len() || !line.is_char_boundary(pos) {
346 391
            return None;
347 392
        }
348 -
        let mut found = self.find_next_local(line, pos, cache, anchors);
393 +
        let mut found = self.find_next_local(sets, line, pos, limit, cache, anchors);
349 394
        for include in &self.includes {
350 -
            let Some(candidate) = include.find_next_inner(sets, line, pos, cache, anchors, active)
395 +
            let Some(candidate) =
396 +
                include.find_next_inner(sets, line, pos, limit, cache, anchors, active)
351 397
            else {
352 398
                continue;
353 399
            };
354 400
            found = match found {
355 401
                Some(current) if current.start <= candidate.start => Some(current),
360 406
    }
361 407
362 408
    /// Finds the next local pattern match at or after `pos`.
363 409
    fn find_next_local(
364 410
        &self,
411 +
        sets: &[PatternSet],
365 412
        line: &str,
366 413
        pos: usize,
414 +
        limit: usize,
367 415
        cache: &mut EndRegexCache,
368 416
        anchors: AnchorState,
369 417
    ) -> Option<Match> {
370 418
        let regexes = self.regexes.as_ref()?;
371 419
        let (entry, captures) = regexes.captures_with_options(
372 420
            line,
373 421
            pos,
374 -
            line.len(),
422 +
            limit,
375 423
            RegSetLead::Position,
376 424
            anchors.search_options(pos),
377 425
        )?;
378 426
        let pattern = self.patterns.get(entry)?;
379 427
        let regex_match = RegexMatch::from_captures(captures, pattern.needs_match_captures())?;
380 428
381 -
        pattern.match_result(regex_match, line, cache)
429 +
        pattern.match_result(regex_match, sets, line, cache)
382 430
    }
383 431
}
384 432
385 433
impl PatternCompiler<'_> {
386 434
    /// Creates a compiler for a raw grammar.
497 545
        };
498 546
        let nested = self.compile_nested_set(&pattern.patterns)?;
499 547
        let id = self.next_rule;
500 548
        self.next_rule += 1;
501 549
550 +
        let matched = self.captures(pattern.captures.as_ref())?;
551 +
        let begin = self.captures(pattern.begin_captures.as_ref().or(pattern.captures.as_ref()))?;
552 +
        let end = self.captures(pattern.end_captures.as_ref().or(pattern.captures.as_ref()))?;
553 +
        let while_rule =
554 +
            self.captures(pattern.while_captures.as_ref().or(pattern.captures.as_ref()))?;
555 +
502 556
        compiled.push(Pattern {
503 557
            id,
504 558
            scope,
505 559
            content_scope: Scope::from_raw(pattern.content_name.as_deref(), &mut self.interner),
506 560
            captures: PatternCaptures {
507 -
                matched: self.interner.captures(pattern.captures.as_ref()),
508 -
                begin: self
509 -
                    .interner
510 -
                    .captures(pattern.begin_captures.as_ref().or(pattern.captures.as_ref())),
511 -
                end: self
512 -
                    .interner
513 -
                    .captures(pattern.end_captures.as_ref().or(pattern.captures.as_ref())),
514 -
                while_rule: self
515 -
                    .interner
516 -
                    .captures(pattern.while_captures.as_ref().or(pattern.captures.as_ref())),
561 +
                matched,
562 +
                begin,
563 +
                end,
564 +
                while_rule,
517 565
            },
518 566
            body,
519 567
            nested,
520 568
        });
521 569
        Ok(())
580 628
        self.assign_set(id, set);
581 629
582 630
        Ok(Some(id))
583 631
    }
584 632
633 +
    /// Compiles capture metadata.
634 +
    fn captures(
635 +
        &mut self,
636 +
        raw: Option<&BTreeMap<String, RawCapture>>,
637 +
    ) -> Result<Captures, Error> {
638 +
        let mut captures = Captures::new();
639 +
        let Some(raw) = raw else {
640 +
            return Ok(captures);
641 +
        };
642 +
        for (index, capture) in raw {
643 +
            let Some(scope_index) = index.parse().ok() else {
644 +
                continue;
645 +
            };
646 +
            let nested = if capture.patterns.is_empty() {
647 +
                None
648 +
            } else {
649 +
                Some(self.compile_nested_set(&capture.patterns)?)
650 +
            };
651 +
            captures.insert(
652 +
                scope_index,
653 +
                Capture {
654 +
                    scope: Scope::from_raw(capture.name.as_deref(), &mut self.interner),
655 +
                    content_scope: Scope::from_raw(
656 +
                        capture.content_name.as_deref(),
657 +
                        &mut self.interner,
658 +
                    ),
659 +
                    nested,
660 +
                },
661 +
            );
662 +
        }
663 +
        Ok(captures)
664 +
    }
665 +
585 666
    /// Builds direct rule-id lookups after compilation.
586 667
    fn rule_locations(&self) -> Vec<Option<RuleLocation>> {
587 668
        let mut locations = vec![None; self.next_rule];
588 669
        for (set_index, set) in self.sets.iter().enumerate() {
589 670
            let set_id = PatternSetId::new(set_index);
649 730
    pub(super) fn append_match_spans(
650 731
        &self,
651 732
        matched: &RegexMatch,
652 733
        captures: &Captures,
653 734
        spans: &mut Vec<ScopeSpan>,
735 +
        sets: &[PatternSet],
736 +
        line: &str,
737 +
        cache: &mut EndRegexCache,
738 +
        anchors: AnchorState,
654 739
    ) {
655 740
        self.scope.push_visible(spans, matched.start, matched.end);
656 -
        for (index, scope) in captures {
741 +
        for (index, capture) in captures {
657 742
            if let Some(Some((start, end))) = matched.captures.get(*index)
658 743
                && start < end
659 744
            {
660 -
                scope.push_visible(spans, *start, *end);
745 +
                capture.push_spans(spans, sets, line, *start, *end, cache, anchors);
661 746
            }
662 747
        }
663 748
        spans.sort_by_key(|span| (span.start, span.end));
664 749
    }
665 750
687 772
688 773
    /// Builds a [`Match`] for one regex hit, dispatching by body kind.
689 774
    fn match_result(
690 775
        &self,
691 776
        regex_match: RegexMatch,
777 +
        sets: &[PatternSet],
692 778
        line: &str,
693 779
        cache: &mut EndRegexCache,
694 780
    ) -> Option<Match> {
695 781
        match &self.body {
696 -
            PatternBody::Match { .. } => Some(self.simple_match(regex_match)),
697 -
            PatternBody::BeginEnd { end, .. } => self.begin_match(end, regex_match, line, cache),
698 -
            PatternBody::BeginWhile { .. } => Some(self.begin_while_match(regex_match, line)),
782 +
            PatternBody::Match { .. } => {
783 +
                Some(self.simple_match(regex_match, sets, line, cache))
784 +
            }
785 +
            PatternBody::BeginEnd { end, .. } => {
786 +
                self.begin_match(end, regex_match, sets, line, cache)
787 +
            }
788 +
            PatternBody::BeginWhile { .. } => {
789 +
                Some(self.begin_while_match(regex_match, sets, line, cache))
790 +
            }
699 791
        }
700 792
    }
701 793
702 794
    /// Builds a match for a single-line match rule.
703 -
    fn simple_match(&self, regex_match: RegexMatch) -> Match {
795 +
    fn simple_match(
796 +
        &self,
797 +
        regex_match: RegexMatch,
798 +
        sets: &[PatternSet],
799 +
        line: &str,
800 +
        cache: &mut EndRegexCache,
801 +
    ) -> Match {
704 802
        let mut spans = Vec::new();
705 -
        self.append_match_spans(&regex_match, &self.captures.matched, &mut spans);
803 +
        self.append_match_spans(
804 +
            &regex_match,
805 +
            &self.captures.matched,
806 +
            &mut spans,
807 +
            sets,
808 +
            line,
809 +
            cache,
810 +
            AnchorState::new(false),
811 +
        );
706 812
        Match {
707 813
            start: regex_match.start,
708 814
            end: regex_match.end,
709 815
            spans,
710 816
            open_rule: None,
714 820
    /// Builds a match for a begin/end rule, eagerly closing on the same line if possible.
715 821
    fn begin_match(
716 822
        &self,
717 823
        end_pattern: &EndPattern,
718 824
        begin: RegexMatch,
825 +
        sets: &[PatternSet],
719 826
        line: &str,
720 827
        cache: &mut EndRegexCache,
721 828
    ) -> Option<Match> {
722 829
        let end_regex = end_pattern.resolve_for_begin(&begin, line, cache)?;
723 830
        let dynamic_end = end_regex.dynamic_source();
724 831
        let mut spans = Vec::new();
725 -
        self.append_match_spans(&begin, &self.captures.begin, &mut spans);
832 +
        self.append_match_spans(
833 +
            &begin,
834 +
            &self.captures.begin,
835 +
            &mut spans,
836 +
            sets,
837 +
            line,
838 +
            cache,
839 +
            AnchorState::new(false),
840 +
        );
726 841
727 842
        Some(Match {
728 843
            start: begin.start,
729 844
            end: begin.end,
730 845
            spans,
734 849
            }),
735 850
        })
736 851
    }
737 852
738 853
    /// Builds a match for a begin/while rule.
739 -
    fn begin_while_match(&self, begin: RegexMatch, line: &str) -> Match {
854 +
    fn begin_while_match(
855 +
        &self,
856 +
        begin: RegexMatch,
857 +
        sets: &[PatternSet],
858 +
        line: &str,
859 +
        cache: &mut EndRegexCache,
860 +
    ) -> Match {
740 861
        let mut spans = Vec::new();
741 862
        let end = begin.next_pos(line);
742 863
743 -
        self.append_match_spans(&begin, &self.captures.begin, &mut spans);
864 +
        self.append_match_spans(
865 +
            &begin,
866 +
            &self.captures.begin,
867 +
            &mut spans,
868 +
            sets,
869 +
            line,
870 +
            cache,
871 +
            AnchorState::new(false),
872 +
        );
744 873
        self.scope.push_visible(&mut spans, begin.start, end);
745 874
746 875
        Match {
747 876
            start: begin.start,
748 877
            end,
crates/highlight/src/grammar/tokenize.rs +24 -2
98 98
    ) -> usize {
99 99
        let Some(found) = self.grammar.patterns.find_next(
100 100
            &self.grammar.pattern_sets,
101 101
            line,
102 102
            pos,
103 +
            line.len(),
103 104
            &mut self.cache,
104 105
            *anchors,
105 106
        )
106 107
        else {
107 108
            return line.len();
138 139
        }
139 140
        let Some(end) = pattern.resume_end(open.dynamic_end.as_deref(), &mut self.cache) else {
140 141
            return self.advance_inside_while_rule(state, line, pos, spans, pattern, anchors);
141 142
        };
142 143
        self.next_event_inside(pattern, &end, line, pos, *anchors)
143 -
            .apply(state, line, pos, spans, pattern, anchors)
144 +
            .apply(
145 +
                state,
146 +
                line,
147 +
                pos,
148 +
                spans,
149 +
                pattern,
150 +
                &self.grammar.pattern_sets,
151 +
                &mut self.cache,
152 +
                anchors,
153 +
            )
144 154
    }
145 155
146 156
    /// Advances past one nested event inside an open begin/while rule.
147 157
    fn advance_inside_while_rule(
148 158
        &mut self,
155 165
    ) -> usize {
156 166
        let nested = pattern.nested.find_next(
157 167
            &self.grammar.pattern_sets,
158 168
            line,
159 169
            pos,
170 +
            line.len(),
160 171
            &mut self.cache,
161 172
            *anchors,
162 173
        );
163 174
        let Some(nested) = nested else {
164 175
            Scope::push_content_visible(
218 229
    ) -> InsideEvent {
219 230
        let nested = pattern.nested.find_next(
220 231
            &self.grammar.pattern_sets,
221 232
            line,
222 233
            pos,
234 +
            line.len(),
223 235
            &mut self.cache,
224 236
            anchors,
225 237
        );
226 238
        let close = pattern.find_end_match(end, line, pos, anchors);
227 239
267 279
        state: &mut LineState,
268 280
        line: &str,
269 281
        pos: usize,
270 282
        spans: &mut Vec<ScopeSpan>,
271 283
        pattern: &Pattern,
284 +
        sets: &[PatternSet],
285 +
        cache: &mut EndRegexCache,
272 286
        anchors: &mut AnchorState,
273 287
    ) -> usize {
274 288
        match self {
275 289
            Self::Close(close) => {
276 290
                Scope::push_content_visible(
278 292
                    &pattern.content_scope,
279 293
                    spans,
280 294
                    pos,
281 295
                    close.start,
282 296
                );
283 -
                pattern.append_match_spans(&close, &pattern.captures.end, spans);
297 +
                pattern.append_match_spans(
298 +
                    &close,
299 +
                    &pattern.captures.end,
300 +
                    spans,
301 +
                    sets,
302 +
                    line,
303 +
                    cache,
304 +
                    *anchors,
305 +
                );
284 306
                state.stack.pop();
285 307
                close.next_pos(line)
286 308
            }
287 309
            Self::Nested(nested) => {
288 310
                let next_pos = nested.next_pos_after_open(line);
crates/highlight/src/raw.rs +6 -0
77 77
/// A parsed, uncompiled TextMate capture.
78 78
#[derive(Clone, Debug, Deserialize)]
79 79
pub struct RawCapture {
80 80
    /// Scope assigned to the captured group.
81 81
    pub name: Option<String>,
82 +
    /// Scope assigned to retokenized captured content.
83 +
    #[serde(rename = "contentName")]
84 +
    pub content_name: Option<String>,
85 +
    /// Nested patterns used to retokenize the captured group.
86 +
    #[serde(default)]
87 +
    pub patterns: Vec<RawPattern>,
82 88
}
83 89
84 90
/// A parsed, uncompiled TextMate theme.
85 91
#[derive(Clone, Debug, Deserialize)]
86 92
pub struct RawTheme {
crates/highlight/src/tests.rs +60 -0
536 536
    assert!(style.contains(FontStyle::ITALIC));
537 537
    assert!(style.contains(FontStyle::UNDERLINE));
538 538
    assert!(style.contains(FontStyle::STRIKETHROUGH));
539 539
}
540 540
541 +
#[test]
542 +
fn capture_patterns_retokenize_captured_text() {
543 +
    let grammar = Grammar::from_str(
544 +
        r#"{
545 +
            "name":"Test",
546 +
            "scopeName":"source.test",
547 +
            "patterns":[
548 +
                {
549 +
                    "match":"value\\(([^)]*)\\)",
550 +
                    "captures":{
551 +
                        "1":{
552 +
                            "name":"meta.arguments.test",
553 +
                            "patterns":[{"match":"\\b[a-z]+\\b","name":"variable.parameter.test"}]
554 +
                        }
555 +
                    }
556 +
                }
557 +
            ],
558 +
            "repository":{}
559 +
        }"#,
560 +
    )
561 +
    .unwrap();
562 +
    let mut state = LineState::default();
563 +
564 +
    let spans = grammar.tokenize_line(&mut state, "value(alpha)");
565 +
    let scopes = scope_names(&grammar, &spans);
566 +
567 +
    assert!(scopes.contains(&"meta.arguments.test"));
568 +
    assert!(scopes.contains(&"variable.parameter.test"));
569 +
}
570 +
571 +
#[test]
572 +
fn capture_content_name_scopes_retokenized_text() {
573 +
    let grammar = Grammar::from_str(
574 +
        r#"{
575 +
            "name":"Test",
576 +
            "scopeName":"source.test",
577 +
            "patterns":[
578 +
                {
579 +
                    "match":"tag<([^>]*)>",
580 +
                    "captures":{
581 +
                        "1":{
582 +
                            "contentName":"meta.tag.content.test",
583 +
                            "patterns":[{"match":"\\w+","name":"entity.name.tag.test"}]
584 +
                        }
585 +
                    }
586 +
                }
587 +
            ],
588 +
            "repository":{}
589 +
        }"#,
590 +
    )
591 +
    .unwrap();
592 +
    let mut state = LineState::default();
593 +
594 +
    let spans = grammar.tokenize_line(&mut state, "tag<body>");
595 +
    let scopes = scope_names(&grammar, &spans);
596 +
597 +
    assert!(scopes.contains(&"meta.tag.content.test"));
598 +
    assert!(scopes.contains(&"entity.name.tag.test"));
599 +
}
600 +
541 601
#[test]
542 602
fn theme_matches_space_separated_scope_stacks() {
543 603
    let theme = r##"{
544 604
        "name":"Stack Theme",
545 605
        "settings":[